shared-context-ai 0.1.14 → 0.1.15

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.
Files changed (2) hide show
  1. package/dist/index.js +116 -172
  2. package/package.json +5 -1
package/dist/index.js CHANGED
@@ -1,67 +1,78 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ln=Object.create;var _t=Object.defineProperty;var un=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var dn=Object.getPrototypeOf,mn=Object.prototype.hasOwnProperty;var se=(n,e)=>()=>(n&&(e=n(n=0)),e);var je=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),vt=(n,e)=>{for(var t in e)_t(n,t,{get:e[t],enumerable:!0})},fn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pn(e))!mn.call(n,s)&&s!==t&&_t(n,s,{get:()=>e[s],enumerable:!(r=un(e,s))||r.enumerable});return n};var Q=(n,e,t)=>(t=n!=null?ln(dn(n)):{},fn(e||!n||!n.__esModule?_t(t,"default",{value:n,enumerable:!0}):t,n));var qe=je(Pt=>{"use strict";var Qe=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},jt=class extends Qe{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Pt.CommanderError=Qe;Pt.InvalidArgumentError=jt});var Ze=je(Rt=>{"use strict";var{InvalidArgumentError:hn}=qe(),Et=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new hn(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function gn(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Rt.Argument=Et;Rt.humanReadableArgName=gn});var Tt=je(It=>{"use strict";var{humanReadableArgName:yn}=Ze(),$t=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),o=r.long&&e._findOption(r.long);!s&&!o?t.push(r):r.long&&!o?t.push(e.createOption(r.long,r.description)):r.short&&!s&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(o=>!o.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>yn(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),s=t.helpWidth??80;function o(p,y){return t.formatItem(p,r,y,t)}let a=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],i=t.commandDescription(e);i.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(i),s),""]));let c=t.visibleArguments(e).map(p=>o(t.styleArgumentTerm(t.argumentTerm(p)),t.styleArgumentDescription(t.argumentDescription(p))));c.length>0&&(a=a.concat([t.styleTitle("Arguments:"),...c,""]));let l=t.visibleOptions(e).map(p=>o(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));if(l.length>0&&(a=a.concat([t.styleTitle("Options:"),...l,""])),t.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(y=>o(t.styleOptionTerm(t.optionTerm(y)),t.styleOptionDescription(t.optionDescription(y))));p.length>0&&(a=a.concat([t.styleTitle("Global Options:"),...p,""]))}let u=t.visibleCommands(e).map(p=>o(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));return u.length>0&&(a=a.concat([t.styleTitle("Commands:"),...u,""])),a.join(`
3
- `)}displayWidth(e){return xr(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,r,s){let a=" ".repeat(2);if(!r)return a+e;let i=e.padEnd(t+e.length-s.displayWidth(e)),c=2,u=(this.helpWidth??80)-t-c-2,p;return u<this.minWidthToWrap||s.preformatted(r)?p=r:p=s.boxWrap(r,u).replace(/\n/g,`
4
- `+" ".repeat(t+c)),a+i+" ".repeat(c)+p.replace(/\n/g,`
5
- ${a}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return r.forEach(a=>{let i=a.match(s);if(i===null){o.push("");return}let c=[i.shift()],l=this.displayWidth(c[0]);i.forEach(u=>{let p=this.displayWidth(u);if(l+p<=t){c.push(u),l+=p;return}o.push(c.join(""));let y=u.trimStart();c=[y],l=this.displayWidth(y)}),o.push(c.join(""))}),o.join(`
6
- `)}};function xr(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}It.Help=$t;It.stripColor=xr});var Mt=je(Nt=>{"use strict";var{InvalidArgumentError:bn}=qe(),Ft=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Sn(e);this.short=r.shortFlag,this.long=r.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}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new bn(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Or(this.name().replace(/^no-/,"")):Or(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Dt=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function Or(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Sn(n){let e,t,r=/^-[^-]$/,s=/^--[^-]/,o=n.split(/[ |,]+/).concat("guard");if(r.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&r.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let a=o[0],i=`option creation failed due to '${a}' in option flags '${n}'`;throw/^-[^-][^-]/.test(a)?new Error(`${i}
2
+ "use strict";var Oo=Object.create;var qt=Object.defineProperty;var ko=Object.getOwnPropertyDescriptor;var vo=Object.getOwnPropertyNames;var Ro=Object.getPrototypeOf,To=Object.prototype.hasOwnProperty;var he=(r,e)=>()=>(r&&(e=r(r=0)),e);var q=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),zt=(r,e)=>{for(var t in e)qt(r,t,{get:e[t],enumerable:!0})},Do=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of vo(e))!To.call(r,s)&&s!==t&&qt(r,s,{get:()=>e[s],enumerable:!(n=ko(e,s))||n.enumerable});return r};var ce=(r,e,t)=>(t=r!=null?Oo(Ro(r)):{},Do(e||!r||!r.__esModule?qt(t,"default",{value:r,enumerable:!0}):t,r));var ot=q(Jt=>{"use strict";var pt=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Zt=class extends pt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Jt.CommanderError=pt;Jt.InvalidArgumentError=Zt});var mt=q(Kt=>{"use strict";var{InvalidArgumentError:Po}=ot(),Xt=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Po(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function No(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Kt.Argument=Xt;Kt.humanReadableArgName=No});var er=q(Qt=>{"use strict";var{humanReadableArgName:jo}=mt(),Yt=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>jo(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth??80;function o(S,_){return t.formatItem(S,n,_,t)}let a=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],c=t.commandDescription(e);c.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(c),s),""]));let u=t.visibleArguments(e).map(S=>o(t.styleArgumentTerm(t.argumentTerm(S)),t.styleArgumentDescription(t.argumentDescription(S))));u.length>0&&(a=a.concat([t.styleTitle("Arguments:"),...u,""]));let l=t.visibleOptions(e).map(S=>o(t.styleOptionTerm(t.optionTerm(S)),t.styleOptionDescription(t.optionDescription(S))));if(l.length>0&&(a=a.concat([t.styleTitle("Options:"),...l,""])),t.showGlobalOptions){let S=t.visibleGlobalOptions(e).map(_=>o(t.styleOptionTerm(t.optionTerm(_)),t.styleOptionDescription(t.optionDescription(_))));S.length>0&&(a=a.concat([t.styleTitle("Global Options:"),...S,""]))}let h=t.visibleCommands(e).map(S=>o(t.styleSubcommandTerm(t.subcommandTerm(S)),t.styleSubcommandDescription(t.subcommandDescription(S))));return h.length>0&&(a=a.concat([t.styleTitle("Commands:"),...h,""])),a.join(`
3
+ `)}displayWidth(e){return Kr(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,s){let a=" ".repeat(2);if(!n)return a+e;let c=e.padEnd(t+e.length-s.displayWidth(e)),u=2,h=(this.helpWidth??80)-t-u-2,S;return h<this.minWidthToWrap||s.preformatted(n)?S=n:S=s.boxWrap(n,h).replace(/\n/g,`
4
+ `+" ".repeat(t+u)),a+c+" ".repeat(u)+S.replace(/\n/g,`
5
+ ${a}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(a=>{let c=a.match(s);if(c===null){o.push("");return}let u=[c.shift()],l=this.displayWidth(u[0]);c.forEach(h=>{let S=this.displayWidth(h);if(l+S<=t){u.push(h),l+=S;return}o.push(u.join(""));let _=h.trimStart();u=[_],l=this.displayWidth(_)}),o.push(u.join(""))}),o.join(`
6
+ `)}};function Kr(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}Qt.Help=Yt;Qt.stripColor=Kr});var sr=q(nr=>{"use strict";var{InvalidArgumentError:Lo}=ot(),tr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Fo(e);this.short=n.shortFlag,this.long=n.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}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Lo(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Yr(this.name().replace(/^no-/,"")):Yr(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},rr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function Yr(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Fo(r){let e,t,n=/^-[^-]$/,s=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let a=o[0],c=`option creation failed due to '${a}' in option flags '${r}'`;throw/^-[^-][^-]/.test(a)?new Error(`${c}
7
7
  - a short flag is a single dash and a single character
8
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')`):r.test(a)?new Error(`${i}
10
- - too many short flags`):s.test(a)?new Error(`${i}
11
- - too many long flags`):new Error(`${i}
12
- - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${n}'.`);return{shortFlag:e,longFlag:t}}Nt.Option=Ft;Nt.DualOptions=Dt});var vr=je(_r=>{"use strict";function wn(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let o=1;n[s-1]===e[r-1]?o=0:o=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+o),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function An(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(a=>a.slice(2)));let r=[],s=3,o=.4;return e.forEach(a=>{if(a.length<=1)return;let i=wn(n,a),c=Math.max(n.length,a.length);(c-i)/c>o&&(i<s?(s=i,r=[a]):i===s&&r.push(a))}),r.sort((a,i)=>a.localeCompare(i)),t&&(r=r.map(a=>`--${a}`)),r.length>1?`
13
- (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
14
- (Did you mean ${r[0]}?)`:""}_r.suggestSimilar=An});var Rr=je(Vt=>{"use strict";var Cn=require("events").EventEmitter,Lt=require("child_process"),ye=require("path"),et=require("fs"),D=require("process"),{Argument:kn,humanReadableArgName:xn}=Ze(),{CommanderError:Ht}=qe(),{Help:On,stripColor:_n}=Tt(),{Option:jr,DualOptions:vn}=Mt(),{suggestSimilar:Pr}=vr(),Wt=class n extends Cn{constructor(e){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=e||"",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:t=>D.stdout.write(t),writeErr:t=>D.stderr.write(t),outputError:(t,r)=>r(t),getOutHelpWidth:()=>D.stdout.isTTY?D.stdout.columns:void 0,getErrHelpWidth:()=>D.stderr.isTTY?D.stderr.columns:void 0,getOutHasColors:()=>Ut()??(D.stdout.isTTY&&D.stdout.hasColors?.()),getErrHasColors:()=>Ut()??(D.stderr.isTTY&&D.stderr.hasColors?.()),stripColor:t=>_n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let s=t,o=r;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,a,i]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(a);return s&&(c.description(s),c._executableHandler=!0),o.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(o.noHelp||o.hidden),c._executableFile=o.executableFile||null,i&&c.arguments(i),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new n(e)}createHelp(){return Object.assign(new On,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
15
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new kn(e,t)}argument(e,t,r,s){let o=this.createArgument(e,t);return typeof r=="function"?o.default(s).argParser(r):o.default(r),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",a=this.createCommand(r);return a.helpOption(!1),s&&a.arguments(s),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
- Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new Ht(e,t,r)),D.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,o=r.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new jr(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(o){if(o.code==="commander.invalidArgument"){let a=`${s} ${o.message}`;this.error(a,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
17
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(o,a,i)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let c=this.getOptionValue(r);o!==null&&e.parseArg?o=this._callParseArg(e,o,c,a):o!==null&&e.variadic&&(o=e._concatValue(o,c)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(r,o,i)};return this.on("option:"+t,o=>{let a=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let a=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,a,"env")}),this}_optionEx(e,t,r,s,o){if(typeof t=="object"&&t instanceof jr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,r);if(a.makeOptionMandatory(!!e.mandatory),typeof s=="function")a.default(o).argParser(s);else if(s instanceof RegExp){let i=s;s=(c,l)=>{let u=i.exec(c);return u?u[0]:l},a.default(o).argParser(s)}else a.default(s);return this.addOption(a)}option(e,t,r,s){return this._optionEx({},e,t,r,s)}requiredOption(e,t,r,s){return this._optionEx({mandatory:!0},e,t,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){D.versions?.electron&&(t.from="electron");let s=D.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=D.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":D.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new 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(e,t,r){if(et.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
19
- - if '${r}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(a)?new Error(`${c}
10
+ - too many short flags`):s.test(a)?new Error(`${c}
11
+ - too many long flags`):new Error(`${c}
12
+ - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}nr.Option=tr;nr.DualOptions=rr});var en=q(Qr=>{"use strict";function $o(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let o=1;r[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function Mo(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(a=>a.slice(2)));let n=[],s=3,o=.4;return e.forEach(a=>{if(a.length<=1)return;let c=$o(r,a),u=Math.max(r.length,a.length);(u-c)/u>o&&(c<s?(s=c,n=[a]):c===s&&n.push(a))}),n.sort((a,c)=>a.localeCompare(c)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
13
+ (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
14
+ (Did you mean ${n[0]}?)`:""}Qr.suggestSimilar=Mo});var sn=q(lr=>{"use strict";var Ho=require("events").EventEmitter,or=require("child_process"),ke=require("path"),ht=require("fs"),$=require("process"),{Argument:Uo,humanReadableArgName:Bo}=mt(),{CommanderError:ir}=ot(),{Help:Wo,stripColor:Vo}=er(),{Option:tn,DualOptions:Go}=sr(),{suggestSimilar:rn}=en(),ar=class r extends Ho{constructor(e){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=e||"",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:t=>$.stdout.write(t),writeErr:t=>$.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>$.stdout.isTTY?$.stdout.columns:void 0,getErrHelpWidth:()=>$.stderr.isTTY?$.stderr.columns:void 0,getOutHasColors:()=>cr()??($.stdout.isTTY&&$.stdout.hasColors?.()),getErrHasColors:()=>cr()??($.stderr.isTTY&&$.stderr.hasColors?.()),stripColor:t=>Vo(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,a,c]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(a);return s&&(u.description(s),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,c&&u.arguments(c),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Wo,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Uo(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",a=this.createCommand(n);return a.helpOption(!1),s&&a.arguments(s),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new ir(e,t,n)),$.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new tn(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let a=`${s} ${o.message}`;this.error(a,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
17
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,a,c)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,a):o!==null&&e.variadic&&(o=e._concatValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,c)};return this.on("option:"+t,o=>{let a=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let a=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,a,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof tn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof s=="function")a.default(o).argParser(s);else if(s instanceof RegExp){let c=s;s=(u,l)=>{let h=c.exec(u);return h?h[0]:l},a.default(o).argParser(s)}else a.default(s);return this.addOption(a)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){$.versions?.electron&&(t.from="electron");let s=$.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=$.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":$.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new 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(e,t,n){if(ht.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
19
+ - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
20
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
- - ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(u,p){let y=ye.resolve(u,p);if(et.existsSync(y))return y;if(s.includes(ye.extname(p)))return;let g=s.find(S=>et.existsSync(`${y}${S}`));if(g)return`${y}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,i=this._executableDir||"";if(this._scriptPath){let u;try{u=et.realpathSync(this._scriptPath)}catch{u=this._scriptPath}i=ye.resolve(ye.dirname(u),i)}if(i){let u=o(i,a);if(!u&&!e._executableFile&&this._scriptPath){let p=ye.basename(this._scriptPath,ye.extname(this._scriptPath));p!==this._name&&(u=o(i,`${p}-${e._name}`))}a=u||a}r=s.includes(ye.extname(a));let c;D.platform!=="win32"?r?(t.unshift(a),t=Er(D.execArgv).concat(t),c=Lt.spawn(D.argv[0],t,{stdio:"inherit"})):c=Lt.spawn(a,t,{stdio:"inherit"}):(this._checkForMissingExecutable(a,i,e._name),t.unshift(a),t=Er(D.execArgv).concat(t),c=Lt.spawn(D.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{D.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new Ht(u,"commander.executeSubCommandAsync","(close)")):D.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(a,i,e._name);else if(u.code==="EACCES")throw new Error(`'${a}' not executable`);if(!l)D.exit(1);else{let p=new Ht(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),this.runningCommand=c}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,o)=>{let a=s;if(s!==null&&r.parseArg){let i=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;a=this._callParseArg(r,s,o,i)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let o=r.defaultValue;r.variadic?s<this.args.length?(o=this.args.slice(s),r.parseArg&&(o=o.reduce((a,i)=>e(r,i,a),r.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],r.parseArg&&(o=e(r,o,r.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(a=>{s.push({hookedCommand:o,callback:a})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{r=this._chainOrCall(r,()=>o.callback(o.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(o,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(o=>r.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],s=t,o=e.slice();function a(c){return c.length>1&&c[0]==="-"}let i=null;for(;o.length;){let c=o.shift();if(c==="--"){s===r&&s.push(c),s.push(...o);break}if(i&&!a(c)){this.emit(`option:${i.name()}`,c);continue}if(i=null,a(c)){let l=this._findOption(c);if(l){if(l.required){let u=o.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;o.length>0&&!a(o[0])&&(u=o.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);i=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),o.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(a(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(c)){t.push(c),o.length>0&&r.push(...o);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){r.push(c),o.length>0&&r.push(...o);break}}if(this._passThroughOptions){s.push(c),o.length>0&&s.push(...o);break}s.push(c)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
21
+ - ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(h,S){let _=ke.resolve(h,S);if(ht.existsSync(_))return _;if(s.includes(ke.extname(S)))return;let d=s.find(m=>ht.existsSync(`${_}${m}`));if(d)return`${_}${d}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let h;try{h=ht.realpathSync(this._scriptPath)}catch{h=this._scriptPath}c=ke.resolve(ke.dirname(h),c)}if(c){let h=o(c,a);if(!h&&!e._executableFile&&this._scriptPath){let S=ke.basename(this._scriptPath,ke.extname(this._scriptPath));S!==this._name&&(h=o(c,`${S}-${e._name}`))}a=h||a}n=s.includes(ke.extname(a));let u;$.platform!=="win32"?n?(t.unshift(a),t=nn($.execArgv).concat(t),u=or.spawn($.argv[0],t,{stdio:"inherit"})):u=or.spawn(a,t,{stdio:"inherit"}):(this._checkForMissingExecutable(a,c,e._name),t.unshift(a),t=nn($.execArgv).concat(t),u=or.spawn($.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(S=>{$.on(S,()=>{u.killed===!1&&u.exitCode===null&&u.kill(S)})});let l=this._exitCallback;u.on("close",h=>{h=h??1,l?l(new ir(h,"commander.executeSubCommandAsync","(close)")):$.exit(h)}),u.on("error",h=>{if(h.code==="ENOENT")this._checkForMissingExecutable(a,c,e._name);else if(h.code==="EACCES")throw new Error(`'${a}' not executable`);if(!l)$.exit(1);else{let S=new ir(1,"commander.executeSubCommandAsync","(error)");S.nestedError=h,l(S)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,o)=>{let a=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,s,o,c)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((a,c)=>e(n,c,a),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(a=>{s.push({hookedCommand:o,callback:a})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(o,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function a(u){return u.length>1&&u[0]==="-"}let c=null;for(;o.length;){let u=o.shift();if(u==="--"){s===n&&s.push(u),s.push(...o);break}if(c&&!a(u)){this.emit(`option:${c.name()}`,u);continue}if(c=null,a(u)){let l=this._findOption(u);if(l){if(l.required){let h=o.shift();h===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,h)}else if(l.optional){let h=null;o.length>0&&!a(o[0])&&(h=o.shift()),this.emit(`option:${l.name()}`,h)}else this.emit(`option:${l.name()}`);c=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,u.slice(2)):(this.emit(`option:${l.name()}`),o.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),h=this._findOption(u.slice(0,l));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,u.slice(l+1));continue}}if(a(u)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(u),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(u),o.length>0&&s.push(...o);break}s.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
- `),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,o=r.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in D.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,D.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new vn(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=a=>{let i=a.attributeName(),c=this.getOptionValue(i),l=this.options.find(p=>p.negate&&i===p.attributeName()),u=this.options.find(p=>!p.negate&&i===p.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||a},s=a=>{let i=r(a),c=i.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${i.envVar}'`:`option '${i.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let a=o.createHelp().visibleOptions(o).filter(i=>i.long).map(i=>i.long);s=s.concat(a),o=o.parent}while(o&&!o._enablePositionalOptions);t=Pr(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=Pr(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>xn(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ye.basename(e,ye.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),r=this._getOutputContext(e);t.prepareContext({error:r.error,helpWidth:r.helpWidth,outputHasColors:r.hasColors});let s=t.formatHelp(this,t);return r.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,r,s,o;return t?(r=i=>this._outputConfiguration.writeErr(i),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(r=i=>this._outputConfiguration.writeOut(i),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:i=>(s||(i=this._outputConfiguration.stripColor(i)),r(i)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getOutputContext(e),s={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach(a=>a.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:r.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(a=>a.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(D.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
- Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let a;typeof t=="function"?a=t({error:o.error,command:o.command}):a=t,a&&o.write(`${a}
27
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Er(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:r=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],r=o[3],s=o[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}function Ut(){if(D.env.NO_COLOR||D.env.FORCE_COLOR==="0"||D.env.FORCE_COLOR==="false")return!1;if(D.env.FORCE_COLOR||D.env.CLICOLOR_FORCE!==void 0)return!0}Vt.Command=Wt;Vt.useColor=Ut});var Fr=je(ie=>{"use strict";var{Argument:$r}=Ze(),{Command:Bt}=Rr(),{CommanderError:jn,InvalidArgumentError:Ir}=qe(),{Help:Pn}=Tt(),{Option:Tr}=Mt();ie.program=new Bt;ie.createCommand=n=>new Bt(n);ie.createOption=(n,e)=>new Tr(n,e);ie.createArgument=(n,e)=>new $r(n,e);ie.Command=Bt;ie.Option=Tr;ie.Argument=$r;ie.Help=Pn;ie.CommanderError=jn;ie.InvalidArgumentError=Ir;ie.InvalidOptionArgumentError=Ir});var zt={};vt(zt,{addToManifest:()=>te,clearAuth:()=>Jt,getAuth:()=>ae,getConfig:()=>Ae,getManifest:()=>Y,getSyncState:()=>nt,removeFromManifest:()=>st,saveAuth:()=>Gt,saveConfig:()=>qr,saveManifest:()=>Yt,saveSyncState:()=>Fe,shouldSync:()=>Kt,updateConfig:()=>$n});function Ge(){let n=process.env.SC_PROFILE;return n?(0,Pe.join)(Wr,"profiles",n):Wr}function qt(){return(0,Pe.join)(Ge(),"auth.json")}function Vr(){return(0,Pe.join)(Ge(),"config.json")}function Br(){return(0,Pe.join)(Ge(),"manifest.json")}function En(){(0,le.mkdirSync)(Ge(),{recursive:!0})}function tt(n,e){try{return(0,le.existsSync)(n)?JSON.parse((0,le.readFileSync)(n,"utf-8")):e}catch{return e}}function rt(n,e,t=!1){if(En(),(0,le.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
- `,"utf-8"),t)try{(0,le.chmodSync)(n,384)}catch{}}function ae(){return tt(qt(),null)}function Gt(n){rt(qt(),n,!0)}function Jt(){try{(0,le.writeFileSync)(qt(),"{}","utf-8")}catch{}}function Ae(){return tt(Vr(),Rn)}function qr(n){rt(Vr(),n)}function $n(n){let e=Ae();qr({...e,...n})}function Y(){return tt(Br(),In)}function Yt(n){rt(Br(),n)}function te(n){let e=Y(),t=e.installations.findIndex(r=>r.resourceId===n.resourceId&&r.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),Yt(e)}function st(n,e){let t=Y();t.installations=t.installations.filter(r=>!(r.resourceId===n&&(!e||r.agent===e))),Yt(t)}function Gr(){return(0,Pe.join)(Ge(),"last-sync.json")}function nt(){return tt(Gr(),null)}function Fe(n){rt(Gr(),n)}function Kt(n=Tn){let e=nt();return e?.lastSyncAt?Date.now()-new Date(e.lastSyncAt).getTime()>=n:!0}var le,Pe,Ur,Wr,Rn,In,Tn,re=se(()=>{"use strict";le=require("fs"),Pe=require("path"),Ur=require("os"),Wr=(0,Pe.join)((0,Ur.homedir)(),".config","shared-context");Rn={apiBase:"https://sharedcontext.ai"};In={installations:[]};Tn=720*60*1e3});var Jr={};vt(Jr,{del:()=>Xt,get:()=>U,isAuthenticated:()=>N,patch:()=>Nn,post:()=>T});function Fn(){return Ae().apiBase||"https://sharedcontext.ai"}function Dn(){let n={"Content-Type":"application/json"},e=ae();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function N(){return!!ae()?.token}async function ot(n,e,t,r){let s=`${Fn()}${e}`;try{let o={method:n,headers:Dn(),body:t?JSON.stringify(t):void 0};r&&(o.signal=AbortSignal.timeout(r));let a=await fetch(s,o),i=a.headers.get("content-type")||"";if(!i.includes("application/json"))return a.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${i||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${a.status}`,message:a.statusText}};let c=await a.json();return a.ok?{ok:!0,data:c.data??c}:{ok:!1,error:{code:c?.error?.code||`HTTP_${a.status}`,message:c?.error?.message||c?.message||a.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function U(n){return ot("GET",n)}function T(n,e,t){return ot("POST",n,e,t)}function Nn(n,e){return ot("PATCH",n,e)}function Xt(n,e){return ot("DELETE",n,e)}var K=se(()=>{"use strict";re()});function fo(){try{return nr.default.statSync("/.dockerenv"),!0}catch{return!1}}function ho(){try{return nr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function or(){return sr===void 0&&(sr=fo()||ho()),sr}var nr,sr,cs=se(()=>{"use strict";nr=Q(require("fs"),1)});function Te(){return ir===void 0&&(ir=go()||or()),ir}var ls,ir,go,ar=se(()=>{"use strict";ls=Q(require("fs"),1);cs();go=()=>{try{return ls.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var cr,ps,St,us,xe,lr=se(()=>{"use strict";cr=Q(require("process"),1),ps=Q(require("os"),1),St=Q(require("fs"),1);ar();us=()=>{if(cr.default.platform!=="linux")return!1;if(ps.default.release().toLowerCase().includes("microsoft"))return!Te();try{if(St.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!Te()}catch{}return St.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||St.default.existsSync("/run/WSL")?!Te():!1},xe=cr.default.env.__IS_WSL_TEST__?us:us()});var ur,Ke,yo,bo,pr,ds=se(()=>{"use strict";ur=Q(require("process"),1),Ke=Q(require("fs/promises"),1);lr();lr();yo=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",r=!1;try{await Ke.default.access(t,Ke.constants.F_OK),r=!0}catch{}if(!r)return n;let s=await Ke.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):n}})(),bo=async()=>`${await yo()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,pr=async()=>xe?bo():`${ur.default.env.SYSTEMROOT||ur.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Oe(n,e,t){let r=s=>Object.defineProperty(n,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get(){let s=t();return r(s),s},set(s){r(s)}}),n}var ms=se(()=>{"use strict"});async function dr(){if(hs.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await So("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(n)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var fs,hs,gs,So,ys=se(()=>{"use strict";fs=require("util"),hs=Q(require("process"),1),gs=require("child_process"),So=(0,fs.promisify)(gs.execFile)});async function ws(n,{humanReadableOutput:e=!0,signal:t}={}){if(bs.default.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await wo("osascript",["-e",n,r],s);return o.trim()}var bs,Ss,mr,wo,As=se(()=>{"use strict";bs=Q(require("process"),1),Ss=require("util"),mr=require("child_process"),wo=(0,Ss.promisify)(mr.execFile)});async function fr(n){return ws(`tell application "Finder" to set app_path to application file id "${n}" as string
29
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Cs=se(()=>{"use strict";As()});async function gr(n=Ao){let{stdout:e}=await n("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new hr(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,s=r.lastIndexOf("."),o=r.lastIndexOf("-"),a=s===-1?void 0:r.slice(0,s),i=o===-1?void 0:r.slice(0,o);return wt[r]??wt[a]??wt[i]??{name:r,id:r}}var ks,xs,Ao,wt,oa,hr,Os=se(()=>{"use strict";ks=require("util"),xs=require("child_process"),Ao=(0,ks.promisify)(xs.execFile),wt={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},oa=new Map(Object.entries(wt)),hr=class extends Error{}});async function yr(){if(At.default.platform==="darwin"){let n=await dr();return{name:await fr(n),id:n}}if(At.default.platform==="linux"){let{stdout:n}=await Co("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:ko(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(At.default.platform==="win32")return gr();throw new Error("Only macOS, Linux, and Windows are supported")}var _s,At,vs,Co,ko,js=se(()=>{"use strict";_s=require("util"),At=Q(require("process"),1),vs=require("child_process");ys();Cs();Os();Co=(0,_s.promisify)(vs.execFile),ko=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Fs={};vt(Fs,{apps:()=>_e,default:()=>jo,openApp:()=>vo});async function Oo(){let n=await pr(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=wr.Buffer.from(e,"utf16le").toString("base64"),{stdout:r}=await xo(n,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=r.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function $s(n){if(typeof n=="string"||Array.isArray(n))return n;let{[Es]:e}=n;if(!e)throw new Error(`${Es} is not supported`);return e}function kt({[Ve]:n},{wsl:e}){if(e&&xe)return $s(e);if(!n)throw new Error(`${Ve} is not supported`);return $s(n)}var Sr,wr,Ar,Is,Ts,Cr,Ct,Po,xo,br,Ps,Ve,Es,Rs,ze,_o,vo,_e,jo,Ds=se(()=>{"use strict";Sr=Q(require("process"),1),wr=require("buffer"),Ar=Q(require("path"),1),Is=require("url"),Ts=require("util"),Cr=Q(require("child_process"),1),Ct=Q(require("fs/promises"),1);ds();ms();js();ar();Po={},xo=(0,Ts.promisify)(Cr.default.execFile),br=Ar.default.dirname((0,Is.fileURLToPath)(Po.url)),Ps=Ar.default.join(br,"xdg-open"),{platform:Ve,arch:Es}=Sr.default;Rs=async(n,e)=>{let t;for(let r of n)try{return await e(r)}catch(s){t=s}throw t},ze=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return Rs(n.app,i=>ze({...n,app:i}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return Rs(e,i=>ze({...n,app:{name:i,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let i={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},c={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=xe?await Oo():await yr();if(l.id in i){let u=i[l.id];return e==="browserPrivate"&&t.push(c[u]),ze({...n,app:{name:_e[u],arguments:t}})}throw new Error(`${l.name} is not supported as a default browser`)}let r,s=[],o={};if(Ve==="darwin")r="open",n.wait&&s.push("--wait-apps"),n.background&&s.push("--background"),n.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(Ve==="win32"||xe&&!Te()&&!e){r=await pr(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),xe||(o.windowsVerbatimArguments=!0);let i=["Start"];n.wait&&i.push("-Wait"),e?(i.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&i.push(`"${n.target}"`),t.length>0&&(t=t.map(c=>`"\`"${c}\`""`),i.push("-ArgumentList",t.join(","))),n.target=wr.Buffer.from(i.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let i=!br||br==="/",c=!1;try{await Ct.default.access(Ps,Ct.constants.X_OK),c=!0}catch{}r=Sr.default.versions.electron??(Ve==="android"||i||!c)?"xdg-open":Ps}t.length>0&&s.push(...t),n.wait||(o.stdio="ignore",o.detached=!0)}Ve==="darwin"&&t.length>0&&s.push("--args",...t),n.target&&s.push(n.target);let a=Cr.default.spawn(r,s,o);return n.wait?new Promise((i,c)=>{a.once("error",c),a.once("close",l=>{if(!n.allowNonzeroExitCode&&l>0){c(new Error(`Exited with code ${l}`));return}i(a)})}):(a.unref(),a)},_o=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return ze({...e,target:n})},vo=(n,e)=>{if(typeof n!="string"&&!Array.isArray(n))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return ze({...e,app:{name:n,arguments:t}})};_e={};Oe(_e,"chrome",()=>kt({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Oe(_e,"brave",()=>kt({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Oe(_e,"firefox",()=>kt({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Oe(_e,"edge",()=>kt({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Oe(_e,"browser",()=>"browser");Oe(_e,"browserPrivate",()=>"browserPrivate");jo=_o});var Dr=Q(Fr(),1),{program:Wo,createCommand:Uo,createArgument:Vo,createOption:Bo,CommanderError:qo,InvalidArgumentError:Go,InvalidOptionArgumentError:Jo,Command:Nr,Argument:Yo,Option:Ko,Help:zo}=Dr.default;var Mr=!1,Lr=!1;function Hr(n,e){Mr=n,Lr=e}function b(){return Mr?!0:Lr?!1:!process.stdout.isTTY}function I(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function j(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function m(n){console.log(n)}function x(n){console.error(n)}function ne(n,e=2){if(n.length===0)return"";let t=[];for(let r of n)for(let s=0;s<r.length;s++)t[s]=Math.max(t[s]||0,r[s].length);return n.map(r=>r.map((s,o)=>o<r.length-1?s.padEnd(t[o]+e):s).join("")).join(`
30
- `)}var bt=require("fs"),Ie=require("path"),is=require("os");re();K();var Qt=require("fs"),oe=require("path"),Ce=require("os"),De=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function pe(n){if(n){let r=De.find(o=>o.id===n);if(r)return r;let s=De.find(o=>o.dir===`.${n}`||o.dir===n);return s||null}for(let r of De)if(r.envVars.some(s=>process.env[s]))return r;let e=(0,Ce.homedir)(),t=[];for(let r of De)(0,Qt.existsSync)((0,oe.join)(e,r.dir))&&t.push(r);return t.length===1?t[0]:null}function Ne(){let n=[],e=(0,Ce.homedir)();for(let t of De)(t.envVars.some(r=>process.env[r])||(0,Qt.existsSync)((0,oe.join)(e,t.dir)))&&n.push(t);return n}function de(){let n=Ne();return n.length>1?`Multiple AI agents detected (${n.map(e=>e.label).join(", ")}). Use --agent to specify: ${n.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${De.map(e=>e.id).join(", ")})`}function M(n,e){return e?(0,oe.join)(process.cwd(),n.dir,n.skillsSubdir):(0,oe.join)((0,Ce.homedir)(),n.dir,n.skillsSubdir)}function z(n,e){return e?(0,oe.join)(process.cwd(),n.dir,"agents"):(0,oe.join)((0,Ce.homedir)(),n.dir,"agents")}function B(n,e){return e?(0,oe.join)(process.cwd(),".mcp.json"):n.id==="claude-code"?(0,oe.join)((0,Ce.homedir)(),".claude.json"):n.id==="cursor"?(0,oe.join)((0,Ce.homedir)(),".cursor","mcp.json"):(0,oe.join)(process.cwd(),".mcp.json")}function Z(n,e){return e?(0,oe.join)(process.cwd(),n.dir,"settings.json"):(0,oe.join)((0,Ce.homedir)(),n.dir,"settings.json")}var G=require("fs"),Ee=require("path");var he=require("fs"),fe=require("path");K();re();var ke=require("fs"),it=require("path"),Yr=".shared-context",Kr="project.json";function me(){let n=(0,it.join)(process.cwd(),Yr,Kr);if(!(0,ke.existsSync)(n))return null;try{let e=JSON.parse((0,ke.readFileSync)(n,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function Je(n){let e=(0,it.join)(process.cwd(),Yr);(0,ke.mkdirSync)(e,{recursive:!0}),(0,ke.writeFileSync)((0,it.join)(e,Kr),JSON.stringify(n,null,2)+`
31
- `,"utf-8")}var Xr={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function W(n,e){let t=(0,fe.resolve)(n);for(let r of e){let s=(0,fe.resolve)((0,fe.join)(n,r.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${r.path}`);(0,he.mkdirSync)((0,fe.dirname)(s),{recursive:!0}),(0,he.writeFileSync)(s,r.content,"utf-8")}}function Mn(n){let e=n.resource.slug||n.resource.id,t=Xr[n.resource.resourceType]||n.resource.resourceType+"s";return n.resource.storageType==="github"&&n.resource.githubOwner?`${t}/external/${n.resource.githubOwner}/${e}`:n.resource.orgSlug?`${t}/${n.resource.orgSlug}/${e}`:`${t}/${e}`}function zr(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function Zt(n,e,t){let r=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"))||t.files.find(l=>l.path.endsWith(".json")&&l.path.includes("resources/"));if(!r)throw new Error("MCP package does not contain a config file");let s=JSON.parse(r.content),o=B(n,e),a=t.resource.slug||t.resource.id,i={};if((0,he.existsSync)(o))try{i=JSON.parse((0,he.readFileSync)(o,"utf-8"))}catch{i={}}let c=typeof i.mcpServers=="object"&&i.mcpServers&&!Array.isArray(i.mcpServers)?i.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(c,s.mcpServers):c[a]=s,i.mcpServers=c,(0,he.mkdirSync)((0,fe.dirname)(o),{recursive:!0}),(0,he.writeFileSync)(o,JSON.stringify(i,null,2)+`
32
- `,"utf-8")}function Ln(n,e,t,r){let s=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),a=Z(n,e),i={},c=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:o;for(let[l,u]of Object.entries(c))if(!(l==="name"||l==="description")&&Array.isArray(u)){i[l]||(i[l]=[]);for(let p of u)i[l].push(p)}if(Object.keys(i).length===0)throw new Error("Hook package does not contain any hook event handlers");return er(a,i,r),a}function Qr(n){n.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),o=pe(s.agent);if(!o){let f=de();b()?j("install","NO_AGENTS",f):x(f),process.exit(1)}let a=N(),c=await U(`${a?"/api/cli/resource":"/api/public/resource"}/${e}`);c.ok||(b()?j("install",c.error.code,c.error.message):x(`Install failed: ${c.error.message}`),process.exit(1));let l=c.data,u=l.resource.slug||l.resource.id,p=Mn(l),y;if(l.resource.resourceType==="agent"){let f=z(o,!!s.project);y=(0,fe.join)(f,...zr(l));try{W(y,l.files)}catch(A){b()?j("install","WRITE_FAILED",`Failed to write files: ${A}`):x(`Failed to write files: ${A}`),process.exit(1)}}else if(l.resource.resourceType==="mcp"){y="";try{Zt(o,!!s.project,l)}catch(f){b()?j("install","WRITE_FAILED",`Failed to install MCP config: ${f}`):x(`Failed to install MCP config: ${f}`),process.exit(1)}}else if(l.resource.resourceType==="hook"){y="";try{Ln(o,!!s.project,l,p)}catch(f){b()?j("install","WRITE_FAILED",`Failed to install hook config: ${f}`):x(`Failed to install hook config: ${f}`),process.exit(1)}}else{let f=M(o,!!s.project);y=(0,fe.join)(f,...zr(l));try{if(l.resource.resourceType==="collection"){let O=await be(o).install(l,s.project?"project":"user",o);if(y=O.installDir,!b())for(let C of O.warnings)x(`Warning: ${C}`)}else W(y,l.files)}catch(A){b()?j("install","WRITE_FAILED",`Failed to write files: ${A}`):x(`Failed to write files: ${A}`),process.exit(1)}}let g;if(a&&l.resource.latestSha){let f=await T("/api/cli/install",{resourceId:l.resource.id,agentPlatform:o.platform,installedSha:l.resource.latestSha});f.ok||(g=`Could not record install on server: ${f.error.message}`,b()||x(`Warning: ${g}`))}let S=s.project?me():null;S&&a&&await T(`/api/cli/projects/${S.projectId}/resources`,{resourceId:l.resource.id}).catch(()=>{});let d={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},h=l.resource.resourceType==="collection";if(te({resourceId:l.resource.id,slug:u,installPath:p,title:l.resource.title,sha:l.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),...h?{pluginFormat:d[o.id]||"directory",memberCount:l.memberResources?.length}:{},...S?{projectId:S.projectId}:{}}),l.memberResources&&l.resource.resourceType==="collection")for(let f of l.memberResources){let A=f.slug||f.id,O=Xr[f.resourceType]||f.resourceType+"s",C=f.orgSlug||l.resource.orgSlug,w=C?`${O}/${C}/${A}`:`${O}/${A}`;te({resourceId:f.id,slug:A,installPath:w,title:f.title,sha:f.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:l.resource.id}),a&&f.latestSha&&await T("/api/cli/install",{resourceId:f.id,agentPlatform:o.platform,installedSha:f.latestSha}).catch(()=>{})}if(b())I("install",{installPath:p,title:l.resource.title,path:y||void 0,files:l.files.length,...l.resource.resourceType==="mcp"?{mcpConfigPath:B(o,!!s.project)}:{},...l.resource.resourceType==="hook"?{settingsPath:Z(o,!!s.project)}:{},...l.memberResources?{memberResources:l.memberResources.map(f=>({title:f.title,resourceType:f.resourceType,slug:f.slug}))}:{},...g&&{warning:g}});else{if(l.resource.resourceType==="mcp"?m(`Installed MCP "${l.resource.title}" to ${B(o,!!s.project)}`):l.resource.resourceType==="hook"?m(`Installed hook "${l.resource.title}" to ${Z(o,!!s.project)}`):l.memberResources&&l.memberResources.length>0?m(`Installed "${l.resource.title}" (${l.memberResources.length} resources)`):m(`Installed "${l.resource.title}" to ${y}`),l.resource.resourceType!=="mcp"&&l.resource.resourceType!=="hook"&&!(l.memberResources&&l.memberResources.length>0)&&m(` ${l.files.length} file${l.files.length===1?"":"s"} written`),l.memberResources&&l.memberResources.length>0){let f={};for(let O of l.memberResources){let C=O.resourceType||"other";f[C]||(f[C]=[]),f[C].push(O.title)}let A={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};m("");for(let[O,C]of Object.entries(f)){let w=A[O]||O;m(` ${w}: ${C.join(", ")}`)}}a||(m(""),m("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var at=class{buildFiles(e){let t=[],r=[],s=[],o={},a={};for(let i of e.files){let c=i.path.split("/"),l=c[0];if(l==="agents")s.push({path:i.path.slice(7),content:i.content});else if(l==="mcps"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(o,u.mcpServers);else if(i.path.includes("resources/")){let p=c.indexOf("resources"),y=p>0?c[p-1]:c[1];o[y]=u}}catch{t.push(`Failed to parse MCP config: ${i.path}`)}}else if(l==="hooks"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content),p=i.path.replace(/\/[^/]+$/,"");Hn(u,a,p)}catch{t.push(`Failed to parse hook config: ${i.path}`)}}else l==="skills"||l==="commands"||l==="files"?r.push({path:i.path.slice(l.length+1),content:i.content}):r.push(i)}return{mainFiles:r,agentFiles:s,mcpEntries:o,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=e.resource.slug||e.resource.id,i=M(r,o),c=Vn(e),l=(0,Ee.join)(i,...c),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(g=>!g.path.includes("/")),y=s.mainFiles.filter(g=>g.path.includes("/"));if(p.length>0){let g=p.find(S=>S.path==="README.md");g&&p.push({path:"SKILL.md",content:Un(e,g.content)}),W(l,p),u+=p.length}y.length>0&&(W(i,y),u+=y.length)}if(s.agentFiles.length>0){let p=z(r,o);W(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Wn(B(r,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&er(Z(r,o),s.hookEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r,s){let o=[],i=M(r,t==="project"),c=(0,Ee.join)(i,e),l=!1;return(0,G.existsSync)(c)&&((0,G.rmSync)(c,{recursive:!0,force:!0}),l=!0),l||o.push(`Collection directory not found at ${c}`),{removed:l,warnings:o}}describeLocation(e,t,r){let s=M(r,t==="project");return(0,Ee.join)(s,e)}};function Hn(n,e,t){if(!n||typeof n!="object")return;let r=n,s=r.hooks&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)?r.hooks:r;for(let[o,a]of Object.entries(s))if(!(o==="name"||o==="description")&&Array.isArray(a)){e[o]||(e[o]=[]);for(let i of a){let c=t&&typeof i=="object"&&i!==null?{...i,_sc:t}:i;e[o].push(c)}}}function er(n,e,t){let r={};if((0,G.existsSync)(n))try{r=JSON.parse((0,G.readFileSync)(n,"utf-8"))}catch{r={}}let s=typeof r.hooks=="object"&&r.hooks&&!Array.isArray(r.hooks)?r.hooks:{};if(t)for(let[o,a]of Object.entries(s))Array.isArray(a)&&(s[o]=a.filter(i=>!i||typeof i!="object"||i._sc!==t),s[o].length===0&&delete s[o]);for(let[o,a]of Object.entries(e)){Array.isArray(s[o])||(s[o]=[]);for(let i of a){let c=t&&typeof i=="object"&&i!==null?{...i,_sc:t}:i,l=JSON.stringify(c);s[o].some(p=>JSON.stringify(p)===l)||s[o].push(c)}}r.hooks=s,(0,G.mkdirSync)((0,Ee.dirname)(n),{recursive:!0}),(0,G.writeFileSync)(n,JSON.stringify(r,null,2)+`
33
- `,"utf-8")}function tr(n,e){if(!(0,G.existsSync)(n))return!1;let t;try{t=JSON.parse((0,G.readFileSync)(n,"utf-8"))}catch{return!1}let r=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!r)return!1;let s=!1;for(let[o,a]of Object.entries(r)){if(!Array.isArray(a))continue;let i=a.filter(c=>!c||typeof c!="object"||c._sc!==e);i.length!==a.length&&(s=!0,i.length===0?delete r[o]:r[o]=i)}return s&&(t.hooks=r,(0,G.writeFileSync)(n,JSON.stringify(t,null,2)+`
34
- `,"utf-8")),s}function Wn(n,e){let t={};if((0,G.existsSync)(n))try{t=JSON.parse((0,G.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,G.mkdirSync)((0,Ee.dirname)(n),{recursive:!0}),(0,G.writeFileSync)(n,JSON.stringify(t,null,2)+`
35
- `,"utf-8")}function Un(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
36
- `)}function Vn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var ee=require("fs"),Re=require("path");var Bn={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},ct=class{buildFiles(e){let t=[],r=[],s=[],o={},a={};for(let i of e.files){let c=i.path.split("/"),l=c[0];if(l==="agents")s.push({path:i.path.slice(7),content:i.content});else if(l==="mcps"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(o,u.mcpServers);else if(i.path.includes("resources/")){let p=c.indexOf("resources"),y=p>0?c[p-1]:c[1];o[y]=u}}catch{t.push(`Failed to parse MCP config: ${i.path}`)}}else if(l==="hooks"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content);qn(u,a)}catch{t.push(`Failed to parse hook config: ${i.path}`)}}else l==="skills"||l==="commands"||l==="files"?r.push({path:i.path.slice(l.length+1),content:i.content}):r.push(i)}return{mainFiles:r,agentFiles:s,mcpEntries:o,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=e.resource.slug||e.resource.id,i=M(r,o),c=Kn(e),l=(0,Re.join)(i,...c),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(g=>!g.path.includes("/")),y=s.mainFiles.filter(g=>g.path.includes("/"));if(p.length>0){let g=p.find(S=>S.path==="README.md");g&&p.push({path:"SKILL.md",content:Yn(e,g.content)}),W(l,p),u+=p.length}y.length>0&&(W(i,y),u+=y.length)}if(s.agentFiles.length>0){let p=z(r,o);W(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Jn(B(r,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Gn(Z(r,o),s.hookEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=M(r,t==="project"),i=(0,Re.join)(a,e),c=!1;return(0,ee.existsSync)(i)&&((0,ee.rmSync)(i,{recursive:!0,force:!0}),c=!0),c||s.push(`Collection directory not found at ${i}`),{removed:c,warnings:s}}describeLocation(e,t,r){let s=M(r,t==="project");return(0,Re.join)(s,e)}};function qn(n,e){if(!n||typeof n!="object")return;let t=n,r=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(r)){if(s==="name"||s==="description"||!Array.isArray(o))continue;let a=Bn[s]||s;e[a]||(e[a]=[]);for(let i of o)e[a].push(i)}}function Gn(n,e){let t={};if((0,ee.existsSync)(n))try{t=JSON.parse((0,ee.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,o]of Object.entries(e)){Array.isArray(r[s])||(r[s]=[]);for(let a of o){let i=JSON.stringify(a);r[s].some(l=>JSON.stringify(l)===i)||r[s].push(a)}}t.hooks=r,(0,ee.mkdirSync)((0,Re.dirname)(n),{recursive:!0}),(0,ee.writeFileSync)(n,JSON.stringify(t,null,2)+`
37
- `,"utf-8")}function Jn(n,e){let t={};if((0,ee.existsSync)(n))try{t=JSON.parse((0,ee.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,ee.mkdirSync)((0,Re.dirname)(n),{recursive:!0}),(0,ee.writeFileSync)(n,JSON.stringify(t,null,2)+`
38
- `,"utf-8")}function Yn(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
39
- `)}function Kn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var J=require("fs"),Se=require("path");var lt=class{buildFiles(e){let t=[],r=[],s=[],o={},a=[],i=e.resource.slug||e.resource.id;for(let c of e.files){let l=c.path.split("/"),u=l[0];if(u==="agents")s.push({path:c.path.slice(7),content:c.content});else if(u==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let y=l.indexOf("resources"),g=y>0?l[y-1]:l[1];o[g]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else u==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${c.path})`):u==="skills"||u==="commands"||u==="files"?r.push({path:c.path.slice(u.length+1),content:c.content}):r.push(c)}return{mainFiles:r,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:a,warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=M(r,o),i=Qn(e),c=(0,Se.join)(a,...i),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(y=>!y.path.includes("/")),p=s.mainFiles.filter(y=>y.path.includes("/"));if(u.length>0){let y=u.find(g=>g.path==="README.md");y&&u.push({path:"SKILL.md",content:Xn(e,y.content)}),W(c,u),l+=u.length}p.length>0&&(W(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=z(r,o);W(u,s.agentFiles),l+=s.agentFiles.length}for(let u of s.customFiles)(0,J.mkdirSync)((0,Se.dirname)(u.absolutePath),{recursive:!0}),(0,J.writeFileSync)(u.absolutePath,u.content,"utf-8"),l++;return Object.keys(s.mcpEntries).length>0&&zn(B(r,o),s.mcpEntries),{installDir:c,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=M(r,t==="project"),i=(0,Se.join)(a,e),c=!1;(0,J.existsSync)(i)&&((0,J.rmSync)(i,{recursive:!0,force:!0}),c=!0);let l=(0,Se.join)(homedir(),".cursor","rules");if((0,J.existsSync)(l))try{let u=(0,J.readdirSync)(l);for(let p of u)p.startsWith(`${e}-`)&&p.endsWith(".mdc")&&((0,J.unlinkSync)((0,Se.join)(l,p)),c=!0)}catch{s.push("Could not clean up Cursor rules")}return c||s.push(`Collection not found for Cursor at ${i}`),{removed:c,warnings:s}}describeLocation(e,t,r){let s=M(r,t==="project");return(0,Se.join)(s,e)}};function zn(n,e){let t={};if((0,J.existsSync)(n))try{t=JSON.parse((0,J.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,J.mkdirSync)((0,Se.dirname)(n),{recursive:!0}),(0,J.writeFileSync)(n,JSON.stringify(t,null,2)+`
40
- `,"utf-8")}function Xn(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
41
- `)}function Qn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var dt=require("fs"),ut=require("path");var pt=class{buildFiles(e){let t=[],r=[],s=[];for(let o of e.files){let i=o.path.split("/")[0];i==="agents"?s.push({path:o.path.slice(7),content:o.content}):i==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):i==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):i==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):i==="skills"||i==="files"?r.push({path:o.path.slice(i.length+1),content:o.content}):r.push(o)}return{mainFiles:r,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=M(r,o),i=eo(e),c=(0,ut.join)(a,...i),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(y=>!y.path.includes("/")),p=s.mainFiles.filter(y=>y.path.includes("/"));if(u.length>0){let y=u.find(g=>g.path==="README.md");y&&u.push({path:"SKILL.md",content:Zn(e,y.content)}),W(c,u),l+=u.length}p.length>0&&(W(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=z(r,o);W(u,s.agentFiles),l+=s.agentFiles.length}return{installDir:c,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=M(r,t==="project"),i=(0,ut.join)(a,e),c=!1;return(0,dt.existsSync)(i)&&((0,dt.rmSync)(i,{recursive:!0,force:!0}),c=!0),c||s.push(`Collection directory not found at ${i}`),{removed:c,warnings:s}}describeLocation(e,t,r){let s=M(r,t==="project");return(0,ut.join)(s,e)}};function Zn(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
42
- `)}function eo(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var ue=require("fs"),Me=require("path");var mt=class{buildFiles(e){let t=[],r=[],s={};for(let o of e.files){let a=o.path.split("/"),i=a[0];if(i==="agents")r.push({path:o.path.slice(7),content:o.content});else if(i==="mcps"){if(o.path.endsWith(".json"))try{let c=JSON.parse(o.content);if(c.mcpServers&&typeof c.mcpServers=="object")Object.assign(s,c.mcpServers);else if(o.path.includes("resources/")){let l=a.indexOf("resources"),u=l>0?a[l-1]:a[1];s[u]=c}}catch{}}else i==="skills"||i==="commands"||i==="hooks"||i==="files"?t.push({path:o.path.slice(i.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:r,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=M(r,o),i=ro(e),c=(0,Me.join)(a,...i),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(y=>!y.path.includes("/")),p=s.mainFiles.filter(y=>y.path.includes("/"));u.length>0&&(W(c,u),l+=u.length),p.length>0&&(W(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=z(r,o);W(u,s.agentFiles),l+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&to(B(r,o),s.mcpEntries),{installDir:c,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let o=M(r,t==="project"),a=(0,Me.join)(o,e),i=!1;return(0,ue.existsSync)(a)&&((0,ue.rmSync)(a,{recursive:!0,force:!0}),i=!0),{removed:i,warnings:[]}}describeLocation(e,t,r){let s=M(r,t==="project");return(0,Me.join)(s,e)}};function to(n,e){let t={};if((0,ue.existsSync)(n))try{t=JSON.parse((0,ue.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,ue.mkdirSync)((0,Me.dirname)(n),{recursive:!0}),(0,ue.writeFileSync)(n,JSON.stringify(t,null,2)+`
43
- `,"utf-8")}function ro(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function be(n){switch(n.id){case"claude-code":return new at;case"gemini-cli":case"antigravity":return new ct;case"cursor":return new lt;case"codex":return new pt;default:return new mt}}var Zr=`---
44
- title: Resource Manager
45
- description: Search, install, and manage AI resources from the Shared Context library
24
+ `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in $.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,$.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Go(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=a=>{let c=a.attributeName(),u=this.getOptionValue(c),l=this.options.find(S=>S.negate&&c===S.attributeName()),h=this.options.find(S=>!S.negate&&c===S.attributeName());return l&&(l.presetArg===void 0&&u===!1||l.presetArg!==void 0&&u===l.presetArg)?l:h||a},s=a=>{let c=n(a),u=c.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let a=o.createHelp().visibleOptions(o).filter(c=>c.long).map(c=>c.long);s=s.concat(a),o=o.parent}while(o&&!o._enablePositionalOptions);t=rn(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=rn(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Bo(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ke.basename(e,ke.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=t.formatHelp(this,t);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,n,s,o;return t?(n=c=>this._outputConfiguration.writeErr(c),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=c=>this._outputConfiguration.writeOut(c),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:c=>(s||(c=this._outputConfiguration.stripColor(c)),n(c)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(a=>a.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(a=>a.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number($.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let a;typeof t=="function"?a=t({error:o.error,command:o.command}):a=t,a&&o.write(`${a}
27
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function nn(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}function cr(){if($.env.NO_COLOR||$.env.FORCE_COLOR==="0"||$.env.FORCE_COLOR==="false")return!1;if($.env.FORCE_COLOR||$.env.CLICOLOR_FORCE!==void 0)return!0}lr.Command=ar;lr.useColor=cr});var ln=q(Ee=>{"use strict";var{Argument:on}=mt(),{Command:ur}=sn(),{CommanderError:qo,InvalidArgumentError:an}=ot(),{Help:zo}=er(),{Option:cn}=sr();Ee.program=new ur;Ee.createCommand=r=>new ur(r);Ee.createOption=(r,e)=>new cn(r,e);Ee.createArgument=(r,e)=>new on(r,e);Ee.Command=ur;Ee.Option=cn;Ee.Argument=on;Ee.Help=zo;Ee.CommanderError=qo;Ee.InvalidArgumentError=an;Ee.InvalidOptionArgumentError=an});var gr={};zt(gr,{addToManifest:()=>ue,clearAuth:()=>pr,getAuth:()=>Se,getConfig:()=>Re,getManifest:()=>Y,getSyncState:()=>Et,removeFromManifest:()=>at,saveAuth:()=>dr,saveConfig:()=>Sn,saveManifest:()=>mr,saveSyncState:()=>Ze,shouldSync:()=>hr,updateConfig:()=>Xo});function it(){let r=process.env.SC_PROFILE;return r?(0,Ue.join)(hn,"profiles",r):hn}function fr(){return(0,Ue.join)(it(),"auth.json")}function yn(){return(0,Ue.join)(it(),"config.json")}function En(){return(0,Ue.join)(it(),"manifest.json")}function Zo(){(0,Ce.mkdirSync)(it(),{recursive:!0})}function gt(r,e){try{return(0,Ce.existsSync)(r)?JSON.parse((0,Ce.readFileSync)(r,"utf-8")):e}catch{return e}}function yt(r,e,t=!1){if(Zo(),(0,Ce.writeFileSync)(r,JSON.stringify(e,null,2)+`
28
+ `,"utf-8"),t)try{(0,Ce.chmodSync)(r,384)}catch{}}function Se(){return gt(fr(),null)}function dr(r){yt(fr(),r,!0)}function pr(){try{(0,Ce.writeFileSync)(fr(),"{}","utf-8")}catch{}}function Re(){return gt(yn(),Jo)}function Sn(r){yt(yn(),r)}function Xo(r){let e=Re();Sn({...e,...r})}function Y(){return gt(En(),Ko)}function mr(r){yt(En(),r)}function ue(r){let e=Y(),t=e.installations.findIndex(n=>n.resourceId===r.resourceId&&n.agent===r.agent);t>=0?e.installations[t]=r:e.installations.push(r),mr(e)}function at(r,e){let t=Y();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),mr(t)}function Cn(){return(0,Ue.join)(it(),"last-sync.json")}function Et(){return gt(Cn(),null)}function Ze(r){yt(Cn(),r)}function hr(r=Yo){let e=Et();return e?.lastSyncAt?Date.now()-new Date(e.lastSyncAt).getTime()>=r:!0}var Ce,Ue,gn,hn,Jo,Ko,Yo,me=he(()=>{"use strict";Ce=require("fs"),Ue=require("path"),gn=require("os"),hn=(0,Ue.join)((0,gn.homedir)(),".config","shared-context");Jo={apiBase:"https://sharedcontext.ai"};Ko={installations:[]};Yo=720*60*1e3});var _n={};zt(_n,{del:()=>yr,fetchRaw:()=>Er,get:()=>G,isAuthenticated:()=>M,patch:()=>Qo,post:()=>L});function wn(){return Re().apiBase||"https://sharedcontext.ai"}function An(){let r={"Content-Type":"application/json"},e=Se();return e?.token&&(r.Authorization=`Bearer ${e.token}`),r}function M(){return!!Se()?.token}async function St(r,e,t,n){let s=`${wn()}${e}`;try{let o={method:r,headers:An(),body:t?JSON.stringify(t):void 0};n&&(o.signal=AbortSignal.timeout(n));let a=await fetch(s,o),c=a.headers.get("content-type")||"";if(!c.includes("application/json"))return a.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${c||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${a.status}`,message:a.statusText}};let u=await a.json();return a.ok?{ok:!0,data:u.data??u}:{ok:!1,error:{code:u?.error?.code||`HTTP_${a.status}`,message:u?.error?.message||u?.message||a.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function G(r){return St("GET",r)}function L(r,e,t){return St("POST",r,e,t)}function Qo(r,e){return St("PATCH",r,e)}function yr(r,e){return St("DELETE",r,e)}async function Er(r){let e=`${wn()}${r}`,t=await fetch(e,{headers:An()});if(!t.ok)throw new Error(`Download failed: ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}var se=he(()=>{"use strict";me()});var Cr=q((Ta,bn)=>{"use strict";bn.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Ct=q(In=>{"use strict";var xn={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function ei(r){return function(...e){return e.length&&(r=r.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+r)}}for(let r of Object.keys(xn))In[r]=ei(xn[r])});var Tn=q((Pa,Rn)=>{"use strict";var ti=require("fs"),ne=require("path"),On=Cr(),ri=Ct(),ni=typeof process=="object"&&process.platform==="win32",kn=r=>typeof r=="object"&&r!==null,vn=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function J(r){this.sep=ne.sep,this.fs=ti,kn(r)&&kn(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}Rn.exports=J;J.prototype.makeDir=function(r){let e=this;function t(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(o){if(!(!o||o.substr(-1,1)===":")){s+=e.sep+o;var a;try{a=e.fs.statSync(s)}catch{e.fs.mkdirSync(s)}if(a&&a.isFile())throw ri.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};J.prototype.writeFileTo=function(r,e,t,n){let s=this;if(s.fs.existsSync(r)){if(!t)return!1;var o=s.fs.statSync(r);if(o.isDirectory())return!1}var a=ne.dirname(r);s.fs.existsSync(a)||s.makeDir(a);var c;try{c=s.fs.openSync(r,"w",438)}catch{s.fs.chmodSync(r,438),c=s.fs.openSync(r,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(r,n||438),!0};J.prototype.writeFileToAsync=function(r,e,t,n,s){typeof n=="function"&&(s=n,n=void 0);let o=this;o.fs.exists(r,function(a){if(a&&!t)return s(!1);o.fs.stat(r,function(c,u){if(a&&u.isDirectory())return s(!1);var l=ne.dirname(r);o.fs.exists(l,function(h){h||o.makeDir(l),o.fs.open(r,"w",438,function(S,_){S?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(d,m){o.fs.write(m,e,0,e.length,0,function(){o.fs.close(m,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):_?o.fs.write(_,e,0,e.length,0,function(){o.fs.close(_,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};J.prototype.findFiles=function(r){let e=this;function t(n,s,o){typeof s=="boolean"&&(o=s,s=void 0);let a=[];return e.fs.readdirSync(n).forEach(function(c){let u=ne.join(n,c),l=e.fs.statSync(u);(!s||s.test(u))&&a.push(ne.normalize(u)+(l.isDirectory()?e.sep:"")),l.isDirectory()&&o&&(a=a.concat(t(u,s,o)))}),a}return t(r,void 0,!0)};J.prototype.findFilesAsync=function(r,e){let t=this,n=[];t.fs.readdir(r,function(s,o){if(s)return e(s);let a=o.length;if(!a)return e(null,n);o.forEach(function(c){c=ne.join(r,c),t.fs.stat(c,function(u,l){if(u)return e(u);l&&(n.push(ne.normalize(c)+(l.isDirectory()?t.sep:"")),l.isDirectory()?t.findFilesAsync(c,function(h,S){if(h)return e(h);n=n.concat(S),--a||e(null,n)}):--a||e(null,n))})})})};J.prototype.getAttributes=function(){};J.prototype.setAttributes=function(){};J.crc32update=function(r,e){return vn[(r^e)&255]^r>>>8};J.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=J.crc32update(t,r[n++]);return~t>>>0};J.methodToString=function(r){switch(r){case On.STORED:return"STORED ("+r+")";case On.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};J.canonical=function(r){if(!r)return"";let e=ne.posix.normalize("/"+r.split("\\").join("/"));return ne.join(".",e)};J.zipnamefix=function(r){if(!r)return"";let e=ne.posix.normalize("/"+r.split("\\").join("/"));return ne.posix.join(".",e)};J.findLast=function(r,e){if(!Array.isArray(r))throw new TypeError("arr is not array");let t=r.length>>>0;for(let n=t-1;n>=0;n--)if(e(r[n],n,r))return r[n]};J.sanitize=function(r,e){r=ne.resolve(ne.normalize(r));for(var t=e.split("/"),n=0,s=t.length;n<s;n++){var o=ne.normalize(ne.join(r,t.slice(n,s).join(ne.sep)));if(o.indexOf(r)===0)return o}return ne.normalize(ne.join(r,ne.basename(e)))};J.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};J.readBigUInt64LE=function(r,e){var t=Buffer.from(r.slice(e,e+8));return t.swap64(),parseInt(`0x${t.toString("hex")}`)};J.fromDOS2Date=function(r){return new Date((r>>25&127)+1980,Math.max((r>>21&15)-1,0),Math.max(r>>16&31,1),r>>11&31,r>>5&63,(r&31)<<1)};J.fromDate2DOS=function(r){let e=0,t=0;return r.getFullYear()>1979&&(e=(r.getFullYear()-1980&127)<<9|r.getMonth()+1<<5|r.getDate(),t=r.getHours()<<11|r.getMinutes()<<5|r.getSeconds()>>1),e<<16|t};J.isWin=ni;J.crcTable=vn});var Pn=q((Na,Dn)=>{"use strict";var si=require("path");Dn.exports=function(r,{fs:e}){var t=r||"",n=o(),s=null;function o(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(s=e.statSync(t),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=si.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var jn=q((ja,Nn)=>{"use strict";Nn.exports={efs:!0,encode:r=>Buffer.from(r,"utf8"),decode:r=>r.toString("utf8")}});var Ke=q((La,Xe)=>{"use strict";Xe.exports=Tn();Xe.exports.Constants=Cr();Xe.exports.Errors=Ct();Xe.exports.FileAttr=Pn();Xe.exports.decoder=jn()});var Fn=q((Fa,Ln)=>{"use strict";var Ne=Ke(),v=Ne.Constants;Ln.exports=function(){var r=20,e=10,t=0,n=0,s=0,o=0,a=0,c=0,u=0,l=0,h=0,S=0,_=0,d=0,m=0;r|=Ne.isWin?2560:768,t|=v.FLG_EFS;let p={extraLen:0},f=i=>Math.max(0,i)>>>0,g=i=>Math.max(0,i)&65535,C=i=>Math.max(0,i)&255;return s=Ne.fromDate2DOS(new Date),{get made(){return r},set made(i){r=i},get version(){return e},set version(i){e=i},get flags(){return t},set flags(i){t=i},get flags_efs(){return(t&v.FLG_EFS)>0},set flags_efs(i){i?t|=v.FLG_EFS:t&=~v.FLG_EFS},get flags_desc(){return(t&v.FLG_DESC)>0},set flags_desc(i){i?t|=v.FLG_DESC:t&=~v.FLG_DESC},get method(){return n},set method(i){switch(i){case v.STORED:this.version=10;case v.DEFLATED:default:this.version=20}n=i},get time(){return Ne.fromDOS2Date(this.timeval)},set time(i){this.timeval=Ne.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=f(i)},get timeHighByte(){return C(s>>>8)},get crc(){return o},set crc(i){o=f(i)},get compressedSize(){return a},set compressedSize(i){a=f(i)},get size(){return c},set size(i){c=f(i)},get fileNameLength(){return u},set fileNameLength(i){u=i},get extraLength(){return l},set extraLength(i){l=i},get extraLocalLength(){return p.extraLen},set extraLocalLength(i){p.extraLen=i},get commentLength(){return h},set commentLength(i){h=i},get diskNumStart(){return S},set diskNumStart(i){S=f(i)},get inAttr(){return _},set inAttr(i){_=f(i)},get attr(){return d},set attr(i){d=f(i)},get fileAttr(){return(d||0)>>16&4095},get offset(){return m},set offset(i){m=f(i)},get encrypted(){return(t&v.FLG_ENC)===v.FLG_ENC},get centralHeaderSize(){return v.CENHDR+u+l+h},get realDataOffset(){return m+v.LOCHDR+p.fnameLen+p.extraLen},get localHeader(){return p},loadLocalHeaderFromBinary:function(i){var y=i.slice(m,m+v.LOCHDR);if(y.readUInt32LE(0)!==v.LOCSIG)throw Ne.Errors.INVALID_LOC();p.version=y.readUInt16LE(v.LOCVER),p.flags=y.readUInt16LE(v.LOCFLG),p.method=y.readUInt16LE(v.LOCHOW),p.time=y.readUInt32LE(v.LOCTIM),p.crc=y.readUInt32LE(v.LOCCRC),p.compressedSize=y.readUInt32LE(v.LOCSIZ),p.size=y.readUInt32LE(v.LOCLEN),p.fnameLen=y.readUInt16LE(v.LOCNAM),p.extraLen=y.readUInt16LE(v.LOCEXT);let E=m+v.LOCHDR+p.fnameLen,b=E+p.extraLen;return i.slice(E,b)},loadFromBinary:function(i){if(i.length!==v.CENHDR||i.readUInt32LE(0)!==v.CENSIG)throw Ne.Errors.INVALID_CEN();r=i.readUInt16LE(v.CENVEM),e=i.readUInt16LE(v.CENVER),t=i.readUInt16LE(v.CENFLG),n=i.readUInt16LE(v.CENHOW),s=i.readUInt32LE(v.CENTIM),o=i.readUInt32LE(v.CENCRC),a=i.readUInt32LE(v.CENSIZ),c=i.readUInt32LE(v.CENLEN),u=i.readUInt16LE(v.CENNAM),l=i.readUInt16LE(v.CENEXT),h=i.readUInt16LE(v.CENCOM),S=i.readUInt16LE(v.CENDSK),_=i.readUInt16LE(v.CENATT),d=i.readUInt32LE(v.CENATX),m=i.readUInt32LE(v.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(v.LOCHDR);return i.writeUInt32LE(v.LOCSIG,0),i.writeUInt16LE(e,v.LOCVER),i.writeUInt16LE(t,v.LOCFLG),i.writeUInt16LE(n,v.LOCHOW),i.writeUInt32LE(s,v.LOCTIM),i.writeUInt32LE(o,v.LOCCRC),i.writeUInt32LE(a,v.LOCSIZ),i.writeUInt32LE(c,v.LOCLEN),i.writeUInt16LE(u,v.LOCNAM),i.writeUInt16LE(p.extraLen,v.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(v.CENHDR+u+l+h);return i.writeUInt32LE(v.CENSIG,0),i.writeUInt16LE(r,v.CENVEM),i.writeUInt16LE(e,v.CENVER),i.writeUInt16LE(t,v.CENFLG),i.writeUInt16LE(n,v.CENHOW),i.writeUInt32LE(s,v.CENTIM),i.writeUInt32LE(o,v.CENCRC),i.writeUInt32LE(a,v.CENSIZ),i.writeUInt32LE(c,v.CENLEN),i.writeUInt16LE(u,v.CENNAM),i.writeUInt16LE(l,v.CENEXT),i.writeUInt16LE(h,v.CENCOM),i.writeUInt16LE(S,v.CENDSK),i.writeUInt16LE(_,v.CENATT),i.writeUInt32LE(d,v.CENATX),i.writeUInt32LE(m,v.CENOFF),i},toJSON:function(){let i=function(y){return y+" bytes"};return{made:r,version:e,flags:t,method:Ne.methodToString(n),time:this.time,crc:"0x"+o.toString(16).toUpperCase(),compressedSize:i(a),size:i(c),fileNameLength:i(u),extraLength:i(l),commentLength:i(h),diskNumStart:S,inAttr:_,attr:d,offset:m,centralHeaderSize:i(v.CENHDR+u+l+h)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Mn=q(($a,$n)=>{"use strict";var Ye=Ke(),z=Ye.Constants;$n.exports=function(){var r=0,e=0,t=0,n=0,s=0;return{get diskEntries(){return r},set diskEntries(o){r=e=o},get totalEntries(){return e},set totalEntries(o){e=r=o},get size(){return t},set size(o){t=o},get offset(){return n},set offset(o){n=o},get commentLength(){return s},set commentLength(o){s=o},get mainHeaderSize(){return z.ENDHDR+s},loadFromBinary:function(o){if((o.length!==z.ENDHDR||o.readUInt32LE(0)!==z.ENDSIG)&&(o.length<z.ZIP64HDR||o.readUInt32LE(0)!==z.ZIP64SIG))throw Ye.Errors.INVALID_END();o.readUInt32LE(0)===z.ENDSIG?(r=o.readUInt16LE(z.ENDSUB),e=o.readUInt16LE(z.ENDTOT),t=o.readUInt32LE(z.ENDSIZ),n=o.readUInt32LE(z.ENDOFF),s=o.readUInt16LE(z.ENDCOM)):(r=Ye.readBigUInt64LE(o,z.ZIP64SUB),e=Ye.readBigUInt64LE(o,z.ZIP64TOT),t=Ye.readBigUInt64LE(o,z.ZIP64SIZE),n=Ye.readBigUInt64LE(o,z.ZIP64OFF),s=0)},toBinary:function(){var o=Buffer.alloc(z.ENDHDR+s);return o.writeUInt32LE(z.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(r,z.ENDSUB),o.writeUInt16LE(e,z.ENDTOT),o.writeUInt32LE(t,z.ENDSIZ),o.writeUInt32LE(n,z.ENDOFF),o.writeUInt16LE(s,z.ENDCOM),o.fill(" ",z.ENDHDR),o},toJSON:function(){let o=function(a,c){let u=a.toString(16).toUpperCase();for(;u.length<c;)u="0"+u;return"0x"+u};return{diskEntries:r,totalEntries:e,size:t+" bytes",offset:o(n,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ar=q(wr=>{"use strict";wr.EntryHeader=Fn();wr.MainHeader=Mn()});var Un=q((Ha,Hn)=>{"use strict";Hn.exports=function(r){var e=require("zlib"),t={chunkSize:(parseInt(r.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(r,t)},deflateAsync:function(n){var s=e.createDeflateRaw(t),o=[],a=0;s.on("data",function(c){o.push(c),a+=c.length}),s.on("end",function(){var c=Buffer.alloc(a),u=0;c.fill(0);for(var l=0;l<o.length;l++){var h=o[l];h.copy(c,u),u+=h.length}n&&n(c)}),s.end(r)}}}});var Wn=q((Ua,Bn)=>{"use strict";var oi=+(process.versions?process.versions.node:"").split(".")[0]||0;Bn.exports=function(r,e){var t=require("zlib");let n=oi>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(r,n)},inflateAsync:function(s){var o=t.createInflateRaw(n),a=[],c=0;o.on("data",function(u){a.push(u),c+=u.length}),o.on("end",function(){var u=Buffer.alloc(c),l=0;u.fill(0);for(var h=0;h<a.length;h++){var S=a[h];S.copy(u,l),l+=S.length}s&&s(u)}),o.end(r)}}}});var Zn=q((Ba,zn)=>{"use strict";var{randomFillSync:Vn}=require("crypto"),ii=Ct(),ai=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),qn=(r,e)=>Math.imul(r,e)>>>0,Gn=(r,e)=>ai[(r^e)&255]^r>>>8,ct=()=>typeof Vn=="function"?Vn(Buffer.alloc(12)):ct.node();ct.node=()=>{let r=Buffer.alloc(12),e=r.length;for(let t=0;t<e;t++)r[t]=Math.random()*256&255;return r};var wt={genSalt:ct};function At(r){let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}At.prototype.updateKeys=function(r){let e=this.keys;return e[0]=Gn(e[0],r),e[1]+=e[0]&255,e[1]=qn(e[1],134775813)+1,e[2]=Gn(e[2],e[1]>>>24),r};At.prototype.next=function(){let r=(this.keys[2]|2)>>>0;return qn(r,r^1)>>8&255};function ci(r){let e=new At(r);return function(t){let n=Buffer.alloc(t.length),s=0;for(let o of t)n[s++]=e.updateKeys(o^e.next());return n}}function li(r){let e=new At(r);return function(t,n,s=0){n||(n=Buffer.alloc(t.length));for(let o of t){let a=e.next();n[s++]=o^a,e.updateKeys(o)}return n}}function ui(r,e,t){if(!r||!Buffer.isBuffer(r)||r.length<12)return Buffer.alloc(0);let n=ci(t),s=n(r.slice(0,12)),o=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==o)throw ii.WRONG_PASSWORD();return n(r.slice(12))}function fi(r){Buffer.isBuffer(r)&&r.length>=12?wt.genSalt=function(){return r.slice(0,12)}:r==="node"?wt.genSalt=ct.node:wt.genSalt=ct}function di(r,e,t,n=!1){r==null&&(r=Buffer.alloc(0)),Buffer.isBuffer(r)||(r=Buffer.from(r.toString()));let s=li(t),o=wt.genSalt();o[11]=e.crc>>>24&255,n&&(o[10]=e.crc>>>16&255);let a=Buffer.alloc(r.length+12);return s(o,a),s(r,a,12)}zn.exports={decrypt:ui,encrypt:di,_salter:fi}});var Jn=q(_t=>{"use strict";_t.Deflater=Un();_t.Inflater=Wn();_t.ZipCrypto=Zn()});var br=q((Va,Xn)=>{"use strict";var H=Ke(),pi=Ar(),X=H.Constants,_r=Jn();Xn.exports=function(r,e){var t=new pi.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),o=!1,a=null,c=Buffer.alloc(0),u=Buffer.alloc(0),l=!0;let h=r,S=typeof h.decoder=="object"?h.decoder:H.decoder;l=S.hasOwnProperty("efs")?S.efs:!1;function _(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function d(i){if(t.flags_desc){let y={},E=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(E)==X.LOCSIG||e.readUInt32LE(E)==X.CENSIG)throw H.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(E)==X.EXTSIG)y.crc=e.readUInt32LE(E+X.EXTCRC),y.compressedSize=e.readUInt32LE(E+X.EXTSIZ),y.size=e.readUInt32LE(E+X.EXTLEN);else if(e.readUInt16LE(E+12)===19280)y.crc=e.readUInt32LE(E+X.EXTCRC-4),y.compressedSize=e.readUInt32LE(E+X.EXTSIZ-4),y.size=e.readUInt32LE(E+X.EXTLEN-4);else throw H.Errors.DESCRIPTOR_UNKNOWN();if(y.compressedSize!==t.compressedSize||y.size!==t.size||y.crc!==t.crc)throw H.Errors.DESCRIPTOR_FAULTY();if(H.crc32(i)!==y.crc)return!1}else if(H.crc32(i)!==t.localHeader.crc)return!1;return!0}function m(i,y,E){if(typeof y>"u"&&typeof i=="string"&&(E=i,i=void 0),o)return i&&y&&y(Buffer.alloc(0),H.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var b=_();if(b.length===0)return i&&y&&y(b),b;if(t.encrypted){if(typeof E!="string"&&!Buffer.isBuffer(E))throw H.Errors.INVALID_PASS_PARAM();b=_r.ZipCrypto.decrypt(b,t,E)}var A=Buffer.alloc(t.size);switch(t.method){case H.Constants.STORED:if(b.copy(A),d(A))return i&&y&&y(A),A;throw i&&y&&y(A,H.Errors.BAD_CRC()),H.Errors.BAD_CRC();case H.Constants.DEFLATED:var I=new _r.Inflater(b,t.size);if(i)I.inflateAsync(function(O){O.copy(O,0),y&&(d(O)?y(O):y(O,H.Errors.BAD_CRC()))});else{if(I.inflate(A).copy(A,0),!d(A))throw H.Errors.BAD_CRC(`"${S.decode(n)}"`);return A}break;default:throw i&&y&&y(Buffer.alloc(0),H.Errors.UNKNOWN_METHOD()),H.Errors.UNKNOWN_METHOD()}}function p(i,y){if((!a||!a.length)&&Buffer.isBuffer(e))return i&&y&&y(_()),_();if(a.length&&!o){var E;switch(t.method){case H.Constants.STORED:return t.compressedSize=t.size,E=Buffer.alloc(a.length),a.copy(E),i&&y&&y(E),E;default:case H.Constants.DEFLATED:var b=new _r.Deflater(a);if(i)b.deflateAsync(function(I){E=Buffer.alloc(I.length),t.compressedSize=I.length,I.copy(E),y&&y(E)});else{var A=b.deflate();return t.compressedSize=A.length,A}b=null;break}}else if(i&&y)y(Buffer.alloc(0));else return Buffer.alloc(0)}function f(i,y){return(i.readUInt32LE(y+4)<<4)+i.readUInt32LE(y)}function g(i){try{for(var y=0,E,b,A;y+4<i.length;)E=i.readUInt16LE(y),y+=2,b=i.readUInt16LE(y),y+=2,A=i.slice(y,y+b),y+=b,X.ID_ZIP64===E&&C(A)}catch{throw H.Errors.EXTRA_FIELD_PARSE_ERROR()}}function C(i){var y,E,b,A;i.length>=X.EF_ZIP64_SCOMP&&(y=f(i,X.EF_ZIP64_SUNCOMP),t.size===X.EF_ZIP64_OR_32&&(t.size=y)),i.length>=X.EF_ZIP64_RHO&&(E=f(i,X.EF_ZIP64_SCOMP),t.compressedSize===X.EF_ZIP64_OR_32&&(t.compressedSize=E)),i.length>=X.EF_ZIP64_DSN&&(b=f(i,X.EF_ZIP64_RHO),t.offset===X.EF_ZIP64_OR_32&&(t.offset=b)),i.length>=X.EF_ZIP64_DSN+4&&(A=i.readUInt32LE(X.EF_ZIP64_DSN),t.diskNumStart===X.EF_ZIP64_OR_16&&(t.diskNumStart=A))}return{get entryName(){return S.decode(n)},get rawEntryName(){return n},set entryName(i){n=H.toBuffer(i,S.encode);var y=n[n.length-1];o=y===47||y===92,t.fileNameLength=n.length},get efs(){return typeof l=="function"?l(this.entryName):l},get extra(){return c},set extra(i){c=i,t.extraLength=i.length,g(i)},get comment(){return S.decode(s)},set comment(i){if(s=H.toBuffer(i,S.encode),t.commentLength=s.length,s.length>65535)throw H.Errors.COMMENT_TOO_LONG()},get name(){var i=S.decode(n);return o?i.substr(i.length-1).split("/").pop():i.split("/").pop()},get isDirectory(){return o},getCompressedData:function(){return p(!1,null)},getCompressedDataAsync:function(i){p(!0,i)},setData:function(i){a=H.toBuffer(i,H.decoder.encode),!o&&a.length?(t.size=a.length,t.method=H.Constants.DEFLATED,t.crc=H.crc32(i),t.changed=!0):t.method=H.Constants.STORED},getData:function(i){return t.changed?a:m(!1,null,i)},getDataAsync:function(i,y){t.changed?i(a):m(!0,i,y)},set attr(i){t.attr=i},get attr(){return t.attr},set header(i){t.loadFromBinary(i)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=c.length;var i=t.centralHeaderToBinary(),y=H.Constants.CENHDR;return n.copy(i,y),y+=n.length,c.copy(i,y),y+=t.extraLength,s.copy(i,y),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=u.length;let y=t.localHeaderToBinary(),E=Buffer.alloc(y.length+n.length+t.extraLocalLength);return y.copy(E,i),i+=y.length,n.copy(E,i),i+=n.length,u.copy(E,i),i+=u.length,E},toJSON:function(){let i=function(y){return"<"+(y&&y.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:i(e),data:i(a)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Qn=q((Ga,Yn)=>{"use strict";var Kn=br(),mi=Ar(),ae=Ke();Yn.exports=function(r,e){var t=[],n={},s=Buffer.alloc(0),o=new mi.MainHeader,a=!1,c=null;let u=new Set,l=e,{noSort:h,decoder:S}=l;r?m(l.readEntries):a=!0;function _(){let f=new Set;for(let g of Object.keys(n)){let C=g.split("/");if(C.pop(),!!C.length)for(let i=0;i<C.length;i++){let y=C.slice(0,i+1).join("/")+"/";f.add(y)}}for(let g of f)if(!(g in n)){let C=new Kn(l);C.entryName=g,C.attr=16,C.temporary=!0,t.push(C),n[C.entryName]=C,u.add(C)}}function d(){if(a=!0,n={},o.diskEntries>(r.length-o.offset)/ae.Constants.CENHDR)throw ae.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(o.diskEntries);for(var f=o.offset,g=0;g<t.length;g++){var C=f,i=new Kn(l,r);i.header=r.slice(C,C+=ae.Constants.CENHDR),i.entryName=r.slice(C,C+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(C,C+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(C,C+i.header.commentLength)),f+=i.header.centralHeaderSize,t[g]=i,n[i.entryName]=i}u.clear(),_()}function m(f){var g=r.length-ae.Constants.ENDHDR,C=Math.max(0,g-65535),i=C,y=r.length,E=-1,b=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(C=0),g;g>=i;g--)if(r[g]===80){if(r.readUInt32LE(g)===ae.Constants.ENDSIG){E=g,b=g,y=g+ae.Constants.ENDHDR,i=g-ae.Constants.END64HDR;continue}if(r.readUInt32LE(g)===ae.Constants.END64SIG){i=C;continue}if(r.readUInt32LE(g)===ae.Constants.ZIP64SIG){E=g,y=g+ae.readBigUInt64LE(r,g+ae.Constants.ZIP64SIZE)+ae.Constants.ZIP64LEAD;break}}if(E==-1)throw ae.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(E,y)),o.commentLength&&(s=r.slice(b+ae.Constants.ENDHDR)),f&&d()}function p(){t.length>1&&!h&&t.sort((f,g)=>f.entryName.toLowerCase().localeCompare(g.entryName.toLowerCase()))}return{get entries(){return a||d(),t.filter(f=>!u.has(f))},get comment(){return S.decode(s)},set comment(f){s=ae.toBuffer(f,S.encode),o.commentLength=s.length},getEntryCount:function(){return a?t.length:o.diskEntries},forEach:function(f){this.entries.forEach(f)},getEntry:function(f){return a||d(),n[f]||null},setEntry:function(f){a||d(),t.push(f),n[f.entryName]=f,o.totalEntries=t.length},deleteFile:function(f,g=!0){a||d();let C=n[f];this.getEntryChildren(C,g).map(y=>y.entryName).forEach(this.deleteEntry)},deleteEntry:function(f){a||d();let g=n[f],C=t.indexOf(g);C>=0&&(t.splice(C,1),delete n[f],o.totalEntries=t.length)},getEntryChildren:function(f,g=!0){if(a||d(),typeof f=="object")if(f.isDirectory&&g){let C=[],i=f.entryName;for(let y of t)y.entryName.startsWith(i)&&C.push(y);return C}else return[f];return[]},getChildCount:function(f){if(f&&f.isDirectory){let g=this.getEntryChildren(f);return g.includes(f)?g.length-1:g.length}return 0},compressToBuffer:function(){a||d(),p();let f=[],g=[],C=0,i=0;o.size=0,o.offset=0;let y=0;for(let A of this.entries){let I=A.getCompressedData();A.header.offset=i;let O=A.packLocalHeader(),T=O.length+I.length;i+=T,f.push(O),f.push(I);let k=A.packCentralHeader();g.push(k),o.size+=k.length,C+=T+k.length,y++}C+=o.mainHeaderSize,o.offset=i,o.totalEntries=y,i=0;let E=Buffer.alloc(C);for(let A of f)A.copy(E,i),i+=A.length;for(let A of g)A.copy(E,i),i+=A.length;let b=o.toBinary();return s&&s.copy(b,ae.Constants.ENDHDR),b.copy(E,i),r=E,a=!1,E},toAsyncBuffer:function(f,g,C,i){try{a||d(),p();let y=[],E=[],b=0,A=0,I=0;o.size=0,o.offset=0;let O=function(T){if(T.length>0){let k=T.shift(),N=k.entryName+k.extra.toString();C&&C(N),k.getCompressedDataAsync(function(D){i&&i(N),k.header.offset=A;let F=k.packLocalHeader(),B=F.length+D.length;A+=B,y.push(F),y.push(D);let pe=k.packCentralHeader();E.push(pe),o.size+=pe.length,b+=B+pe.length,I++,O(T)})}else{b+=o.mainHeaderSize,o.offset=A,o.totalEntries=I,A=0;let k=Buffer.alloc(b);y.forEach(function(D){D.copy(k,A),A+=D.length}),E.forEach(function(D){D.copy(k,A),A+=D.length});let N=o.toBinary();s&&s.copy(N,ae.Constants.ENDHDR),N.copy(k,A),r=k,a=!1,f(k)}};O(Array.from(this.entries))}catch(y){g(y)}}}}});var rs=q((qa,ts)=>{"use strict";var Z=Ke(),K=require("path"),hi=br(),gi=Qn(),Be=(...r)=>Z.findLast(r,e=>typeof e=="boolean"),es=(...r)=>Z.findLast(r,e=>typeof e=="string"),yi=(...r)=>Z.findLast(r,e=>typeof e=="function"),Ei={noSort:!1,readEntries:!1,method:Z.Constants.NONE,fs:null};ts.exports=function(r,e){let t=null,n=Object.assign(Object.create(null),Ei);r&&typeof r=="object"&&(r instanceof Uint8Array||(Object.assign(n,r),r=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(r)&&(t=r,n.method=Z.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new Z(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=Z.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=Z.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw Z.Errors.INVALID_FILENAME();let o=new gi(t,n),{canonical:a,sanitize:c,zipnamefix:u}=Z;function l(d){if(d&&o){var m;if(typeof d=="string"&&(m=o.getEntry(K.posix.normalize(d))),typeof d=="object"&&typeof d.entryName<"u"&&typeof d.header<"u"&&(m=o.getEntry(d.entryName)),m)return m}return null}function h(d){let{join:m,normalize:p,sep:f}=K.posix;return m(".",p(f+d.split("\\").join(f)+f))}function S(d){return d instanceof RegExp?(function(m){return function(p){return m.test(p)}})(d):typeof d!="function"?()=>!0:d}let _=(d,m)=>{let p=m.slice(-1);return p=p===s.sep?s.sep:"",K.relative(d,m)+p};return{readFile:function(d,m){var p=l(d);return p&&p.getData(m)||null},childCount:function(d){let m=l(d);if(m)return o.getChildCount(m)},readFileAsync:function(d,m){var p=l(d);p?p.getDataAsync(m):m(null,"getEntry failed for:"+d)},readAsText:function(d,m){var p=l(d);if(p){var f=p.getData();if(f&&f.length)return f.toString(m||"utf8")}return""},readAsTextAsync:function(d,m,p){var f=l(d);f?f.getDataAsync(function(g,C){if(C){m(g,C);return}g&&g.length?m(g.toString(p||"utf8")):m("")}):m("")},deleteFile:function(d,m=!0){var p=l(d);p&&o.deleteFile(p.entryName,m)},deleteEntry:function(d){var m=l(d);m&&o.deleteEntry(m.entryName)},addZipComment:function(d){o.comment=d},getZipComment:function(){return o.comment||""},addZipEntryComment:function(d,m){var p=l(d);p&&(p.comment=m)},getZipEntryComment:function(d){var m=l(d);return m&&m.comment||""},updateFile:function(d,m){var p=l(d);p&&p.setData(m)},addLocalFile:function(d,m,p,f){if(s.fs.existsSync(d)){m=m?h(m):"";let g=K.win32.basename(K.win32.normalize(d));m+=p||g;let C=s.fs.statSync(d),i=C.isFile()?s.fs.readFileSync(d):Buffer.alloc(0);C.isDirectory()&&(m+=s.sep),this.addFile(m,i,f,C)}else throw Z.Errors.FILE_NOT_FOUND(d)},addLocalFileAsync:function(d,m){d=typeof d=="object"?d:{localPath:d};let p=K.resolve(d.localPath),{comment:f}=d,{zipPath:g,zipName:C}=d,i=this;s.fs.stat(p,function(y,E){if(y)return m(y,!1);g=g?h(g):"";let b=K.win32.basename(K.win32.normalize(p));if(g+=C||b,E.isFile())s.fs.readFile(p,function(A,I){return A?m(A,!1):(i.addFile(g,I,f,E),setImmediate(m,void 0,!0))});else if(E.isDirectory())return g+=s.sep,i.addFile(g,Buffer.alloc(0),f,E),setImmediate(m,void 0,!0)})},addLocalFolder:function(d,m,p){if(p=S(p),m=m?h(m):"",d=K.normalize(d),s.fs.existsSync(d)){let f=s.findFiles(d),g=this;if(f.length)for(let C of f){let i=K.join(m,_(d,C));p(i)&&g.addLocalFile(C,K.dirname(i))}}else throw Z.Errors.FILE_NOT_FOUND(d)},addLocalFolderAsync:function(d,m,p,f){f=S(f),p=p?h(p):"",d=K.normalize(d);var g=this;s.fs.open(d,"r",function(C){if(C&&C.code==="ENOENT")m(void 0,Z.Errors.FILE_NOT_FOUND(d));else if(C)m(void 0,C);else{var i=s.findFiles(d),y=-1,E=function(){if(y+=1,y<i.length){var b=i[y],A=_(d,b).split("\\").join("/");A=A.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),f(A)?s.fs.stat(b,function(I,O){I&&m(void 0,I),O.isFile()?s.fs.readFile(b,function(T,k){T?m(void 0,T):(g.addFile(p+A,k,"",O),E())}):(g.addFile(p+A+"/",Buffer.alloc(0),"",O),E())}):process.nextTick(()=>{E()})}else m(!0,void 0)};E()}})},addLocalFolderAsync2:function(d,m){let p=this;d=typeof d=="object"?d:{localPath:d},localPath=K.resolve(h(d.localPath));let{zipPath:f,filter:g,namefix:C}=d;g instanceof RegExp?g=(function(E){return function(b){return E.test(b)}})(g):typeof g!="function"&&(g=function(){return!0}),f=f?h(f):"",C=="latin1"&&(C=E=>E.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof C!="function"&&(C=E=>E);let i=E=>K.join(f,C(_(localPath,E))),y=E=>K.win32.basename(K.win32.normalize(C(E)));s.fs.open(localPath,"r",function(E){E&&E.code==="ENOENT"?m(void 0,Z.Errors.FILE_NOT_FOUND(localPath)):E?m(void 0,E):s.findFilesAsync(localPath,function(b,A){if(b)return m(b);A=A.filter(I=>g(i(I))),A.length||m(void 0,!1),setImmediate(A.reverse().reduce(function(I,O){return function(T,k){if(T||k===!1)return setImmediate(I,T,!1);p.addLocalFileAsync({localPath:O,zipPath:K.dirname(i(O)),zipName:y(O)},I)}},m))})})},addLocalFolderPromise:function(d,m){return new Promise((p,f)=>{this.addLocalFolderAsync2(Object.assign({localPath:d},m),(g,C)=>{g&&f(g),C&&p(this)})})},addFile:function(d,m,p,f){d=u(d);let g=l(d),C=g!=null;C||(g=new hi(n),g.entryName=d),g.comment=p||"";let i=typeof f=="object"&&f instanceof s.fs.Stats;i&&(g.header.time=f.mtime);var y=g.isDirectory?16:0;let E=g.isDirectory?16384:32768;return i?E|=4095&f.mode:typeof f=="number"?E|=4095&f:E|=g.isDirectory?493:420,y=(y|E<<16)>>>0,g.attr=y,g.setData(m),C||o.setEntry(g),g},getEntries:function(d){return o.password=d,o?o.entries:[]},getEntry:function(d){return l(d)},getEntryCount:function(){return o.getEntryCount()},forEach:function(d){return o.forEach(d)},extractEntryTo:function(d,m,p,f,g,C){f=Be(!1,f),g=Be(!1,g),p=Be(!0,p),C=es(g,C);var i=l(d);if(!i)throw Z.Errors.NO_ENTRY();var y=a(i.entryName),E=c(m,C&&!i.isDirectory?C:p?y:K.basename(y));if(i.isDirectory){var b=o.getEntryChildren(i);return b.forEach(function(O){if(O.isDirectory)return;var T=O.getData();if(!T)throw Z.Errors.CANT_EXTRACT_FILE();var k=a(O.entryName),N=c(m,p?k:K.basename(k));let D=g?O.header.fileAttr:void 0;s.writeFileTo(N,T,f,D)}),!0}var A=i.getData(o.password);if(!A)throw Z.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(E)&&!f)throw Z.Errors.CANT_OVERRIDE();let I=g?d.header.fileAttr:void 0;return s.writeFileTo(E,A,f,I),!0},test:function(d){if(!o)return!1;for(var m in o.entries)try{if(m.isDirectory)continue;var p=o.entries[m].getData(d);if(!p)return!1}catch{return!1}return!0},extractAllTo:function(d,m,p,f){if(p=Be(!1,p),f=es(p,f),m=Be(!1,m),!o)throw Z.Errors.NO_ZIP();o.entries.forEach(function(g){var C=c(d,a(g.entryName));if(g.isDirectory){s.makeDir(C);return}var i=g.getData(f);if(!i)throw Z.Errors.CANT_EXTRACT_FILE();let y=p?g.header.fileAttr:void 0;s.writeFileTo(C,i,m,y);try{s.fs.utimesSync(C,g.header.time,g.header.time)}catch{throw Z.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(d,m,p,f){if(f=yi(m,p,f),p=Be(!1,p),m=Be(!1,m),!f)return new Promise((E,b)=>{this.extractAllToAsync(d,m,p,function(A){A?b(A):E(this)})});if(!o){f(Z.Errors.NO_ZIP());return}d=K.resolve(d);let g=E=>c(d,K.normalize(a(E.entryName))),C=(E,b)=>new Error(E+': "'+b+'"'),i=[],y=[];o.entries.forEach(E=>{E.isDirectory?i.push(E):y.push(E)});for(let E of i){let b=g(E),A=p?E.header.fileAttr:void 0;try{s.makeDir(b),A&&s.fs.chmodSync(b,A),s.fs.utimesSync(b,E.header.time,E.header.time)}catch{f(C("Unable to create folder",b))}}y.reverse().reduce(function(E,b){return function(A){if(A)E(A);else{let I=K.normalize(a(b.entryName)),O=c(d,I);b.getDataAsync(function(T,k){if(k)E(k);else if(!T)E(Z.Errors.CANT_EXTRACT_FILE());else{let N=p?b.header.fileAttr:void 0;s.writeFileToAsync(O,T,m,N,function(D){D||E(C("Unable to write file",O)),s.fs.utimes(O,b.header.time,b.header.time,function(F){F?E(C("Unable to set times",O)):E()})})}})}}},f)()},writeZip:function(d,m){if(arguments.length===1&&typeof d=="function"&&(m=d,d=""),!d&&n.filename&&(d=n.filename),!!d){var p=o.compressToBuffer();if(p){var f=s.writeFileTo(d,p,!0);typeof m=="function"&&m(f?null:new Error("failed"),"")}}},writeZipPromise:function(d,m){let{overwrite:p,perm:f}=Object.assign({overwrite:!0},m);return new Promise((g,C)=>{!d&&n.filename&&(d=n.filename),d||C("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let y=E=>E?g(E):C("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(d,i,p,f,y)},C)})},toBufferPromise:function(){return new Promise((d,m)=>{o.toAsyncBuffer(d,m)})},toBuffer:function(d,m,p,f){return typeof d=="function"?(o.toAsyncBuffer(d,m,p,f),null):o.compressToBuffer()}}}});function Vi(){try{return Tr.default.statSync("/.dockerenv"),!0}catch{return!1}}function Gi(){try{return Tr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Dr(){return Rr===void 0&&(Rr=Vi()||Gi()),Rr}var Tr,Rr,bs=he(()=>{"use strict";Tr=ce(require("fs"),1)});function ze(){return Pr===void 0&&(Pr=qi()||Dr()),Pr}var xs,Pr,qi,Nr=he(()=>{"use strict";xs=ce(require("fs"),1);bs();qi=()=>{try{return xs.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var jr,Os,Mt,Is,Fe,Lr=he(()=>{"use strict";jr=ce(require("process"),1),Os=ce(require("os"),1),Mt=ce(require("fs"),1);Nr();Is=()=>{if(jr.default.platform!=="linux")return!1;if(Os.default.release().toLowerCase().includes("microsoft"))return!ze();try{if(Mt.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!ze()}catch{}return Mt.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Mt.default.existsSync("/run/WSL")?!ze():!1},Fe=jr.default.env.__IS_WSL_TEST__?Is:Is()});var Fr,ft,zi,Zi,$r,ks=he(()=>{"use strict";Fr=ce(require("process"),1),ft=ce(require("fs/promises"),1);Lr();Lr();zi=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await ft.default.access(t,ft.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await ft.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Zi=async()=>`${await zi()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,$r=async()=>Fe?Zi():`${Fr.default.env.SYSTEMROOT||Fr.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function $e(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var vs=he(()=>{"use strict"});async function Mr(){if(Ts.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Ji("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var Rs,Ts,Ds,Ji,Ps=he(()=>{"use strict";Rs=require("util"),Ts=ce(require("process"),1),Ds=require("child_process"),Ji=(0,Rs.promisify)(Ds.execFile)});async function Ls(r,{humanReadableOutput:e=!0,signal:t}={}){if(Ns.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await Xi("osascript",["-e",r,n],s);return o.trim()}var Ns,js,Hr,Xi,Fs=he(()=>{"use strict";Ns=ce(require("process"),1),js=require("util"),Hr=require("child_process"),Xi=(0,js.promisify)(Hr.execFile)});async function Ur(r){return Ls(`tell application "Finder" to set app_path to application file id "${r}" as string
29
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var $s=he(()=>{"use strict";Fs()});async function Wr(r=Ki){let{stdout:e}=await r("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new Br(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),o=n.lastIndexOf("-"),a=s===-1?void 0:n.slice(0,s),c=o===-1?void 0:n.slice(0,o);return Ht[n]??Ht[a]??Ht[c]??{name:n,id:n}}var Ms,Hs,Ki,Ht,rl,Br,Us=he(()=>{"use strict";Ms=require("util"),Hs=require("child_process"),Ki=(0,Ms.promisify)(Hs.execFile),Ht={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},rl=new Map(Object.entries(Ht)),Br=class extends Error{}});async function Vr(){if(Ut.default.platform==="darwin"){let r=await Mr();return{name:await Ur(r),id:r}}if(Ut.default.platform==="linux"){let{stdout:r}=await Yi("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Qi(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Ut.default.platform==="win32")return Wr();throw new Error("Only macOS, Linux, and Windows are supported")}var Bs,Ut,Ws,Yi,Qi,Vs=he(()=>{"use strict";Bs=require("util"),Ut=ce(require("process"),1),Ws=require("child_process");Ps();$s();Us();Yi=(0,Bs.promisify)(Ws.execFile),Qi=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Ks={};zt(Ks,{apps:()=>Me,default:()=>sa,openApp:()=>na});async function ta(){let r=await $r(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=zr.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await ea(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function Zs(r){if(typeof r=="string"||Array.isArray(r))return r;let{[qs]:e}=r;if(!e)throw new Error(`${qs} is not supported`);return e}function Wt({[nt]:r},{wsl:e}){if(e&&Fe)return Zs(e);if(!r)throw new Error(`${nt} is not supported`);return Zs(r)}var qr,zr,Zr,Js,Xs,Jr,Bt,oa,ea,Gr,Gs,nt,qs,zs,dt,ra,na,Me,sa,Ys=he(()=>{"use strict";qr=ce(require("process"),1),zr=require("buffer"),Zr=ce(require("path"),1),Js=require("url"),Xs=require("util"),Jr=ce(require("child_process"),1),Bt=ce(require("fs/promises"),1);ks();vs();Vs();Nr();oa={},ea=(0,Xs.promisify)(Jr.default.execFile),Gr=Zr.default.dirname((0,Js.fileURLToPath)(oa.url)),Gs=Zr.default.join(Gr,"xdg-open"),{platform:nt,arch:qs}=qr.default;zs=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},dt=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return zs(r.app,c=>dt({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return zs(e,c=>dt({...r,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=Fe?await ta():await Vr();if(l.id in c){let h=c[l.id];return e==="browserPrivate"&&t.push(u[h]),dt({...r,app:{name:Me[h],arguments:t}})}throw new Error(`${l.name} is not supported as a default browser`)}let n,s=[],o={};if(nt==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(nt==="win32"||Fe&&!ze()&&!e){n=await $r(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Fe||(o.windowsVerbatimArguments=!0);let c=["Start"];r.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&c.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),c.push("-ArgumentList",t.join(","))),r.target=zr.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let c=!Gr||Gr==="/",u=!1;try{await Bt.default.access(Gs,Bt.constants.X_OK),u=!0}catch{}n=qr.default.versions.electron??(nt==="android"||c||!u)?"xdg-open":Gs}t.length>0&&s.push(...t),r.wait||(o.stdio="ignore",o.detached=!0)}nt==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let a=Jr.default.spawn(n,s,o);return r.wait?new Promise((c,u)=>{a.once("error",u),a.once("close",l=>{if(!r.allowNonzeroExitCode&&l>0){u(new Error(`Exited with code ${l}`));return}c(a)})}):(a.unref(),a)},ra=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return dt({...e,target:r})},na=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return dt({...e,app:{name:r,arguments:t}})};Me={};$e(Me,"chrome",()=>Wt({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));$e(Me,"brave",()=>Wt({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));$e(Me,"firefox",()=>Wt({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));$e(Me,"edge",()=>Wt({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));$e(Me,"browser",()=>"browser");$e(Me,"browserPrivate",()=>"browserPrivate");sa=ra});var un=ce(ln(),1),{program:ya,createCommand:Ea,createArgument:Sa,createOption:Ca,CommanderError:wa,InvalidArgumentError:Aa,InvalidOptionArgumentError:_a,Command:fn,Argument:ba,Option:xa,Help:Ia}=un.default;var dn=!1,pn=!1;function mn(r,e){dn=r,pn=e}function x(){return dn?!0:pn?!1:!process.stdout.isTTY}function j(r,e){console.log(JSON.stringify({ok:!0,command:r,data:e}))}function P(r,e,t){console.log(JSON.stringify({ok:!1,command:r,errors:[{code:e,message:t}]}))}function w(r){console.log(r)}function R(r){console.error(r)}function ge(r,e=2){if(r.length===0)return"";let t=[];for(let n of r)for(let s=0;s<n.length;s++)t[s]=Math.max(t[s]||0,n[s].length);return r.map(n=>n.map((s,o)=>o<n.length-1?s.padEnd(t[o]+e):s).join("")).join(`
30
+ `)}var $t=require("fs"),qe=require("path"),As=require("os");me();se();var Sr=require("fs"),ye=require("path"),Te=require("os"),Je=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function be(r){if(r){let n=Je.find(o=>o.id===r);if(n)return n;let s=Je.find(o=>o.dir===`.${r}`||o.dir===r);return s||null}for(let n of Je)if(n.envVars.some(s=>process.env[s]))return n;let e=(0,Te.homedir)(),t=[];for(let n of Je)(0,Sr.existsSync)((0,ye.join)(e,n.dir))&&t.push(n);return t.length===1?t[0]:null}function De(){let r=[],e=(0,Te.homedir)();for(let t of Je)(t.envVars.some(n=>process.env[n])||(0,Sr.existsSync)((0,ye.join)(e,t.dir)))&&r.push(t);return r}function Pe(){let r=De();return r.length>1?`Multiple AI agents detected (${r.map(e=>e.label).join(", ")}). Use --agent to specify: ${r.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${Je.map(e=>e.id).join(", ")})`}function W(r,e){return e?(0,ye.join)(process.cwd(),r.dir,r.skillsSubdir):(0,ye.join)((0,Te.homedir)(),r.dir,r.skillsSubdir)}function te(r,e){return e?(0,ye.join)(process.cwd(),r.dir,"agents"):(0,ye.join)((0,Te.homedir)(),r.dir,"agents")}function re(r,e){return e?(0,ye.join)(process.cwd(),".mcp.json"):r.id==="claude-code"?(0,ye.join)((0,Te.homedir)(),".claude.json"):r.id==="cursor"?(0,ye.join)((0,Te.homedir)(),".cursor","mcp.json"):(0,ye.join)(process.cwd(),".mcp.json")}function fe(r,e){return e?(0,ye.join)(process.cwd(),r.dir,"settings.json"):(0,ye.join)((0,Te.homedir)(),r.dir,"settings.json")}var oe=require("fs"),We=require("path");var Ae=require("fs"),we=require("path"),fs=require("child_process");se();var ns=require("child_process"),ss=require("fs"),os=require("path"),is=require("os"),as=ce(rs());se();function Qe(r){let t={"claude-code":"claude",cursor:"cursor","gemini-cli":"gemini"}[r];if(!t)return null;try{return(0,ns.execSync)(`which ${t}`,{stdio:"pipe"}),t}catch{return null}}async function bt(r,e){let t=await Er(r),n=(0,os.join)((0,is.tmpdir)(),`sc-plugin-${e}-${Date.now()}`);return(0,ss.mkdirSync)(n,{recursive:!0}),new as.default(t).extractAllTo(n,!0),n}function xt(r){return{"claude-code":"claude","gemini-cli":"gemini",cursor:"cursor"}[r]||"claude"}me();var je=require("fs"),It=require("path"),cs=".shared-context",ls="project.json";function xe(){let r=(0,It.join)(process.cwd(),cs,ls);if(!(0,je.existsSync)(r))return null;try{let e=JSON.parse((0,je.readFileSync)(r,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function lt(r){let e=(0,It.join)(process.cwd(),cs);(0,je.mkdirSync)(e,{recursive:!0}),(0,je.writeFileSync)((0,It.join)(e,ls),JSON.stringify(r,null,2)+`
31
+ `,"utf-8")}var ds={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function V(r,e){let t=(0,we.resolve)(r);for(let n of e){let s=(0,we.resolve)((0,we.join)(r,n.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${n.path}`);(0,Ae.mkdirSync)((0,we.dirname)(s),{recursive:!0}),(0,Ae.writeFileSync)(s,n.content,"utf-8")}}function xr(r){let e=r.resource.slug||r.resource.id;return`${ds[r.resource.resourceType]||r.resource.resourceType+"s"}/${e}`}function us(r,e,t,n){let s=(0,we.join)(r,e);if(!(0,Ae.existsSync)(s))return{slug:e,renamed:!1};if(!Y().installations.find(u=>{let l=u.installPath.split("/");return l[l.length-1]===e&&u.resourceId!==t}))return{slug:e,renamed:!1};let c=n.resource.orgSlug||n.resource.githubOwner||n.resource.id.slice(0,8);return{slug:`${e}-${c}`,renamed:!0}}function Ir(r,e,t){let n=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"))||t.files.find(l=>l.path.endsWith(".json")&&l.path.includes("resources/"));if(!n)throw new Error("MCP package does not contain a config file");let s=JSON.parse(n.content),o=re(r,e),a=t.resource.slug||t.resource.id,c={};if((0,Ae.existsSync)(o))try{c=JSON.parse((0,Ae.readFileSync)(o,"utf-8"))}catch{c={}}let u=typeof c.mcpServers=="object"&&c.mcpServers&&!Array.isArray(c.mcpServers)?c.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(u,s.mcpServers):u[a]=s,c.mcpServers=u,(0,Ae.mkdirSync)((0,we.dirname)(o),{recursive:!0}),(0,Ae.writeFileSync)(o,JSON.stringify(c,null,2)+`
32
+ `,"utf-8")}function Si(r,e,t,n){let s=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),a=fe(r,e),c={},u=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:o;for(let[l,h]of Object.entries(u))if(!(l==="name"||l==="description")&&Array.isArray(h)){c[l]||(c[l]=[]);for(let S of h)c[l].push(S)}if(Object.keys(c).length===0)throw new Error("Hook package does not contain any hook event handlers");return Or(a,c,n),a}function ps(r){r.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=be(s.agent);if(!o){let i=Pe();x()?P("install","NO_AGENTS",i):R(i),process.exit(1)}let a=M(),u=await G(`${a?"/api/cli/resource":"/api/public/resource"}/${e}`);u.ok||(x()?P("install",u.error.code,u.error.message):R(`Install failed: ${u.error.message}`),process.exit(1));let l=u.data,h=l.resource.slug||l.resource.id,S=xr(l),_,d="decomposed",m;if(l.resource.resourceType==="agent"){let i=te(o,!!s.project),y=us(i,h,l.resource.id,l);y.renamed&&(h=y.slug,S=xr({...l,resource:{...l.resource,slug:h}}),x()||w(`Note: Renamed to "${h}" (collision with existing resource)`)),_=(0,we.join)(i,h);try{V(_,l.files)}catch(E){x()?P("install","WRITE_FAILED",`Failed to write files: ${E}`):R(`Failed to write files: ${E}`),process.exit(1)}}else if(l.resource.resourceType==="mcp"){_="";try{Ir(o,!!s.project,l)}catch(i){x()?P("install","WRITE_FAILED",`Failed to install MCP config: ${i}`):R(`Failed to install MCP config: ${i}`),process.exit(1)}}else if(l.resource.resourceType==="hook"){_="";try{Si(o,!!s.project,l,S)}catch(i){x()?P("install","WRITE_FAILED",`Failed to install hook config: ${i}`):R(`Failed to install hook config: ${i}`),process.exit(1)}}else{let i=W(o,!!s.project);if(l.resource.resourceType!=="collection"){let y=us(i,h,l.resource.id,l);y.renamed&&(h=y.slug,S=xr({...l,resource:{...l.resource,slug:h}}),x()||w(`Note: Renamed to "${h}" (collision with existing resource)`))}_=(0,we.join)(i,h);try{if(l.resource.resourceType==="collection"){let y=Qe(o.id);if(y)try{let E=l.resource.slug||l.resource.id,b=l.resource.orgSlug||"",A=xt(o.id),I=a?`/api/cli/resource/collections/${b}/${E}?format=plugin&platform=${A}`:`/api/public/resource/collections/${b}/${E}?format=plugin&platform=${A}`,O=await bt(I,E);(0,fs.execSync)(`${y} plugin install "${O}"`,{stdio:"pipe"}),_=O,d="plugin",m=O,x()||w(`Installed as native ${y} plugin`)}catch(E){x()||R(`Native plugin install failed, falling back to decomposed: ${E}`);let A=await Ie(o).install(l,s.project?"project":"user",o);_=A.installDir;for(let I of A.warnings)x()||R(`Warning: ${I}`)}else{let b=await Ie(o).install(l,s.project?"project":"user",o);if(_=b.installDir,!x())for(let A of b.warnings)R(`Warning: ${A}`)}}else V(_,l.files)}catch(y){x()?P("install","WRITE_FAILED",`Failed to write files: ${y}`):R(`Failed to write files: ${y}`),process.exit(1)}}let p;if(a&&l.resource.latestSha){let i=await L("/api/cli/install",{resourceId:l.resource.id,agentPlatform:o.platform,installedSha:l.resource.latestSha});i.ok||(p=`Could not record install on server: ${i.error.message}`,x()||R(`Warning: ${p}`))}let f=s.project?xe():null;f&&a&&await L(`/api/cli/projects/${f.projectId}/resources`,{resourceId:l.resource.id}).catch(()=>{});let g={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},C=l.resource.resourceType==="collection";if(ue({resourceId:l.resource.id,slug:h,installPath:S,title:l.resource.title,sha:l.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),...C?{pluginFormat:g[o.id]||"directory",memberCount:l.memberResources?.length,installMode:d,pluginDir:m}:{},...f?{projectId:f.projectId}:{}}),l.memberResources&&l.resource.resourceType==="collection"){if(d==="decomposed")for(let i of l.memberResources){let y=i.slug||i.id,b=`${ds[i.resourceType]||i.resourceType+"s"}/${y}`;ue({resourceId:i.id,slug:y,installPath:b,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:l.resource.id})}for(let i of l.memberResources)a&&i.latestSha&&await L("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{})}if(x())j("install",{installPath:S,title:l.resource.title,path:_||void 0,files:l.files.length,...l.resource.resourceType==="mcp"?{mcpConfigPath:re(o,!!s.project)}:{},...l.resource.resourceType==="hook"?{settingsPath:fe(o,!!s.project)}:{},...l.memberResources?{memberResources:l.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...p&&{warning:p}});else{if(l.resource.resourceType==="mcp"?w(`Installed MCP "${l.resource.title}" to ${re(o,!!s.project)}`):l.resource.resourceType==="hook"?w(`Installed hook "${l.resource.title}" to ${fe(o,!!s.project)}`):l.memberResources&&l.memberResources.length>0?w(`Installed "${l.resource.title}" (${l.memberResources.length} resources)`):w(`Installed "${l.resource.title}" to ${_}`),l.resource.resourceType!=="mcp"&&l.resource.resourceType!=="hook"&&!(l.memberResources&&l.memberResources.length>0)&&w(` ${l.files.length} file${l.files.length===1?"":"s"} written`),l.memberResources&&l.memberResources.length>0){let i={};for(let E of l.memberResources){let b=E.resourceType||"other";i[b]||(i[b]=[]),i[b].push(E.title)}let y={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};w("");for(let[E,b]of Object.entries(i)){let A=y[E]||E;w(` ${A}: ${b.join(", ")}`)}}a||(w(""),w("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var Ot=class{buildFiles(e){let t=[],n=[],s=[],o={},a={};for(let c of e.files){let u=c.path.split("/"),l=u[0];if(l==="agents")s.push({path:c.path.slice(7),content:c.content});else if(l==="mcps"){if(c.path.endsWith(".json"))try{let h=JSON.parse(c.content);if(h.mcpServers&&typeof h.mcpServers=="object")Object.assign(o,h.mcpServers);else if(c.path.includes("resources/")){let S=u.indexOf("resources"),_=S>0?u[S-1]:u[1];o[_]=h}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(l==="hooks"){if(c.path.endsWith(".json"))try{let h=JSON.parse(c.content),S=c.path.replace(/\/[^/]+$/,"");Ci(h,a,S)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else l==="skills"||l==="commands"||l==="files"?n.push({path:c.path.slice(l.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",a=e.resource.slug||e.resource.id,c=W(n,o),u=_i(e),l=(0,We.join)(c,...u),h=0;if(s.mainFiles.length>0){let S=s.mainFiles.filter(d=>!d.path.includes("/")),_=s.mainFiles.filter(d=>d.path.includes("/"));if(S.length>0){let d=S.find(m=>m.path==="README.md");d&&S.push({path:"SKILL.md",content:Ai(e,d.content)}),V(l,S),h+=S.length}_.length>0&&(V(c,_),h+=_.length)}if(s.agentFiles.length>0){let S=te(n,o);V(S,s.agentFiles),h+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&wi(re(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Or(fe(n,o),s.hookEntries),{installDir:l,filesWritten:h,warnings:s.warnings}}async uninstall(e,t,n,s){let o=[],c=W(n,t==="project"),u=(0,We.join)(c,e),l=!1;return(0,oe.existsSync)(u)&&((0,oe.rmSync)(u,{recursive:!0,force:!0}),l=!0),l||o.push(`Collection directory not found at ${u}`),{removed:l,warnings:o}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,We.join)(s,e)}};function Ci(r,e,t){if(!r||typeof r!="object")return;let n=r,s=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:n;for(let[o,a]of Object.entries(s))if(!(o==="name"||o==="description")&&Array.isArray(a)){e[o]||(e[o]=[]);for(let c of a){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c;e[o].push(u)}}}function Or(r,e,t){let n={};if((0,oe.existsSync)(r))try{n=JSON.parse((0,oe.readFileSync)(r,"utf-8"))}catch{n={}}let s=typeof n.hooks=="object"&&n.hooks&&!Array.isArray(n.hooks)?n.hooks:{};if(t)for(let[o,a]of Object.entries(s))Array.isArray(a)&&(s[o]=a.filter(c=>!c||typeof c!="object"||c._sc!==t),s[o].length===0&&delete s[o]);for(let[o,a]of Object.entries(e)){Array.isArray(s[o])||(s[o]=[]);for(let c of a){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c,l=JSON.stringify(u);s[o].some(S=>JSON.stringify(S)===l)||s[o].push(u)}}n.hooks=s,(0,oe.mkdirSync)((0,We.dirname)(r),{recursive:!0}),(0,oe.writeFileSync)(r,JSON.stringify(n,null,2)+`
33
+ `,"utf-8")}function kr(r,e){if(!(0,oe.existsSync)(r))return!1;let t;try{t=JSON.parse((0,oe.readFileSync)(r,"utf-8"))}catch{return!1}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!n)return!1;let s=!1;for(let[o,a]of Object.entries(n)){if(!Array.isArray(a))continue;let c=a.filter(u=>!u||typeof u!="object"||u._sc!==e);c.length!==a.length&&(s=!0,c.length===0?delete n[o]:n[o]=c)}return s&&(t.hooks=n,(0,oe.writeFileSync)(r,JSON.stringify(t,null,2)+`
34
+ `,"utf-8")),s}function wi(r,e){let t={};if((0,oe.existsSync)(r))try{t=JSON.parse((0,oe.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,oe.mkdirSync)((0,We.dirname)(r),{recursive:!0}),(0,oe.writeFileSync)(r,JSON.stringify(t,null,2)+`
35
+ `,"utf-8")}function Ai(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
36
+ `)}function _i(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var de=require("fs"),Ve=require("path");var bi={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},kt=class{buildFiles(e){let t=[],n=[],s=[],o={},a={};for(let c of e.files){let u=c.path.split("/"),l=u[0];if(l==="agents")s.push({path:c.path.slice(7),content:c.content});else if(l==="mcps"){if(c.path.endsWith(".json"))try{let h=JSON.parse(c.content);if(h.mcpServers&&typeof h.mcpServers=="object")Object.assign(o,h.mcpServers);else if(c.path.includes("resources/")){let S=u.indexOf("resources"),_=S>0?u[S-1]:u[1];o[_]=h}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(l==="hooks"){if(c.path.endsWith(".json"))try{let h=JSON.parse(c.content);xi(h,a)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else l==="skills"||l==="commands"||l==="files"?n.push({path:c.path.slice(l.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",a=e.resource.slug||e.resource.id,c=W(n,o),u=vi(e),l=(0,Ve.join)(c,...u),h=0;if(s.mainFiles.length>0){let S=s.mainFiles.filter(d=>!d.path.includes("/")),_=s.mainFiles.filter(d=>d.path.includes("/"));if(S.length>0){let d=S.find(m=>m.path==="README.md");d&&S.push({path:"SKILL.md",content:ki(e,d.content)}),V(l,S),h+=S.length}_.length>0&&(V(c,_),h+=_.length)}if(s.agentFiles.length>0){let S=te(n,o);V(S,s.agentFiles),h+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Oi(re(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Ii(fe(n,o),s.hookEntries),{installDir:l,filesWritten:h,warnings:s.warnings}}async uninstall(e,t,n){let s=[],a=W(n,t==="project"),c=(0,Ve.join)(a,e),u=!1;return(0,de.existsSync)(c)&&((0,de.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Ve.join)(s,e)}};function xi(r,e){if(!r||typeof r!="object")return;let t=r,n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(n)){if(s==="name"||s==="description"||!Array.isArray(o))continue;let a=bi[s]||s;e[a]||(e[a]=[]);for(let c of o)e[a].push(c)}}function Ii(r,e){let t={};if((0,de.existsSync)(r))try{t=JSON.parse((0,de.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,o]of Object.entries(e)){Array.isArray(n[s])||(n[s]=[]);for(let a of o){let c=JSON.stringify(a);n[s].some(l=>JSON.stringify(l)===c)||n[s].push(a)}}t.hooks=n,(0,de.mkdirSync)((0,Ve.dirname)(r),{recursive:!0}),(0,de.writeFileSync)(r,JSON.stringify(t,null,2)+`
37
+ `,"utf-8")}function Oi(r,e){let t={};if((0,de.existsSync)(r))try{t=JSON.parse((0,de.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,de.mkdirSync)((0,Ve.dirname)(r),{recursive:!0}),(0,de.writeFileSync)(r,JSON.stringify(t,null,2)+`
38
+ `,"utf-8")}function ki(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
39
+ `)}function vi(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var ie=require("fs"),ve=require("path");var vt=class{buildFiles(e){let t=[],n=[],s=[],o={},a=[],c=e.resource.slug||e.resource.id;for(let u of e.files){let l=u.path.split("/"),h=l[0];if(h==="agents")s.push({path:u.path.slice(7),content:u.content});else if(h==="mcps"){if(u.path.endsWith(".json"))try{let S=JSON.parse(u.content);if(S.mcpServers&&typeof S.mcpServers=="object")Object.assign(o,S.mcpServers);else if(u.path.includes("resources/")){let _=l.indexOf("resources"),d=_>0?l[_-1]:l[1];o[d]=S}}catch{t.push(`Failed to parse MCP config: ${u.path}`)}}else h==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${u.path})`):h==="skills"||h==="commands"||h==="files"?n.push({path:u.path.slice(h.length+1),content:u.content}):n.push(u)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:a,warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",a=W(n,o),c=Di(e),u=(0,ve.join)(a,...c),l=0;if(s.mainFiles.length>0){let h=s.mainFiles.filter(_=>!_.path.includes("/")),S=s.mainFiles.filter(_=>_.path.includes("/"));if(h.length>0){let _=h.find(d=>d.path==="README.md");_&&h.push({path:"SKILL.md",content:Ti(e,_.content)}),V(u,h),l+=h.length}S.length>0&&(V(a,S),l+=S.length)}if(s.agentFiles.length>0){let h=te(n,o);V(h,s.agentFiles),l+=s.agentFiles.length}for(let h of s.customFiles)(0,ie.mkdirSync)((0,ve.dirname)(h.absolutePath),{recursive:!0}),(0,ie.writeFileSync)(h.absolutePath,h.content,"utf-8"),l++;return Object.keys(s.mcpEntries).length>0&&Ri(re(n,o),s.mcpEntries),{installDir:u,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,n){let s=[],a=W(n,t==="project"),c=(0,ve.join)(a,e),u=!1;(0,ie.existsSync)(c)&&((0,ie.rmSync)(c,{recursive:!0,force:!0}),u=!0);let l=(0,ve.join)(homedir(),".cursor","rules");if((0,ie.existsSync)(l))try{let h=(0,ie.readdirSync)(l);for(let S of h)S.startsWith(`${e}-`)&&S.endsWith(".mdc")&&((0,ie.unlinkSync)((0,ve.join)(l,S)),u=!0)}catch{s.push("Could not clean up Cursor rules")}return u||s.push(`Collection not found for Cursor at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,ve.join)(s,e)}};function Ri(r,e){let t={};if((0,ie.existsSync)(r))try{t=JSON.parse((0,ie.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,ie.mkdirSync)((0,ve.dirname)(r),{recursive:!0}),(0,ie.writeFileSync)(r,JSON.stringify(t,null,2)+`
40
+ `,"utf-8")}function Ti(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
41
+ `)}function Di(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Dt=require("fs"),Rt=require("path");var Tt=class{buildFiles(e){let t=[],n=[],s=[];for(let o of e.files){let c=o.path.split("/")[0];c==="agents"?s.push({path:o.path.slice(7),content:o.content}):c==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):c==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):c==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):c==="skills"||c==="files"?n.push({path:o.path.slice(c.length+1),content:o.content}):n.push(o)}return{mainFiles:n,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",a=W(n,o),c=Ni(e),u=(0,Rt.join)(a,...c),l=0;if(s.mainFiles.length>0){let h=s.mainFiles.filter(_=>!_.path.includes("/")),S=s.mainFiles.filter(_=>_.path.includes("/"));if(h.length>0){let _=h.find(d=>d.path==="README.md");_&&h.push({path:"SKILL.md",content:Pi(e,_.content)}),V(u,h),l+=h.length}S.length>0&&(V(a,S),l+=S.length)}if(s.agentFiles.length>0){let h=te(n,o);V(h,s.agentFiles),l+=s.agentFiles.length}return{installDir:u,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,n){let s=[],a=W(n,t==="project"),c=(0,Rt.join)(a,e),u=!1;return(0,Dt.existsSync)(c)&&((0,Dt.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Rt.join)(s,e)}};function Pi(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
42
+ `)}function Ni(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var _e=require("fs"),et=require("path");var Pt=class{buildFiles(e){let t=[],n=[],s={};for(let o of e.files){let a=o.path.split("/"),c=a[0];if(c==="agents")n.push({path:o.path.slice(7),content:o.content});else if(c==="mcps"){if(o.path.endsWith(".json"))try{let u=JSON.parse(o.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(s,u.mcpServers);else if(o.path.includes("resources/")){let l=a.indexOf("resources"),h=l>0?a[l-1]:a[1];s[h]=u}}catch{}}else c==="skills"||c==="commands"||c==="hooks"||c==="files"?t.push({path:o.path.slice(c.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:n,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",a=W(n,o),c=Li(e),u=(0,et.join)(a,...c),l=0;if(s.mainFiles.length>0){let h=s.mainFiles.filter(_=>!_.path.includes("/")),S=s.mainFiles.filter(_=>_.path.includes("/"));h.length>0&&(V(u,h),l+=h.length),S.length>0&&(V(a,S),l+=S.length)}if(s.agentFiles.length>0){let h=te(n,o);V(h,s.agentFiles),l+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&ji(re(n,o),s.mcpEntries),{installDir:u,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,n){let o=W(n,t==="project"),a=(0,et.join)(o,e),c=!1;return(0,_e.existsSync)(a)&&((0,_e.rmSync)(a,{recursive:!0,force:!0}),c=!0),{removed:c,warnings:[]}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,et.join)(s,e)}};function ji(r,e){let t={};if((0,_e.existsSync)(r))try{t=JSON.parse((0,_e.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,_e.mkdirSync)((0,et.dirname)(r),{recursive:!0}),(0,_e.writeFileSync)(r,JSON.stringify(t,null,2)+`
43
+ `,"utf-8")}function Li(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}function Ie(r){switch(r.id){case"claude-code":return new Ot;case"gemini-cli":case"antigravity":return new kt;case"cursor":return new vt;case"codex":return new Tt;default:return new Pt}}var ms=`---
44
+ name: Context Manager
45
+ description: "Your AI chief of staff \u2014 distills expert knowledge into resources, finds off-the-shelf solutions, and manages your working context"
46
+ tools:
47
+ - Read
48
+ - Write
49
+ - Edit
50
+ - Bash
51
+ - Grep
52
+ - Glob
53
+ - Agent
54
+ - WebSearch
46
55
  ---
47
56
 
48
- # Resource Manager
57
+ # Context Manager
49
58
 
50
- You have access to the Shared Context resource library \u2014 a curated collection of AI skills, agents, hooks, MCPs, and collections you can search, install, and manage via the CLI.
59
+ You are a chief of staff for AI automation. You help knowledge workers build their AI workforce \u2014 distilling their expertise into well-structured resources (agents, skills, hooks, collections) and sourcing off-the-shelf solutions from the Shared Context library when custom building isn't needed.
51
60
 
52
- ## IMPORTANT: Search Before Creating
61
+ ## Build vs Source: When to Search the Library First
53
62
 
54
- **Before creating any new resource, ALWAYS search this library first.** A proven, community-tested resource is better than one improvised from scratch.
63
+ **Search the library first** when:
64
+ - The user wants a tool connector or MCP (e.g., "I need to connect to Slack")
65
+ - The user wants a common task automated but doesn't have strong opinions about *how*
66
+ - The user doesn't have the domain expertise to teach
67
+ - The task is generic and not company-specific
55
68
 
56
- Search when:
69
+ **Build custom** when:
70
+ - The user has domain expertise they want to encode ("here's how I do code reviews")
71
+ - The workflow is company-specific with unique steps, templates, or constraints
72
+ - Existing library resources are close but miss critical requirements
73
+ - The task requires specific judgment calls that only this user can define
57
74
 
58
- - The user asks for help in any domain (testing, deployment, debugging, code review, etc.)
59
- - A structured workflow or best-practice approach would be valuable
60
- - You want to **do something well** rather than improvise
61
-
62
- Do **not** search when you already have an installed resource that covers the task, or when the request is trivially simple.
63
-
64
- ## Quick Reference
75
+ ## CLI Quick Reference
65
76
 
66
77
  | Action | Command |
67
78
  |--------|---------|
@@ -72,147 +83,80 @@ Do **not** search when you already have an installed resource that covers the ta
72
83
  | Sync state | \`npx shared-context-ai sync\` |
73
84
  | Check updates | \`npx shared-context-ai check\` |
74
85
  | Update all | \`npx shared-context-ai update\` |
75
- | Update one | \`npx shared-context-ai update <installPath>\` |
76
86
  | Uninstall | \`npx shared-context-ai uninstall <installPath>\` |
77
87
  | Status | \`npx shared-context-ai status\` |
78
88
 
79
- ## How to Search Effectively
89
+ ### How to Search Effectively
80
90
 
81
91
  Use specific keywords. Separate multiple keywords with commas \u2014 the search returns results matching **all** terms.
82
92
 
83
93
  \`\`\`bash
84
- # Single keyword
85
94
  npx shared-context-ai search "testing"
86
- npx shared-context-ai search "deployment"
87
-
88
- # Multiple keywords (comma-separated, AND logic)
89
95
  npx shared-context-ai search "react,testing"
90
- npx shared-context-ai search "CI/CD,pipeline,docker"
91
-
92
- # Filter by resource type
93
96
  npx shared-context-ai search "code review" --type skill
94
- npx shared-context-ai search "linting" --type hook
95
97
  npx shared-context-ai search "database" --type mcp
96
- npx shared-context-ai search "onboarding" --type collection
97
- npx shared-context-ai search "reviewer" --type agent
98
-
99
- # Filter by tag
100
98
  npx shared-context-ai search "deployment" --tag devops
101
99
  \`\`\`
102
100
 
103
- **Flags:** \`--type <type>\` (skill, agent, hook, mcp, collection), \`--tag <tag>\`, \`--limit <n>\` (default: 20)
104
-
105
- **Tip:** Use commas to combine keywords, not spaces. \`"react,testing"\` finds resources about both react AND testing. \`"react testing"\` searches for the exact phrase.
106
-
107
- **JSON output includes \`installPath\` and \`installCommand\`** \u2014 use \`installPath\` directly with \`preview\`, \`install\`, \`update\`, and \`uninstall\` commands. No need to construct paths manually.
108
-
109
- ## How to Present Results
110
-
111
- After searching, **show the user what you found before installing**. Let them choose.
112
-
113
- 1. Run \`npx shared-context-ai search "query"\` and review the results
114
- 2. Pick the 1-3 most relevant matches
115
- 3. Tell the user: the resource name, what it does, type, and install count (as a quality signal)
116
- 4. Preview with \`npx shared-context-ai preview <installPath>\` to confirm it fits
117
- 5. Ask the user if they'd like to install it
118
-
119
- If no resources match, say so and proceed with your best approach. Don't search repeatedly for the same thing.
120
-
121
- ## Install Paths by Resource Type
122
-
123
- The \`installPath\` from search results works with all commands:
101
+ ### Install Paths
124
102
 
125
103
  \`\`\`bash
126
- # Skills
127
104
  npx shared-context-ai install skills/acme/api-testing
128
-
129
- # Agents
130
105
  npx shared-context-ai install agents/acme/code-reviewer
131
-
132
- # Hooks
133
106
  npx shared-context-ai install hooks/acme/pre-commit-lint
134
-
135
- # MCPs
136
107
  npx shared-context-ai install mcps/acme/postgres-mcp
137
-
138
- # Collections (installs all member resources)
139
108
  npx shared-context-ai install collections/acme/devops-bundle
140
109
  \`\`\`
141
110
 
142
- **Flags:** \`--project\` (project-scoped install), \`--agent <agent>\` (override agent detection)
143
-
144
- Resources install to your agent's directory and are immediately available:
145
- - Skills \u2192 \`~/.claude/skills/{org}/{slug}/\`
146
- - Agents \u2192 \`~/.claude/agents/{org}/{slug}/\`
147
- - Hooks \u2192 merged into \`settings.json\`
148
- - MCPs \u2192 merged into \`.mcp.json\`
149
- - Collections \u2192 all members installed to their respective locations
150
-
151
- ## Other Commands
152
-
153
- \`\`\`bash
154
- npx shared-context-ai list # List installed resources with paths and update status
155
- npx shared-context-ai check # Check for available updates
156
- npx shared-context-ai update # Update all installed resources
157
- npx shared-context-ai update skills/acme/api-testing # Update one resource by path
158
- npx shared-context-ai uninstall skills/acme/api-testing
159
- npx shared-context-ai status # Auth status, detected agents, install count
160
- \`\`\`
161
-
162
- ## Output Modes
163
-
164
- - **Human mode** (default in terminals): Formatted tables
165
- - **JSON mode** (default when piped, or \`--json\`): Machine-readable envelope
166
-
167
- \`\`\`json
168
- {
169
- "ok": true,
170
- "command": "search",
171
- "data": {
172
- "results": [
173
- {
174
- "installPath": "skills/acme/api-testing",
175
- "installCommand": "npx shared-context-ai install skills/acme/api-testing",
176
- "title": "API Testing Guide",
177
- "description": "Comprehensive API testing patterns",
178
- "resourceType": "skill",
179
- "installCount": 42,
180
- "topicTags": ["testing", "api"]
181
- }
182
- ],
183
- "count": 1
184
- }
185
- }
186
- \`\`\`
187
-
188
- **Error codes:** \`NOT_FOUND\`, \`AUTH_MISSING\`, \`NO_AGENTS\`, \`SKILL_NOT_FOUND\`, \`WRITE_FAILED\`, \`API_ERROR\`, \`UNEXPECTED\`
189
- `;var F=require("fs"),L=require("path"),ns=require("crypto");var ft=".context-collection",ht="manifest.json";function es(n,e){return{version:1,name:n.name||"Untitled Plugin",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}function so(n,e){return{version:1,name:n.name||"Untitled Extension",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}function no(n,e){return{version:1,name:n.name||"Untitled Plugin",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}var rr=[{path:`${ft}/${ht}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:es,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:es,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:so,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:no,formatLabel:"Cursor Plugin"}];var ts=[{folder:"skills",mainFile:"SKILL.md",resourceType:"skill",canHaveChildren:!0},{folder:"commands",mainFile:null,resourceType:"skill",canHaveChildren:!0},{folder:"hooks",mainFile:"hook.json",resourceType:"hook",canHaveChildren:!1},{folder:"agents",mainFile:null,resourceType:"agent",canHaveChildren:!0},{folder:"mcps",mainFile:"mcp.json",resourceType:"mcp",canHaveChildren:!0},{folder:"collections",mainFile:"README.md",resourceType:"collection",canHaveChildren:!1}],rs=`${ft}/${ht}`,oo=new Set(["py","sh","js","ts","rb","go","rs","bash","zsh"]),io=new Set(["json","yaml","yml","toml","xml","csv","txt","env","ini","cfg"]);function Ye(n){let e={name:"",description:"",body:n};if(!n.startsWith(`---
190
- `)&&!n.startsWith(`---\r
191
- `))return e;let t=n.indexOf(`
192
- ---`,3);if(t===-1)return e;let r=n.slice(4,t),s=n.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let o={},a={},i=new Set(["requires","tools"]),c={},l=r.split(`
193
- `),u=null,p=!1;for(let y=0;y<l.length;y++){let g=l[y];if(u&&/^\s+-\s/.test(g)){let f=g.replace(/^\s+-\s/,"").trim();if(f){let A=Le(f);p?c[u].push(A):a[u].push(A)}continue}u=null,p=!1;let S=g.indexOf(":");if(S===-1)continue;let d=g.slice(0,S).trim(),h=g.slice(S+1).trim();if(!h&&d&&y+1<l.length&&/^\s+-\s/.test(l[y+1])){u=d,i.has(d)?(p=!0,c[d]=[]):(p=!1,a[d]=[]);continue}d==="name"||d==="title"?e.name=Le(h):d==="description"?e.description=Le(h):d==="skill_class"?e.skillClass=Le(h):d==="service"?e.service=Le(h):d&&h&&(o[d]=Le(h))}return c.requires?.length&&(e.requires=c.requires),c.tools?.length&&(e.tools=c.tools),Object.keys(o).length&&(e.fields=o),Object.keys(a).length&&(e.arrayFields=a),e}function Le(n){let e=n.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")){let t=e.slice(1,-1);return e.startsWith('"')?t.replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.replace(/''/g,"'")}return e}function ao(n){let{body:e}=Ye(n);return e.replace(/\r\n/g,`
194
- `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function $e(n){let e=ao(n);return`sha256:${(0,ns.createHash)("sha256").update(e,"utf8").digest("hex")}`}function ge(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function He(n){try{return(0,F.statSync)(n).isDirectory()}catch{return!1}}function ss(n){try{return(0,F.readdirSync)(n).filter(e=>!e.startsWith(".")&&He((0,L.join)(n,e)))}catch{return[]}}function gt(n){try{return(0,F.readdirSync)(n).filter(e=>!e.startsWith(".")&&!He((0,L.join)(n,e)))}catch{return[]}}function co(n){let e=[],t=(0,L.join)(n,"scripts");if((0,F.existsSync)(t)&&He(t))for(let s of gt(t)){let o=(0,L.extname)(s).slice(1);oo.has(o)&&e.push({category:"script",extension:o,filename:s,content:(0,F.readFileSync)((0,L.join)(t,s),"utf-8")})}let r=(0,L.join)(n,"resources");if((0,F.existsSync)(r)&&He(r))for(let s of gt(r)){let o=(0,L.extname)(s).slice(1);io.has(o)&&e.push({category:"resource",extension:o,filename:s,content:(0,F.readFileSync)((0,L.join)(r,s),"utf-8")})}return e}function We(n,e){let t=[],r=[],s,o;function a(g,S){let d=[],h=[];for(let f of ts){let A=(0,L.join)(g,f.folder);if(!(0,F.existsSync)(A)||!He(A))continue;let O=S?`${S}/${f.folder}`:f.folder;if(f.folder==="files"){for(let C of gt(A)){if(!C.endsWith(".md"))continue;let w=(0,L.join)(A,C),_=(0,F.readFileSync)(w,"utf-8"),k=Ye(_),v=k.name||(0,L.basename)(C,".md"),P=`${O}/${(0,L.basename)(C,".md")}`;d.push({importPath:P,resourceType:"file",title:v,description:k.description||null,body:k.body,bodyHash:$e(_),metadata:{},attachments:[]})}continue}for(let C of ss(A)){let w=f.mainFile||`${C}.md`,_=(0,L.join)(A,C,w);if(!(0,F.existsSync)(_))continue;let k=(0,F.readFileSync)(_,"utf-8"),v=`${O}/${C}`,P,H,R,E={},$=null;if(f.resourceType==="hook"||f.resourceType==="mcp"){try{let ce=JSON.parse(k);P=ce.name||ge(C),H=ce.description||null}catch{P=ge(C),H=null}R=k}else if(f.resourceType==="collection"){let ce=(0,L.join)(A,C,ft,ht);if((0,F.existsSync)(ce))try{let we=JSON.parse((0,F.readFileSync)(ce,"utf-8"));P=we.name||ge(C),H=we.description||null,R=k,we.resources&&Array.isArray(we.resources)&&h.push({collectionImportPath:v,memberImportPaths:we.resources.map(ve=>{let Xe=ve.split("/");return Xe.length>=3?`${Xe[0]}/${Xe[Xe.length-1]}`:ve})})}catch{P=ge(C),H=null,R=k}else $=Ye(k),P=$.name||ge(C),H=$.description||null,R=$.body,$.arrayFields?.resources&&h.push({collectionImportPath:v,memberImportPaths:$.arrayFields.resources.map(we=>{let ve=we.split("/");return ve.length>=3?`${ve[0]}/${ve[ve.length-1]}`:we})})}else $=Ye(k),P=$.name||ge(C),H=$.description||null,R=$.body,$.skillClass&&(E.skillClass=$.skillClass),$.service&&(E.service=$.service),$.requires?.length&&(E.requires=$.requires),$.tools?.length&&(E.tools=$.tools),$.fields&&Object.keys($.fields).length&&(E.fields=$.fields);f.folder==="commands"&&(E.fields||(E.fields={}),E.fields["user-invocable"]="true");let q=f.canHaveChildren?co((0,L.join)(A,C)):[];d.push({importPath:v,resourceType:f.resourceType,title:P,description:H,body:R,bodyHash:$e(k),metadata:E,attachments:q})}}return{resources:d,memberships:h}}let i=a(n,"");t.push(...i.resources),r.push(...i.memberships);let c=new Set;e?.mcpConfigPath&&c.add(e.mcpConfigPath);let l=(0,L.join)(n,".mcp.json");(0,F.existsSync)(l)&&c.add(l);for(let g of c)if((0,F.existsSync)(g))try{let S=JSON.parse((0,F.readFileSync)(g,"utf-8"));if(S.mcpServers&&typeof S.mcpServers=="object")for(let[d,h]of Object.entries(S.mcpServers)){let f=`mcps/${d}`;if(t.some(C=>C.importPath===f))continue;let A=ge(d),O=JSON.stringify({name:A,description:`MCP server: ${d}`,mcpServers:{[d]:h}},null,2);t.push({importPath:f,resourceType:"mcp",title:A,description:`MCP server: ${d}`,body:O,bodyHash:$e(O),metadata:{},attachments:[]})}}catch{}if(e?.settingsPath&&(0,F.existsSync)(e.settingsPath))try{let g=JSON.parse((0,F.readFileSync)(e.settingsPath,"utf-8"));if(g.hooks&&typeof g.hooks=="object"&&!Array.isArray(g.hooks)){let S={};for(let[d,h]of Object.entries(g.hooks))if(Array.isArray(h))for(let f of h){if(!f||typeof f!="object")continue;let A=f,O=A._sc;if(!O)continue;S[O]||(S[O]={}),S[O][d]||(S[O][d]=[]);let{_sc:C,...w}=A;S[O][d].push(w)}for(let[d,h]of Object.entries(S)){let f=d;if(t.some(w=>w.importPath===f))continue;let A=d.split("/").pop()||d,O=ge(A),C=JSON.stringify({name:O,description:`Hook: ${O}`,hooks:h},null,2);t.push({importPath:f,resourceType:"hook",title:O,description:`Hook: ${O}`,body:C,bodyHash:$e(C),metadata:{},attachments:[]})}}}catch{}for(let g of rr){if(g.path===rs)continue;let S=(0,L.join)(n,g.path);if((0,F.existsSync)(S)){try{let d=JSON.parse((0,F.readFileSync)(S,"utf-8"));if(s=s||d.name||void 0,o=g.formatLabel,!t.some(h=>h.resourceType==="collection")){let h=t.filter(w=>w.resourceType!=="collection").map(w=>({resourceRef:w.importPath})),f=g.converter(d,h),A=(0,L.join)(n,"README.md"),O=(0,F.existsSync)(A)?(0,F.readFileSync)(A,"utf-8"):"",C="collections/_root";t.push({importPath:C,resourceType:"collection",title:ge(f.name),description:f.description||null,body:O,bodyHash:$e(O),metadata:{},attachments:[],manifestMetadata:{...f.author?{author:f.author}:{},...f.homepage?{homepage:f.homepage}:{},...f.license?{license:f.license}:{}}}),f.resources.length>0&&r.push({collectionImportPath:C,memberImportPaths:f.resources})}}catch{}break}}{let d=function(h,f,A){if(!(A>4))for(let O of ss(h)){if(S.has(O))continue;let C=(0,L.join)(h,O),w=f?`${f}/${O}`:O;for(let _ of rr){if(_.path===rs)continue;let k=(0,L.join)(C,_.path);if((0,F.existsSync)(k)){if(g.has(w))break;g.add(w);try{let v=JSON.parse((0,F.readFileSync)(k,"utf-8")),P=a(C,w);if(P.resources.length===0)break;t.push(...P.resources),r.push(...P.memberships);let H=P.resources.filter(ce=>ce.resourceType!=="collection").map(ce=>({resourceRef:ce.importPath})),R=_.converter(v,H),E=(0,L.join)(C,"README.md"),$=(0,F.existsSync)(E)?(0,F.readFileSync)(E,"utf-8"):"",q=`${w}/_collection`;t.push({importPath:q,resourceType:"collection",title:ge(R.name),description:R.description||null,body:$,bodyHash:$e($),metadata:{},attachments:[],manifestMetadata:{...R.author?{author:R.author}:{},...R.homepage?{homepage:R.homepage}:{},...R.license?{license:R.license}:{}}}),r.push({collectionImportPath:q,memberImportPaths:P.resources.map(ce=>ce.importPath)}),s||(s=v.name||void 0),o||(o=_.formatLabel)}catch{}break}}d(C,w,A+1)}};var y=d;let g=new Set,S=new Set(ts.map(h=>h.folder));d(n,"",0)}let u=(0,L.join)(n,"files");if((0,F.existsSync)(u)&&He(u)&&!t.some(g=>g.resourceType==="file"))for(let g of gt(u)){if(!g.endsWith(".md"))continue;let S=(0,L.join)(u,g),d=(0,F.readFileSync)(S,"utf-8"),h=Ye(d),f=h.name||(0,L.basename)(g,".md"),A=`files/${(0,L.basename)(g,".md")}`;t.some(O=>O.importPath===A)||t.push({importPath:A,resourceType:"file",title:f,description:h.description||null,body:h.body,bodyHash:$e(d),metadata:{},attachments:[]})}return{resources:[...t.filter(g=>g.resourceType!=="collection"),...t.filter(g=>g.resourceType==="collection")],collectionMemberships:r,pluginName:s,formatLabel:o}}function lo(){if(process.platform==="darwin")try{let{execSync:n}=require("child_process"),e=n("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var Ue="resource-manager",os="Resource Manager",yt="collections/shared-context/essentials";function uo(n,e){let t=M(n,e),r=(0,Ie.join)(t,Ue);return(0,bt.mkdirSync)(r,{recursive:!0}),(0,bt.writeFileSync)((0,Ie.join)(r,"SKILL.md"),Zr,"utf-8"),(0,Ie.join)(r,"SKILL.md")}var po={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function mo(n){return Y().installations.some(t=>t.installPath===yt&&t.agent===n)}function as(n){n.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let r={...e,...t.optsWithGlobals()};if(r.code){let{post:d}=await Promise.resolve().then(()=>(K(),Jr)),{saveAuth:h}=await Promise.resolve().then(()=>(re(),zt)),f=await d("/api/cli/auth",{code:r.code});f.ok?(h({token:f.data.token,email:f.data.user.email,orgId:f.data.org.id,orgSlug:f.data.org.slug,orgName:f.data.org.name,createdAt:new Date().toISOString()}),b()||m(`Authenticated as ${f.data.user.email}`)):N()?b()||m("Auth code already used, continuing with saved credentials."):(b()?j("init",f.error.code,f.error.message):x(`Auth failed: ${f.error.message}`),process.exit(1))}else N()||(b()?(j("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(x("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(r.agent){let d=pe(r.agent);if(!d){let h=`Unknown agent: ${r.agent}. Available: ${Ne().map(f=>f.id).join(", ")||"none detected"}`;b()?j("init","NO_AGENTS",h):x(h),process.exit(1)}s=[d]}else if(s=Ne(),s.length===0){let d=de();b()?j("init","NO_AGENTS",d):x(d),process.exit(1)}let o=ae(),a=lo(),i;if(r.linkProject){if(!o?.token){let k="Authentication required for project linking. Run init with --code first.";b()?j("init","AUTH_REQUIRED",k):x(k),process.exit(1)}let d=s[0],h=await T("/api/cli/register-agent",{platform:d.platform,name:`CLI (${a})`});h.ok&&(i=h.data.connectionId);let f=await T(`/api/cli/projects/${r.linkProject}/join`,{localPath:process.cwd()});f.ok||(b()?j("init",f.error.code,f.error.message):x(`Failed to join project: ${f.error.message}`),process.exit(1));let{project:A,resources:O,members:C}=f.data;Je({projectId:A.id,projectName:A.name,projectSlug:A.slug});let w=be(d),_=[];for(let k of O)try{let v=k.installPath,P=await U(`/api/cli/resource/${v}`);if(!P.ok)continue;let H=P.data;await w.install(H,"project",d),te({resourceId:k.id,slug:k.slug||k.id,installPath:v,title:k.title,sha:k.latestSha||"",scope:"project",agent:d.id,installedAt:new Date().toISOString(),projectId:A.id}),k.latestSha&&await T("/api/cli/install",{resourceId:k.id,agentPlatform:d.platform,installedSha:k.latestSha}).catch(()=>{}),_.push({title:k.title,resourceType:k.resourceType})}catch{}if(await T(`/api/cli/projects/${A.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Fe({lastSyncAt:new Date().toISOString(),lastResult:{updatesAvailable:0,untrackedResources:0}}),b())I("init",{project:{id:A.id,name:A.name,slug:A.slug},agent:d.id,resourcesInstalled:_.length,memberCount:C.length});else{if(m(""),m(`Joined project: ${A.name}`),A.description&&m(`"${A.description}"`),m(""),_.length>0){m(`Installed ${_.length} resource${_.length===1?"":"s"}:`);let k={};for(let P of _)k[P.resourceType]||(k[P.resourceType]=[]),k[P.resourceType].push(P.title);let v={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[P,H]of Object.entries(k))m(` ${v[P]||P}: ${H.join(", ")}`)}else m("No resources to install (project is empty)");C.length>0&&(m(""),m(`Team (${C.length}): ${C.map(k=>k.name).join(", ")}`)),m(""),m("Quick reference:"),m(" shared-context-ai status View project sync status"),m(" shared-context-ai sync Check for resource updates")}return}let c=!1,l=(0,Ie.basename)(process.cwd());if(o?.token&&!me()&&l&&l!=="/")try{let d=await T("/api/cli/projects",{name:l});if(d.ok){let{id:h,name:f,slug:A}=d.data;Je({projectId:h,projectName:f,projectSlug:A}),c=!0,b()||m(`Created project: ${f}`)}}catch{}let u=[],p={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let d of s){let h=!1,f=!1,A=[],O=[];if(o?.token){let C=await T("/api/cli/register-agent",{platform:d.platform,name:`CLI (${a})`});if(C.ok){if(!i){i=C.data.connectionId;let{saveAuth:w}=await Promise.resolve().then(()=>(re(),zt));w({...o,connectionId:i})}}else b()||x(`Warning: Could not register ${d.label} connection: ${C.error.message}`)}if(o?.token&&mo(d.id))f=!0,h=!0;else if(o?.token)try{let C=await U(`/api/cli/resource/${yt}`);if(C.ok){let w=C.data,k=await be(d).install(w,r.project?"project":"user",d);if(te({resourceId:w.resource.id,slug:w.resource.slug||"essentials",installPath:yt,title:w.resource.title,sha:w.resource.latestSha||"",scope:r.project?"project":"global",agent:d.id,installedAt:new Date().toISOString(),pluginFormat:p[d.id]||"directory",memberCount:w.memberResources?.length}),w.resource.latestSha&&await T("/api/cli/install",{resourceId:w.resource.id,agentPlatform:d.platform,installedSha:w.resource.latestSha}).catch(()=>{}),w.memberResources)for(let v of w.memberResources){let P=v.slug||v.id,H=po[v.resourceType]||v.resourceType+"s",R=v.orgSlug||w.resource.orgSlug,E=R?`${H}/${R}/${P}`:`${H}/${P}`;te({resourceId:v.id,slug:P,installPath:E,title:v.title,sha:v.latestSha||"",scope:r.project?"project":"global",agent:d.id,installedAt:new Date().toISOString(),collectionId:w.resource.id}),A.push({title:v.title,resourceType:v.resourceType}),v.latestSha&&await T("/api/cli/install",{resourceId:v.id,agentPlatform:d.platform,installedSha:v.latestSha}).catch(()=>{})}if(h=!0,!b()&&k.warnings.length>0)for(let v of k.warnings)x(`Warning: ${v}`)}}catch{}if(!h&&(uo(d,!!r.project),te({resourceId:"resource-manager",slug:Ue,installPath:`skills/${Ue}`,title:os,sha:"",scope:r.project?"project":"global",agent:d.id,installedAt:new Date().toISOString()}),o?.token))try{let C=`skills/shared-context/${Ue}`,w=await U(`/api/cli/resource/${C}`);if(w.ok&&w.data.resource){let _=w.data.resource;_.latestSha&&await T("/api/cli/install",{resourceId:_.id,agentPlatform:d.platform,installedSha:_.latestSha}),te({resourceId:_.id,slug:_.slug||Ue,installPath:`skills/shared-context/${_.slug||Ue}`,title:_.title||os,sha:_.latestSha||"",scope:r.project?"project":"global",agent:d.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let C=(0,Ie.join)((0,is.homedir)(),d.dir),w=We(C,{settingsPath:Z(d,!!r.project),mcpConfigPath:B(d,!!r.project)}),_=Y(),k=new Set(_.installations.map(R=>R.installPath)),v=new Map;for(let R of _.installations){let E=R.installPath.split("/"),$=E[0],q=E[E.length-1];v.has($)||v.set($,new Set),v.get($).add(q)}let P=new Set(["resource-manager",".claude-plugin"]),H=w.resources.filter(R=>{if(k.has(R.importPath))return!1;let E=R.importPath.split("/"),$=E[0],q=E[E.length-1];return!(($==="mcps"||$==="hooks")&&v.get($)?.has(q)||R.importPath.startsWith(".")||P.has(q))});if(H.length>0){let R={dryRun:!1,onConflict:"auto",visibility:"org",resources:H,collectionMemberships:w.collectionMemberships},E=await T("/api/cli/import",R,12e4);E.ok&&(O=[...E.data.created,...E.data.updated,...E.data.installed].map(q=>({resourceType:q.resourceType||q.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:q.slug||q.importPath.split("/").pop()||"",title:q.importPath.split("/").pop()||""})))}}catch{}u.push({agent:d,collectionInstalled:h,installedMembers:A,importedResources:O,skippedEssentials:f})}if(Fe({lastSyncAt:new Date().toISOString(),lastResult:{updatesAvailable:0,untrackedResources:0}}),i){let d=u.reduce((h,f)=>h+f.importedResources.length,0);T("/api/cli/sync-report",{connectionId:i,lastSyncResult:{updatesAvailable:0,importedCount:d}}).catch(()=>{})}let y=u.every(d=>d.skippedEssentials),g=u.some(d=>!d.skippedEssentials&&d.collectionInstalled),S=u.some(d=>d.importedResources.length>0);if(b()){let d=h=>({agent:h.agent.id,collection:h.collectionInstalled?yt:void 0,resourceManagerOnly:!h.collectionInstalled,skipped:h.skippedEssentials,...h.collectionInstalled&&!h.skippedEssentials?{membersInstalled:h.installedMembers.map(f=>({title:f.title,resourceType:f.resourceType}))}:{},...h.importedResources.length>0?{importedResources:h.importedResources.map(f=>({resourceType:f.resourceType,slug:f.slug,title:f.title}))}:{}});I("init",{...d(u[0]),agents:u.map(d),...c?{projectCreated:!0}:{},authenticated:N()})}else{for(let d of u)if(!d.skippedEssentials){if(m(""),d.collectionInstalled){m(`Shared Context Essentials installed for ${d.agent.label} (${d.installedMembers.length} resources)`);let h={};for(let A of d.installedMembers)h[A.resourceType]||(h[A.resourceType]=[]),h[A.resourceType].push(A.title);let f={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};m("");for(let[A,O]of Object.entries(h)){let C=f[A]||A;m(` ${C}: ${O.join(", ")}`)}}else m(`Shared Context initialized for ${d.agent.label}`),m("Resource Manager installed");if(d.importedResources.length>0){m(""),m(`Imported ${d.importedResources.length} existing resource${d.importedResources.length===1?"":"s"}:`);for(let h of d.importedResources)m(` ${h.resourceType.padEnd(12)} ${h.slug.padEnd(24)} ${h.title}`)}}y&&!c&&!S&&(m(""),m("Already initialized. Nothing to do.")),(g||c||S)&&(m(""),m("Quick reference:"),m(' shared-context-ai search "query" Search for resources'),m(" shared-context-ai install <installPath> Install a resource"),m(" shared-context-ai list List installed resources"),m(" shared-context-ai sync Check updates & discover resources"),m(" shared-context-ai preview <installPath> Preview before installing"))}})}var Ns=require("http"),Ms=require("crypto");re();K();re();async function Ls(n){let e=await T("/api/cli/auth",{code:n});return e.ok?(Gt({token:e.data.token,email:e.data.user.email,orgId:e.data.org.id,orgSlug:e.data.org.slug,orgName:e.data.org.name,createdAt:new Date().toISOString()}),b()?I("login",{email:e.data.user.email,org:e.data.org.slug}):m(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(b()?j("login",e.error.code,e.error.message):x(`Login failed: ${e.error.message}`),!1)}async function Eo(){let n=(0,Ms.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,Ns.createServer)((r,s)=>{let o=new URL(r.url||"/","http://localhost"),a=o.searchParams.get("code"),i=o.searchParams.get("state");if(!a||i!==n){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),Ls(a).then(e)});t.listen(0,"127.0.0.1",async()=>{let r=t.address();if(!r||typeof r=="string"){t.close(),e(!1);return}let s=r.port,a=`${Ae().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${n}`;b()||(m("Opening browser for authentication..."),m(`If the browser doesn't open, visit: ${a}`));try{let i=(await Promise.resolve().then(()=>(Ds(),Fs))).default;await i(a)}catch{b()||m(`Could not open browser. Please visit:
195
- ${a}`)}setTimeout(()=>{t.close(),b()||x("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function Hs(n){n.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await Ls(e.code):t=await Eo(),process.exit(t?0:1)})}K();var Ro={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ws(n){let e=Ro[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${e}/external/${n.githubOwner}/${n.slug}`:n.orgSlug?`${e}/${n.orgSlug}/${n.slug}`:`${e}/${n.slug}`}function Us(n){n.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let r=new URLSearchParams({q:e});t.type&&r.set("type",t.type),t.tag&&r.set("tag",t.tag),t.limit&&r.set("limit",t.limit);let s=N()?`/api/cli/search?${r}`:`/api/public/search?${r}`,o=await U(s);o.ok||(b()?j("search",o.error.code,o.error.message):m(`Search failed: ${o.error.message}`),process.exit(1));let a=o.data.results;if(b()){let c=a.map(l=>{let u=Ws(l);return{installPath:u,installCommand:`npx shared-context-ai install ${u}`,title:l.title,description:l.description,resourceType:l.resourceType,installCount:l.installCount,topicTags:l.topicTags}});I("search",{results:c,count:c.length});return}if(a.length===0){let c=t.type?`${t.type}s`:"results";m(`No ${c} found.`);return}m(`Found ${a.length} result${a.length===1?"":"s"}:
196
- `);let i=a.map(c=>[Ws(c),c.title,`\u2193${c.installCount}`]);m(ne(i)),m(`
197
- Install a skill: npx shared-context-ai install <installPath>`)})}K();re();function Vs(n){let e=n.slug||n.resourceId;return n.storageType==="github"&&n.githubOwner?`skills/external/${n.githubOwner}/${e}`:n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function Bs(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if(N()){let e=await U("/api/cli/installed");e.ok||(b()?j("list",e.error.code,e.error.message):m(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(b()){let s=t.map(o=>({...o,installPath:Vs(o)}));I("list",{installations:s,count:s.length});return}if(t.length===0){m("No skills installed."),m("Use 'shared-context-ai search' to find skills to install.");return}m(`${t.length} skill${t.length===1?"":"s"} installed:
198
- `);let r=t.map(s=>[Vs(s),s.title,s.hasUpdate?"(update available)":"(current)"]);m(ne(r))}else{let t=Y().installations;if(b()){I("list",{installations:t,count:t.length});return}if(t.length===0){m("No skills installed locally.");return}m(`${t.length} skill${t.length===1?"":"s"} installed locally:
199
- `);let r=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);m(ne(r)),m(`
200
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}K();function qs(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let r=N()?"/api/cli/resource":"/api/public/resource",s=await U(`${r}/${e}/preview`);s.ok||(b()?j("preview",s.error.code,s.error.message):x(`Preview failed: ${s.error.message}`),process.exit(1)),b()?I("preview",s.data):m(s.data.content)})}K();function Gs(n){n.command("check").description("Check for skill updates").action(async()=>{N()||(b()?j("check","AUTH_MISSING","Login required to check for updates."):x("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await U("/api/cli/updates");e.ok||(b()?j("check",e.error.code,e.error.message):x(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:r}=e.data;if(b()){I("check",{updates:t,count:r});return}if(r===0){m("All skills are up to date.");return}m(`${r} update${r===1?"":"s"} available:
201
- `);let s=t.map(o=>{let a=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${a}`:o.orgSlug?`skills/${o.orgSlug}/${a}`:`skills/${a}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});m(ne(s)),m(`
202
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var kr=require("path");K();re();var $o={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Js(n){let e=n.slug||n.resourceId,t=$o[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${t}/external/${n.githubOwner}/${e}`:n.orgSlug?`${t}/${n.orgSlug}/${e}`:`${t}/${e}`}function Ys(n){n.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,r)=>{let s=r.optsWithGlobals();N()||(b()?j("update","AUTH_MISSING","Login required to update resources."):x("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=pe(s.agent);if(!o){let l=de();b()?j("update","NO_AGENTS",l):x(l),process.exit(1)}let a=await U("/api/cli/updates");a.ok||(b()?j("update",a.error.code,a.error.message):x(`Failed to check updates: ${a.error.message}`),process.exit(1));let i=a.data.updates;if(e&&(i=i.filter(l=>Js(l)===e||l.slug===e||l.resourceId===e),i.length===0)){b()?j("update","SKILL_NOT_FOUND",`No update available for "${e}".`):m(`No update available for "${e}".`);return}if(i.length===0){b()?I("update",{updated:[],count:0}):m("All resources are up to date.");return}let c=[];for(let l of i){let u=Js(l),p=await U(`/api/cli/resource/${u}`);if(!p.ok){b()||x(` Failed to fetch ${u}: ${p.error.message}`);continue}let y=p.data,g=u.split("/").slice(1);if(y.resource.resourceType==="agent"){let S=z(o,!!s.project),d=(0,kr.join)(S,...g);W(d,y.files)}else if(y.resource.resourceType==="mcp")Zt(o,!!s.project,y);else{let S=M(o,!!s.project),d=(0,kr.join)(S,...g);W(d,y.files)}y.resource.latestSha&&await T("/api/cli/update",{resourceId:y.resource.id,installedSha:y.resource.latestSha}),te({resourceId:y.resource.id,slug:y.resource.slug||y.resource.id,installPath:u,title:y.resource.title,sha:y.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString()}),c.push({installPath:u,title:y.resource.title}),b()||m(` Updated ${u}`)}b()?I("update",{updated:c,count:c.length}):c.length>0&&m(`
203
- ${c.length} resource${c.length===1?"":"s"} updated.`)})}var V=require("fs"),Be=require("path");K();re();function Ks(n){n.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{if(!e){let S=Y().installations;if(S.length===0&&(b()?j("uninstall","NOTHING_INSTALLED","No resources installed."):m("No resources installed."),process.exit(0)),b())I("uninstall",{installations:S.map(d=>({path:d.installPath||d.slug,title:d.title,agent:d.agent}))});else{m(`Installed resources:
204
- `);let d=S.map(h=>[h.installPath||h.slug,h.title||"",`(${h.agent})`]);m(ne(d)),m(`
205
- Usage: shared-context-ai uninstall <path>`)}return}let s=r.optsWithGlobals(),o=pe(s.agent);if(!o){let g=de();b()?j("uninstall","NO_AGENTS",g):x(g),process.exit(1)}let i=Y().installations.find(g=>g.installPath===e||g.slug===e||g.resourceId===e),c=e.split("/"),u=["skills","files","commands","hooks","collections","agents","mcps"].includes(c[0])?c[0]:null,p=u?c.slice(1):c,y=!1;if(u==="collections"){let g=be(o),S=p[p.length-1],d=s.project?"project":"user",h=await g.uninstall(S,d,o,i?.resourceId);if(y=h.removed,!b())for(let f of h.warnings)x(`Warning: ${f}`);if(i){let A=Y().installations.filter(O=>O.collectionId===i.resourceId&&O.agent===o.id);for(let O of A){let C=O.installPath.split("/"),w=C[0],_=C.slice(1);if(w==="agents"){let k=z(o,!!s.project),v=(0,Be.join)(k,..._);(0,V.existsSync)(v)&&(0,V.rmSync)(v,{recursive:!0,force:!0})}else if(w==="mcps"){let k=_[_.length-1],v=B(o,!!s.project);if((0,V.existsSync)(v))try{let P=JSON.parse((0,V.readFileSync)(v,"utf-8"));if(typeof P.mcpServers=="object"&&P.mcpServers&&!Array.isArray(P.mcpServers)){let H=P.mcpServers;k in H&&(delete H[k],P.mcpServers=H,(0,V.writeFileSync)(v,JSON.stringify(P,null,2)+`
206
- `,"utf-8"))}}catch{}}else if(w==="hooks")tr(Z(o,!!s.project),O.installPath);else{let k=M(o,!!s.project),v=(0,Be.join)(k,..._);(0,V.existsSync)(v)&&(0,V.rmSync)(v,{recursive:!0,force:!0})}st(O.resourceId,o.id)}}}else if(u==="agents"){let g=z(o,!!s.project),S=(0,Be.join)(g,...p);y=(0,V.existsSync)(S),y&&(0,V.rmSync)(S,{recursive:!0,force:!0})}else if(u==="mcps"){let g=p[p.length-1],S=B(o,!!s.project);if((0,V.existsSync)(S))try{let d=JSON.parse((0,V.readFileSync)(S,"utf-8"));if(typeof d.mcpServers=="object"&&d.mcpServers&&!Array.isArray(d.mcpServers)){let h=d.mcpServers;g in h&&(delete h[g],d.mcpServers=h,(0,V.writeFileSync)(S,JSON.stringify(d,null,2)+`
207
- `,"utf-8"),y=!0)}}catch{}}else if(u==="hooks"){let g=Z(o,!!s.project);y=tr(g,e),!y&&!b()&&x(`Note: No tagged hook entries found in ${g} \u2014 may need manual removal if installed before v0.1.10`)}else{let g=M(o,!!s.project),S=(0,Be.join)(g,...p);if(y=(0,V.existsSync)(S),y&&(0,V.rmSync)(S,{recursive:!0,force:!0}),!y&&i?.slug){let d=(0,Be.join)(g,i.slug);(0,V.existsSync)(d)&&(0,V.rmSync)(d,{recursive:!0,force:!0})}}if(N()&&i){let g=await T("/api/cli/uninstall",{resourceId:i.resourceId});!g.ok&&!b()&&x(`Warning: Could not record uninstall on server: ${g.error.message}`)}i&&st(i.resourceId,o.id),b()?I("uninstall",{path:e,removed:!0}):m(`Uninstalled "${e}"`)})}re();K();function zs(n){n.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=ae(),t=Ae(),r=Y(),s=Ne(),o=me(),a=r.installations.filter(p=>!p.projectId),i=r.installations.filter(p=>p.projectId),c=new Map;for(let p of i){let y=p.projectId;c.has(y)||c.set(y,[]),c.get(y).push(p)}let l=[];if(N()&&c.size>0)for(let[p,y]of c){let g=await U(`/api/cli/projects/${p}/resources`).catch(()=>null),S=g&&g.ok?g.data.resources.length:y.length,d=o?.projectId===p?o.projectName:`Project ${p.slice(0,8)}`;l.push({projectId:p,projectName:d,localCount:y.length,serverCount:S,synced:y.length>=S})}let u={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(p=>p.id),installedCount:r.installations.length,globalCount:a.length,projects:l};if(b()){I("status",u);return}if(m("Shared Context CLI Status"),m("\u2500".repeat(40)),e?.token?m(` Auth: ${e.email} (${e.orgSlug})`):m(" Auth: Not logged in"),m(` API: ${t.apiBase}`),s.length>0?m(` Agents: ${s.map(p=>p.label).join(", ")}`):m(" Agents: None detected"),m(` Global: ${a.length} resource${a.length===1?"":"s"} installed`),l.length>0){m(""),m("Projects:");for(let p of l){let y=p.synced?"\u2713 synced":`\u26A0 ${p.serverCount-p.localCount} new`;m(` ${p.projectName}: ${p.localCount}/${p.serverCount} resources (${y})`)}}else o&&(m(""),m(` Project: ${o.projectName} (linked)`))})}re();K();function Xs(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=ae();e.revoke&&N()&&await Xt("/api/cli/auth"),Jt(),b()?I("logout",{email:t?.email||null}):m("Logged out.")})}var xt=require("fs"),Qs=require("path");K();function Zs(n){n.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,r)=>{let s=r.optsWithGlobals(),o=t.github;if(o&&e&&(b()?j("import","INVALID_ARGS","Cannot use --github with a local path"):x("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(b()?j("import","INVALID_ARGS","Provide a local path or --github <url>"):x("Error: Provide a local path or --github <url>"),process.exit(1)),N()||(b()?j("import","AUTH_MISSING","Authentication required for import"):x("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(b()?j("import","INVALID_ARGS","--on-conflict is not supported with --github"):x("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(b()?j("import","INVALID_ARGS","--dry-run is not supported with --github"):x("Error: --dry-run is not supported with --github"),process.exit(1));let S={url:o};t.resourceType&&(S.resourceType=t.resourceType),b()||m(`
208
- Importing from GitHub: ${o}`);let d=await T("/api/cli/github-import",S);d.ok||(b()?j("import",d.error.code,d.error.message):x(`
209
- Import failed: ${d.error.message}`),process.exit(1));let h=d.data;if(b()){I("import",h);return}m(""),m(` Source: ${h.source.owner}/${h.source.repo}`),m(` Type: ${h.resourceType}`),m(` Title: ${h.title}`),h.slug&&m(` Slug: ${h.slug}`),m(` URL: ${h.url}`),m(""),m("Import complete: 1 created");return}let a=(0,Qs.resolve)(e);(!(0,xt.existsSync)(a)||!(0,xt.statSync)(a).isDirectory())&&(b()?j("import","INVALID_PATH",`Not a directory: ${a}`):x(`Error: Not a directory: ${a}`),process.exit(1));let i=We(a);if(i.resources.length===0){b()?I("import",{resources:[],message:"No resources found"}):m("No resources found in the specified directory.");return}if(!b()){let S=new Map;for(let h of i.resources)S.set(h.resourceType,(S.get(h.resourceType)||0)+1);let d=[...S.entries()].map(([h,f])=>`${f} ${h}${f===1?"":"s"}`).join(", ");m(`
210
- Discovered ${i.resources.length} resources in ${e}:`),m(` ${d}`),i.formatLabel&&i.pluginName?m(` ${i.formatLabel}: ${i.pluginName}`):i.pluginName&&m(` Plugin: ${i.pluginName}`)}let c=t.tags?t.tags.split(",").map(S=>S.trim()).filter(Boolean):void 0,l={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:c,resources:i.resources,collectionMemberships:i.collectionMemberships.length>0?i.collectionMemberships:void 0};!b()&&!t.dryRun?m(`
211
- Executing import...`):b()||m(`
212
- Dry run \u2014 previewing changes...`);let u=await T("/api/cli/import",l,12e4);u.ok||(b()?j("import",u.error.code,u.error.message):x(`
213
- Import failed: ${u.error.message}`),process.exit(1));let p=u.data;if(b()){I("import",p);return}let y=[...p.created.map(S=>({...S,action:"created"})),...p.updated.map(S=>({...S,action:"updated"})),...p.installed.map(S=>({...S,action:"installed"})),...p.cloned.map(S=>({...S,action:"cloned"})),...p.skipped.map(S=>({...S,action:"skipped"})),...p.errors.map(S=>({...S,action:"error"}))];if(y.length>0){m("");let S=y.length,d=y.map((h,f)=>{let A=`[${String(f+1).padStart(String(S).length)}/${S}]`,O=(h.resourceType||"").padEnd(10),C=(h.importPath.split("/").pop()||"").padEnd(24),w="";switch(h.action){case"created":w=`\u2713 created${h.slug?` (slug: ${h.slug})`:""}`;break;case"updated":w="\u2713 updated";break;case"installed":{let _=h.versionsBehind;w=`\u2713 installed${_?` (${_} versions behind)`:""}`;break}case"cloned":w=`\u2713 cloned${h.slug?` (slug: ${h.slug})`:""}`;break;case"skipped":w=`\u2713 skipped (${h.reason||"up to date"})`;break;case"error":w=`\u2717 error: ${h.error||"unknown"}`;break}return` ${A} ${O} ${C} ${w}`});for(let h of d)m(h)}if(p.collections.length>0)for(let S of p.collections){let d=S.importPath.split("/").pop()||S.importPath;m(` collection ${d.padEnd(20)} \u2713 ${S.membersLinked} members linked${S.membersFailed>0?`, ${S.membersFailed} failed`:""}`)}m("");let g=[p.created.length>0?`${p.created.length} created`:null,p.installed.length>0?`${p.installed.length} installed`:null,p.cloned.length>0?`${p.cloned.length} cloned`:null,p.updated.length>0?`${p.updated.length} updated`:null,p.skipped.length>0?`${p.skipped.length} skipped`:null,p.errors.length>0?`${p.errors.length} errors`:null].filter(Boolean);t.dryRun?m(`Dry run complete: ${g.join(", ")}`):m(`Import complete: ${g.join(", ")}`),p.errors.length>0&&process.exit(1)})}var rn=require("path"),sn=require("os");K();re();function nn(n){n.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").action(async(e,t)=>{let r={...e,...t.optsWithGlobals()};if(!r.force&&!Kt()){let w=nt();if(w){let _={...w.lastResult,updates:[],untracked:[],summary:en(w.lastResult.updatesAvailable,w.lastResult.untrackedResources),throttled:!0};tn(_,!!r.quiet);return}}N()||(b()?j("sync","AUTH_MISSING","Login required to sync."):x("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=pe(r.agent);if(!s){let w=de();b()?j("sync","NO_AGENTS",w):x(w),process.exit(1)}let o=[],a=await U("/api/cli/updates");a.ok&&(o=a.data.updates);let i=(0,rn.join)((0,sn.homedir)(),s.dir),c=We(i,{settingsPath:Z(s,!!r.project),mcpConfigPath:B(s,!!r.project)}),l=Y(),u=new Set(l.installations.map(w=>w.installPath)),p=new Map;for(let w of l.installations){let _=w.installPath.split("/"),k=_[0],v=_[_.length-1];p.has(k)||p.set(k,new Set),p.get(k).add(v)}let y=new Set(["resource-manager",".claude-plugin"]),g=c.resources.filter(w=>{if(u.has(w.importPath))return!1;let _=w.importPath.split("/"),k=_[0],v=_[_.length-1];return!((k==="mcps"||k==="hooks")&&p.get(k)?.has(v)||w.importPath.startsWith(".")||y.has(v))}),S=g.length;if(r.import!==!1&&g.length>0){let w={dryRun:!1,onConflict:"auto",visibility:"org",resources:g,collectionMemberships:c.collectionMemberships},_=await T("/api/cli/import",w,12e4);if(_.ok){let k=[..._.data.created,..._.data.updated,..._.data.installed];if(!b()&&!r.quiet){if(k.length>0){m(`
214
- Imported ${k.length} resource${k.length===1?"":"s"}:`);let v=k.map(P=>[` ${(P.resourceType||"").padEnd(12)}`,(P.slug||P.importPath.split("/").pop()||"").padEnd(24),P.importPath]);m(ne(v))}_.data.errors.length>0&&x(`
215
- ${_.data.errors.length} import error(s)`)}g.length=0}else b()||x(`Import failed: ${_.error.message}`)}let d=me(),h=0;if(d){let w=await U(`/api/cli/projects/${d.projectId}/resources`);if(!w.ok)!b()&&!r.quiet&&(x(`Warning: Project "${d.projectName}" not found on server (may have been deleted).`),x(" Remove .shared-context/project.json to unlink this directory."));else if(w.ok){let _=w.data.resources,v=Y().installations.filter(R=>R.projectId===d.projectId),P=new Set(v.map(R=>R.resourceId)),H=_.filter(R=>!P.has(R.id));if(H.length>0){let R=be(s);for(let E of H){let $=E.installPath;try{let q=await U(`/api/cli/resource/${$}`);if(!q.ok)continue;await R.install(q.data,"project",s),te({resourceId:E.id,slug:E.slug||E.id,installPath:$,title:E.title,sha:E.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:d.projectId}),E.latestSha&&await T("/api/cli/install",{resourceId:E.id,agentPlatform:s.platform,installedSha:E.latestSha}).catch(()=>{}),h++}catch{}}!b()&&!r.quiet&&h>0&&m(`
216
- Project "${d.projectName}": installed ${h} new resource${h===1?"":"s"}`)}await T(`/api/cli/projects/${d.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let f=S-g.length,A={updatesAvailable:o.length,untrackedResources:g.length};Fe({lastSyncAt:new Date().toISOString(),lastResult:A});let O=ae();O?.connectionId&&T("/api/cli/sync-report",{connectionId:O.connectionId,lastSyncResult:{updatesAvailable:o.length,importedCount:f}}).catch(()=>{});let C={...A,updates:o,untracked:g.map(w=>({importPath:w.importPath,resourceType:w.resourceType,title:w.title})),summary:en(o.length,g.length),throttled:!1};tn(C,!!r.quiet)})}function en(n,e){let t=[];return n>0&&t.push(`${n} update${n===1?"":"s"} available`),e>0&&t.push(`${e} untracked resource${e===1?"":"s"}`),t.length===0?"Everything is up to date.":t.join(", ")}function tn(n,e){if(b()){I("sync",n);return}if(e){let t=n.summary;n.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),n.untrackedResources>0&&(t+=` \u2014 ${n.untrackedResources} untracked`),m(t);return}if(m(""),n.updates.length>0){m(`${n.updates.length} update${n.updates.length===1?"":"s"} available:
217
- `);let t=n.updates.map(r=>{let s=r.slug||r.resourceId,o=r.resourceType==="skill"?"skills":`${r.resourceType}s`;return[` ${r.storageType==="github"&&r.githubOwner?`${o}/external/${r.githubOwner}/${s}`:r.orgSlug?`${o}/${r.orgSlug}/${s}`:`${o}/${s}`}`,r.title,`${r.installedSha.slice(0,7)} \u2192 ${r.latestSha.slice(0,7)}`]});m(ne(t)),m("")}if(n.untracked.length>0){m(`${n.untracked.length} untracked resource${n.untracked.length===1?"":"s"}:
218
- `);let t=n.untracked.map(r=>[` ${r.resourceType.padEnd(12)}`,r.importPath.padEnd(30),r.title]);m(ne(t)),m("")}n.updatesAvailable===0&&n.untrackedResources===0?m("Everything is up to date."):(n.updatesAvailable>0&&m("Run 'shared-context-ai update' to update installed resources."),n.untrackedResources>0&&m("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),m("")}var on=require("path");K();K();function an(n){n.command("project").description("Manage projects").command("create").description("Create a project for the current folder").argument("[name]","Project name (defaults to folder name)").action(async t=>{if(!N()){let l="Not authenticated. Run 'shared-context-ai login' first.";b()?j("project create","AUTH_MISSING",l):x(l),process.exit(1)}let r=me();if(r){b()?I("project create",{alreadyExists:!0,project:{id:r.projectId,name:r.projectName,slug:r.projectSlug}}):m(`Project already linked: ${r.projectName}`);return}let s=t?.trim()||(0,on.basename)(process.cwd());if(!s||s==="/"){let l='Could not determine project name. Provide one: shared-context-ai project create "My Project"';b()?j("project create","INVALID_NAME",l):x(l),process.exit(1)}let o=await T("/api/cli/projects",{name:s});o.ok||(b()?j("project create",o.error.code,o.error.message):x(`Failed to create project: ${o.error.message}`),process.exit(1));let{id:a,name:i,slug:c}=o.data;Je({projectId:a,projectName:i,projectSlug:c}),b()?I("project create",{id:a,name:i,slug:c}):(m(`Created project: ${i}`),m(""),m("Quick reference:"),m(" shared-context-ai install <installPath> Add a resource to this project"),m(" shared-context-ai sync Check for resource updates"),m(" shared-context-ai status View project sync status"))})}var cn={AUTH_MISSING:"Run 'shared-context-ai login' to authenticate.",AUTH_EXPIRED:"Run 'shared-context-ai login' to re-authenticate.",SKILL_NOT_FOUND:"Check the skill slug and try again.",ALREADY_INSTALLED:"Use 'shared-context-ai update <slug>' to update instead.",NO_AGENTS:"No AI coding agents detected. Run 'shared-context-ai init --agent <name>' to set up manually.",API_ERROR:"The server returned an error. Try again later.",WRITE_FAILED:"Could not write files to disk. Check permissions."},Ot=class extends Error{constructor(t,r){super(r||cn[t]);this.code=t;this.name="CliError"}get recovery(){return cn[this.code]}};var X=new Nr;X.name("shared-context-ai").description("CLI for Shared Context - search, install, and manage AI skills").version("0.1.0").option("--json","Output as JSON (default when piped)").option("--human","Output as human-readable text (default in TTY)").option("--agent <name>","Override agent detection").option("--project","Use project-local directory instead of global").hook("preAction",n=>{let e=n.opts();Hr(!!e.json,!!e.human)});as(X);Hs(X);Us(X);Qr(X);Bs(X);qs(X);Gs(X);Ys(X);Ks(X);zs(X);Xs(X);Zs(X);nn(X);an(X);process.on("uncaughtException",n=>{n instanceof Ot?b()?j(process.argv[2]||"unknown",n.code,n.message):(x(`Error: ${n.message}`),x(n.recovery)):b()?j(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):x(`Error: ${n.message||n}`),process.exit(1)});X.parse();
111
+ ## Building Resources
112
+
113
+ When building custom resources, follow these patterns:
114
+
115
+ **Skills** \u2014 Specific repeatable processes with defined inputs/outputs. Files: \`skills/{slug}/SKILL.md\`
116
+ **Agents** \u2014 Ongoing responsibilities that own a domain. Files: \`agents/{slug}/{slug}.md\`
117
+ **Hooks** \u2014 Automatic event responses (SessionStart, PreToolUse, etc.). Files: \`hooks/{slug}/hook.json\`
118
+
119
+ ### Build Process
120
+
121
+ 1. **Interview** \u2014 Ask targeted questions to understand the goal, expertise, and constraints
122
+ 2. **Build** \u2014 Create resource files with supporting sub-files and filesystem architecture
123
+ 3. **Test** \u2014 Run a real scenario, observe output, refine based on feedback
124
+ 4. **Wire** \u2014 Check existing resources for integration opportunities
125
+
126
+ ### Key Principles
127
+
128
+ - **Distillation, not generation** \u2014 Every instruction should capture something an LLM couldn't know without being told
129
+ - **Specificity over comprehensiveness** \u2014 Only include instructions that meaningfully change Claude's output
130
+ - **Filesystem as memory** \u2014 Design persistent storage so resources accumulate knowledge over time
131
+ - **Search before building** \u2014 Check the Shared Context library before creating from scratch
132
+ `;var U=require("fs"),Q=require("path"),Cs=require("crypto");var Nt=".context-collection",jt="manifest.json";function hs(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function Fi(r,e){return{version:1,name:r.name||"Untitled Extension",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function $i(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}var vr=[{path:`${Nt}/${jt}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:hs,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:hs,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:Fi,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:$i,formatLabel:"Cursor Plugin"}];var gs=[{folder:"skills",mainFile:"SKILL.md",resourceType:"skill",canHaveChildren:!0},{folder:"commands",mainFile:null,resourceType:"skill",canHaveChildren:!0},{folder:"hooks",mainFile:"hook.json",resourceType:"hook",canHaveChildren:!1},{folder:"agents",mainFile:null,resourceType:"agent",canHaveChildren:!0},{folder:"mcps",mainFile:"mcp.json",resourceType:"mcp",canHaveChildren:!0},{folder:"collections",mainFile:"README.md",resourceType:"collection",canHaveChildren:!1}],ys=`${Nt}/${jt}`;function ut(r){let e={name:"",description:"",body:r};if(!r.startsWith(`---
133
+ `)&&!r.startsWith(`---\r
134
+ `))return e;let t=r.indexOf(`
135
+ ---`,3);if(t===-1)return e;let n=r.slice(4,t),s=r.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let o={},a={},c=new Set(["requires","tools"]),u={},l=n.split(`
136
+ `),h=null,S=!1;for(let _=0;_<l.length;_++){let d=l[_];if(h&&/^\s+-\s/.test(d)){let g=d.replace(/^\s+-\s/,"").trim();if(g){let C=tt(g);S?u[h].push(C):a[h].push(C)}continue}h=null,S=!1;let m=d.indexOf(":");if(m===-1)continue;let p=d.slice(0,m).trim(),f=d.slice(m+1).trim();if(!f&&p&&_+1<l.length&&/^\s+-\s/.test(l[_+1])){h=p,c.has(p)?(S=!0,u[p]=[]):(S=!1,a[p]=[]);continue}p==="name"||p==="title"?e.name=tt(f):p==="description"?e.description=tt(f):p==="skill_class"?e.skillClass=tt(f):p==="service"?e.service=tt(f):p&&f&&(o[p]=tt(f))}return u.requires?.length&&(e.requires=u.requires),u.tools?.length&&(e.tools=u.tools),Object.keys(o).length&&(e.fields=o),Object.keys(a).length&&(e.arrayFields=a),e}function tt(r){let e=r.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")){let t=e.slice(1,-1);return e.startsWith('"')?t.replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.replace(/''/g,"'")}return e}function Mi(r){let{body:e}=ut(r);return e.replace(/\r\n/g,`
137
+ `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Ge(r){let e=Mi(r);return`sha256:${(0,Cs.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Oe(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Lt(r){try{return(0,U.statSync)(r).isDirectory()}catch{return!1}}function Es(r){try{return(0,U.readdirSync)(r).filter(e=>!e.startsWith(".")&&Lt((0,Q.join)(r,e)))}catch{return[]}}function Ss(r){try{return(0,U.readdirSync)(r).filter(e=>!e.startsWith(".")&&!Lt((0,Q.join)(r,e)))}catch{return[]}}function rt(r,e){let t=[],n=[],s,o;function a(d,m){let p=[],f=[];for(let g of gs){let C=(0,Q.join)(d,g.folder);if(!(0,U.existsSync)(C)||!Lt(C))continue;let i=m?`${m}/${g.folder}`:g.folder;if(g.folder==="files"){for(let y of Ss(C)){if(!y.endsWith(".md"))continue;let E=(0,Q.join)(C,y),b=(0,U.readFileSync)(E,"utf-8"),A=ut(b),I=A.name||(0,Q.basename)(y,".md"),O=`${i}/${(0,Q.basename)(y,".md")}`;p.push({importPath:O,resourceType:"file",title:I,description:A.description||null,body:A.body,bodyHash:Ge(b),metadata:{}})}continue}for(let y of Es(C)){let E=g.mainFile||`${y}.md`,b=(0,Q.join)(C,y,E);if(!(0,U.existsSync)(b))continue;let A=(0,U.readFileSync)(b,"utf-8"),I=`${i}/${y}`,O,T,k,N={},D=null;if(g.resourceType==="hook"||g.resourceType==="mcp"){try{let F=JSON.parse(A);O=F.name||Oe(y),T=F.description||null}catch{O=Oe(y),T=null}k=A}else if(g.resourceType==="collection"){let F=(0,Q.join)(C,y,Nt,jt);if((0,U.existsSync)(F))try{let B=JSON.parse((0,U.readFileSync)(F,"utf-8"));O=B.name||Oe(y),T=B.description||null,k=A,B.resources&&Array.isArray(B.resources)&&f.push({collectionImportPath:I,memberImportPaths:B.resources.map(pe=>{let He=pe.split("/");return He.length>=3?`${He[0]}/${He[He.length-1]}`:pe})})}catch{O=Oe(y),T=null,k=A}else D=ut(A),O=D.name||Oe(y),T=D.description||null,k=D.body,D.arrayFields?.resources&&f.push({collectionImportPath:I,memberImportPaths:D.arrayFields.resources.map(B=>{let pe=B.split("/");return pe.length>=3?`${pe[0]}/${pe[pe.length-1]}`:B})})}else D=ut(A),O=D.name||Oe(y),T=D.description||null,k=D.body,D.skillClass&&(N.skillClass=D.skillClass),D.service&&(N.service=D.service),D.requires?.length&&(N.requires=D.requires),D.tools?.length&&(N.tools=D.tools),D.fields&&Object.keys(D.fields).length&&(N.fields=D.fields);g.folder==="commands"&&(N.fields||(N.fields={}),N.fields["user-invocable"]="true"),p.push({importPath:I,resourceType:g.resourceType,title:O,description:T,body:k,bodyHash:Ge(A),metadata:N})}}return{resources:p,memberships:f}}let c=a(r,"");t.push(...c.resources),n.push(...c.memberships);let u=new Set;e?.mcpConfigPath&&u.add(e.mcpConfigPath);let l=(0,Q.join)(r,".mcp.json");(0,U.existsSync)(l)&&u.add(l);for(let d of u)if((0,U.existsSync)(d))try{let m=JSON.parse((0,U.readFileSync)(d,"utf-8"));if(m.mcpServers&&typeof m.mcpServers=="object")for(let[p,f]of Object.entries(m.mcpServers)){let g=`mcps/${p}`;if(t.some(y=>y.importPath===g))continue;let C=Oe(p),i=JSON.stringify({name:C,description:`MCP server: ${p}`,mcpServers:{[p]:f}},null,2);t.push({importPath:g,resourceType:"mcp",title:C,description:`MCP server: ${p}`,body:i,bodyHash:Ge(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,U.existsSync)(e.settingsPath))try{let d=JSON.parse((0,U.readFileSync)(e.settingsPath,"utf-8"));if(d.hooks&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)){let m={};for(let[p,f]of Object.entries(d.hooks))if(Array.isArray(f))for(let g of f){if(!g||typeof g!="object")continue;let C=g,i=C._sc;if(!i)continue;m[i]||(m[i]={}),m[i][p]||(m[i][p]=[]);let{_sc:y,...E}=C;m[i][p].push(E)}for(let[p,f]of Object.entries(m)){let g=p;if(t.some(E=>E.importPath===g))continue;let C=p.split("/").pop()||p,i=Oe(C),y=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:f},null,2);t.push({importPath:g,resourceType:"hook",title:i,description:`Hook: ${i}`,body:y,bodyHash:Ge(y),metadata:{}})}}}catch{}for(let d of vr){if(d.path===ys)continue;let m=(0,Q.join)(r,d.path);if((0,U.existsSync)(m)){try{let p=JSON.parse((0,U.readFileSync)(m,"utf-8"));if(s=s||p.name||void 0,o=d.formatLabel,!t.some(f=>f.resourceType==="collection")){let f=t.filter(E=>E.resourceType!=="collection").map(E=>({resourceRef:E.importPath})),g=d.converter(p,f),C=(0,Q.join)(r,"README.md"),i=(0,U.existsSync)(C)?(0,U.readFileSync)(C,"utf-8"):"",y="collections/_root";t.push({importPath:y,resourceType:"collection",title:Oe(g.name),description:g.description||null,body:i,bodyHash:Ge(i),metadata:{},manifestMetadata:{...g.author?{author:g.author}:{},...g.homepage?{homepage:g.homepage}:{},...g.license?{license:g.license}:{}}}),g.resources.length>0&&n.push({collectionImportPath:y,memberImportPaths:g.resources})}}catch{}break}}{let p=function(f,g,C){if(!(C>4))for(let i of Es(f)){if(m.has(i))continue;let y=(0,Q.join)(f,i),E=g?`${g}/${i}`:i;for(let b of vr){if(b.path===ys)continue;let A=(0,Q.join)(y,b.path);if((0,U.existsSync)(A)){if(d.has(E))break;d.add(E);try{let I=JSON.parse((0,U.readFileSync)(A,"utf-8")),O=a(y,E);if(O.resources.length===0)break;t.push(...O.resources),n.push(...O.memberships);let T=O.resources.filter(B=>B.resourceType!=="collection").map(B=>({resourceRef:B.importPath})),k=b.converter(I,T),N=(0,Q.join)(y,"README.md"),D=(0,U.existsSync)(N)?(0,U.readFileSync)(N,"utf-8"):"",F=`${E}/_collection`;t.push({importPath:F,resourceType:"collection",title:Oe(k.name),description:k.description||null,body:D,bodyHash:Ge(D),metadata:{},manifestMetadata:{...k.author?{author:k.author}:{},...k.homepage?{homepage:k.homepage}:{},...k.license?{license:k.license}:{}}}),n.push({collectionImportPath:F,memberImportPaths:O.resources.map(B=>B.importPath)}),s||(s=I.name||void 0),o||(o=b.formatLabel)}catch{}break}}p(y,E,C+1)}};var _=p;let d=new Set,m=new Set(gs.map(f=>f.folder));p(r,"",0)}let h=(0,Q.join)(r,"files");if((0,U.existsSync)(h)&&Lt(h)&&!t.some(d=>d.resourceType==="file"))for(let d of Ss(h)){if(!d.endsWith(".md"))continue;let m=(0,Q.join)(h,d),p=(0,U.readFileSync)(m,"utf-8"),f=ut(p),g=f.name||(0,Q.basename)(d,".md"),C=`files/${(0,Q.basename)(d,".md")}`;t.some(i=>i.importPath===C)||t.push({importPath:C,resourceType:"file",title:g,description:f.description||null,body:f.body,bodyHash:Ge(p),metadata:{}})}return{resources:[...t.filter(d=>d.resourceType!=="collection"),...t.filter(d=>d.resourceType==="collection")],collectionMemberships:n,pluginName:s,formatLabel:o}}function Hi(){if(process.platform==="darwin")try{let{execSync:r}=require("child_process"),e=r("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var Le="context-manager",ws="Context Manager",Ft="collections/shared-context/context-manager";function Ui(r,e){let t=te(r,e),n=(0,qe.join)(t,Le);return(0,$t.mkdirSync)(n,{recursive:!0}),(0,$t.writeFileSync)((0,qe.join)(n,`${Le}.md`),ms,"utf-8"),(0,qe.join)(n,`${Le}.md`)}var Bi={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Wi(r){return Y().installations.some(t=>t.installPath===Ft&&t.agent===r)}function _s(r){r.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(n.code){let{post:p}=await Promise.resolve().then(()=>(se(),_n)),{saveAuth:f}=await Promise.resolve().then(()=>(me(),gr)),g=await p("/api/cli/auth",{code:n.code});g.ok?(f({token:g.data.token,email:g.data.user.email,orgId:g.data.org.id,orgSlug:g.data.org.slug,orgName:g.data.org.name,createdAt:new Date().toISOString()}),x()||w(`Authenticated as ${g.data.user.email}`)):M()?x()||w("Auth code already used, continuing with saved credentials."):(x()?P("init",g.error.code,g.error.message):R(`Auth failed: ${g.error.message}`),process.exit(1))}else M()||(x()?(P("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(R("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let p=be(n.agent);if(!p){let f=`Unknown agent: ${n.agent}. Available: ${De().map(g=>g.id).join(", ")||"none detected"}`;x()?P("init","NO_AGENTS",f):R(f),process.exit(1)}s=[p]}else if(s=De(),s.length===0){let p=Pe();x()?P("init","NO_AGENTS",p):R(p),process.exit(1)}let o=Se(),a=Hi(),c;if(n.linkProject){if(!o?.token){let A="Authentication required for project linking. Run init with --code first.";x()?P("init","AUTH_REQUIRED",A):R(A),process.exit(1)}let p=s[0],f=await L("/api/cli/register-agent",{platform:p.platform,name:`CLI (${a})`});f.ok&&(c=f.data.connectionId);let g=await L(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});g.ok||(x()?P("init",g.error.code,g.error.message):R(`Failed to join project: ${g.error.message}`),process.exit(1));let{project:C,resources:i,members:y}=g.data;lt({projectId:C.id,projectName:C.name,projectSlug:C.slug});let E=Ie(p),b=[];for(let A of i)try{let I=A.installPath,O=await G(`/api/cli/resource/${I}`);if(!O.ok)continue;let T=O.data;await E.install(T,"project",p),ue({resourceId:A.id,slug:A.slug||A.id,installPath:I,title:A.title,sha:A.latestSha||"",scope:"project",agent:p.id,installedAt:new Date().toISOString(),projectId:C.id}),A.latestSha&&await L("/api/cli/install",{resourceId:A.id,agentPlatform:p.platform,installedSha:A.latestSha}).catch(()=>{}),b.push({title:A.title,resourceType:A.resourceType})}catch{}if(await L(`/api/cli/projects/${C.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Ze({lastSyncAt:new Date().toISOString(),lastResult:{updatesAvailable:0,untrackedResources:0}}),x())j("init",{project:{id:C.id,name:C.name,slug:C.slug},agent:p.id,resourcesInstalled:b.length,memberCount:y.length});else{if(w(""),w(`Joined project: ${C.name}`),C.description&&w(`"${C.description}"`),w(""),b.length>0){w(`Installed ${b.length} resource${b.length===1?"":"s"}:`);let A={};for(let O of b)A[O.resourceType]||(A[O.resourceType]=[]),A[O.resourceType].push(O.title);let I={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[O,T]of Object.entries(A))w(` ${I[O]||O}: ${T.join(", ")}`)}else w("No resources to install (project is empty)");y.length>0&&(w(""),w(`Team (${y.length}): ${y.map(A=>A.name).join(", ")}`)),w(""),w("Quick reference:"),w(" shared-context-ai status View project sync status"),w(" shared-context-ai sync Check for resource updates")}return}let u=!1,l=(0,qe.basename)(process.cwd());if(o?.token&&!xe()&&l&&l!=="/")try{let p=await L("/api/cli/projects",{name:l});if(p.ok){let{id:f,name:g,slug:C}=p.data;lt({projectId:f,projectName:g,projectSlug:C}),u=!0,x()||w(`Created project: ${g}`)}}catch{}let h=[],S={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let p of s){let f=!1,g=!1,C=[],i=[];if(o?.token){let y=await L("/api/cli/register-agent",{platform:p.platform,name:`CLI (${a})`});if(y.ok){if(!c){c=y.data.connectionId;let{saveAuth:E}=await Promise.resolve().then(()=>(me(),gr));E({...o,connectionId:c})}}else x()||R(`Warning: Could not register ${p.label} connection: ${y.error.message}`)}if(o?.token&&Wi(p.id))g=!0,f=!0;else if(o?.token)try{let y=await G(`/api/cli/resource/${Ft}`);if(y.ok){let E=y.data,A=await Ie(p).install(E,n.project?"project":"user",p);if(ue({resourceId:E.resource.id,slug:E.resource.slug||"context-manager",installPath:Ft,title:E.resource.title,sha:E.resource.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString(),pluginFormat:S[p.id]||"directory",memberCount:E.memberResources?.length}),E.resource.latestSha&&await L("/api/cli/install",{resourceId:E.resource.id,agentPlatform:p.platform,installedSha:E.resource.latestSha}).catch(()=>{}),E.memberResources)for(let I of E.memberResources){let O=I.slug||I.id,T=Bi[I.resourceType]||I.resourceType+"s",k=I.orgSlug||E.resource.orgSlug,N=k?`${T}/${k}/${O}`:`${T}/${O}`;ue({resourceId:I.id,slug:O,installPath:N,title:I.title,sha:I.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString(),collectionId:E.resource.id}),C.push({title:I.title,resourceType:I.resourceType}),I.latestSha&&await L("/api/cli/install",{resourceId:I.id,agentPlatform:p.platform,installedSha:I.latestSha}).catch(()=>{})}if(f=!0,!x()&&A.warnings.length>0)for(let I of A.warnings)R(`Warning: ${I}`)}}catch{}if(!f&&(Ui(p,!!n.project),ue({resourceId:"context-manager",slug:Le,installPath:`agents/${Le}`,title:ws,sha:"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString()}),o?.token))try{let y=`agents/shared-context/${Le}`,E=await G(`/api/cli/resource/${y}`);if(E.ok&&E.data.resource){let b=E.data.resource;b.latestSha&&await L("/api/cli/install",{resourceId:b.id,agentPlatform:p.platform,installedSha:b.latestSha}),ue({resourceId:b.id,slug:b.slug||Le,installPath:`agents/shared-context/${b.slug||Le}`,title:b.title||ws,sha:b.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let y=(0,qe.join)((0,As.homedir)(),p.dir),E=rt(y,{settingsPath:fe(p,!!n.project),mcpConfigPath:re(p,!!n.project)}),b=Y(),A=new Set(b.installations.map(k=>k.installPath)),I=new Map;for(let k of b.installations){let N=k.installPath.split("/"),D=N[0],F=N[N.length-1];I.has(D)||I.set(D,new Set),I.get(D).add(F)}let O=new Set(["context-manager",".claude-plugin"]),T=E.resources.filter(k=>{if(A.has(k.importPath))return!1;let N=k.importPath.split("/"),D=N[0],F=N[N.length-1];return!((D==="mcps"||D==="hooks")&&I.get(D)?.has(F)||k.importPath.startsWith(".")||O.has(F))});if(T.length>0){let k={dryRun:!1,onConflict:"auto",visibility:"org",resources:T,collectionMemberships:E.collectionMemberships},N=await L("/api/cli/import",k,12e4);N.ok&&(i=[...N.data.created,...N.data.updated,...N.data.installed].map(F=>({resourceType:F.resourceType||F.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:F.slug||F.importPath.split("/").pop()||"",title:F.importPath.split("/").pop()||""})))}}catch{}h.push({agent:p,collectionInstalled:f,installedMembers:C,importedResources:i,skippedEssentials:g})}if(Ze({lastSyncAt:new Date().toISOString(),lastResult:{updatesAvailable:0,untrackedResources:0}}),c){let p=h.reduce((f,g)=>f+g.importedResources.length,0);L("/api/cli/sync-report",{connectionId:c,lastSyncResult:{updatesAvailable:0,importedCount:p}}).catch(()=>{})}let _=h.every(p=>p.skippedEssentials),d=h.some(p=>!p.skippedEssentials),m=h.some(p=>p.importedResources.length>0);if(x()){let p=f=>({agent:f.agent.id,collection:f.collectionInstalled?Ft:void 0,contextManagerOnly:!f.collectionInstalled,skipped:f.skippedEssentials,...f.collectionInstalled&&!f.skippedEssentials?{membersInstalled:f.installedMembers.map(g=>({title:g.title,resourceType:g.resourceType}))}:{},...f.importedResources.length>0?{importedResources:f.importedResources.map(g=>({resourceType:g.resourceType,slug:g.slug,title:g.title}))}:{}});j("init",{...p(h[0]),agents:h.map(p),...u?{projectCreated:!0}:{},authenticated:M()})}else{for(let p of h)if(!p.skippedEssentials){if(w(""),p.collectionInstalled){w(`Context Manager installed for ${p.agent.label} (${p.installedMembers.length} resources)`);let f={};for(let C of p.installedMembers)f[C.resourceType]||(f[C.resourceType]=[]),f[C.resourceType].push(C.title);let g={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};w("");for(let[C,i]of Object.entries(f)){let y=g[C]||C;w(` ${y}: ${i.join(", ")}`)}}else w(`Context Manager installed for ${p.agent.label} (offline)`),w("Context Manager agent written locally");if(p.importedResources.length>0){w(""),w(`Imported ${p.importedResources.length} existing resource${p.importedResources.length===1?"":"s"}:`);for(let f of p.importedResources)w(` ${f.resourceType.padEnd(12)} ${f.slug.padEnd(24)} ${f.title}`)}}_&&!u&&!m&&(w(""),w("Already initialized. Nothing to do.")),(d||u||m)&&(w(""),w("Quick reference:"),w(' shared-context-ai search "query" Search for resources'),w(" shared-context-ai install <installPath> Install a resource"),w(" shared-context-ai list List installed resources"),w(" shared-context-ai sync Check updates & discover resources"),w(" shared-context-ai preview <installPath> Preview before installing"))}})}var Qs=require("http"),eo=require("crypto");me();se();me();async function to(r){let e=await L("/api/cli/auth",{code:r});return e.ok?(dr({token:e.data.token,email:e.data.user.email,orgId:e.data.org.id,orgSlug:e.data.org.slug,orgName:e.data.org.name,createdAt:new Date().toISOString()}),x()?j("login",{email:e.data.user.email,org:e.data.org.slug}):w(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(x()?P("login",e.error.code,e.error.message):R(`Login failed: ${e.error.message}`),!1)}async function ia(){let r=(0,eo.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,Qs.createServer)((n,s)=>{let o=new URL(n.url||"/","http://localhost"),a=o.searchParams.get("code"),c=o.searchParams.get("state");if(!a||c!==r){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),to(a).then(e)});t.listen(0,"127.0.0.1",async()=>{let n=t.address();if(!n||typeof n=="string"){t.close(),e(!1);return}let s=n.port,a=`${Re().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${r}`;x()||(w("Opening browser for authentication..."),w(`If the browser doesn't open, visit: ${a}`));try{let c=(await Promise.resolve().then(()=>(Ys(),Ks))).default;await c(a)}catch{x()||w(`Could not open browser. Please visit:
138
+ ${a}`)}setTimeout(()=>{t.close(),x()||R("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function ro(r){r.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await to(e.code):t=await ia(),process.exit(t?0:1)})}se();var aa={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function no(r){let e=aa[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${e}/external/${r.githubOwner}/${r.slug}`:r.orgSlug?`${e}/${r.orgSlug}/${r.slug}`:`${e}/${r.slug}`}function so(r){r.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let n=new URLSearchParams({q:e});t.type&&n.set("type",t.type),t.tag&&n.set("tag",t.tag),t.limit&&n.set("limit",t.limit);let s=M()?`/api/cli/search?${n}`:`/api/public/search?${n}`,o=await G(s);o.ok||(x()?P("search",o.error.code,o.error.message):w(`Search failed: ${o.error.message}`),process.exit(1));let a=o.data.results;if(x()){let u=a.map(l=>{let h=no(l);return{installPath:h,installCommand:`npx shared-context-ai install ${h}`,title:l.title,description:l.description,resourceType:l.resourceType,installCount:l.installCount,topicTags:l.topicTags}});j("search",{results:u,count:u.length});return}if(a.length===0){let u=t.type?`${t.type}s`:"results";w(`No ${u} found.`);return}w(`Found ${a.length} result${a.length===1?"":"s"}:
139
+ `);let c=a.map(u=>[no(u),u.title,`\u2193${u.installCount}`]);w(ge(c)),w(`
140
+ Install a skill: npx shared-context-ai install <installPath>`)})}se();me();function oo(r){let e=r.slug||r.resourceId;return r.storageType==="github"&&r.githubOwner?`skills/external/${r.githubOwner}/${e}`:r.orgSlug?`skills/${r.orgSlug}/${e}`:`skills/${e}`}function io(r){r.command("list").description("List installed skills").alias("ls").action(async()=>{if(M()){let e=await G("/api/cli/installed");e.ok||(x()?P("list",e.error.code,e.error.message):w(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(x()){let s=t.map(o=>({...o,installPath:oo(o)}));j("list",{installations:s,count:s.length});return}if(t.length===0){w("No skills installed."),w("Use 'shared-context-ai search' to find skills to install.");return}w(`${t.length} skill${t.length===1?"":"s"} installed:
141
+ `);let n=t.map(s=>[oo(s),s.title,s.hasUpdate?"(update available)":"(current)"]);w(ge(n))}else{let t=Y().installations;if(x()){j("list",{installations:t,count:t.length});return}if(t.length===0){w("No skills installed locally.");return}w(`${t.length} skill${t.length===1?"":"s"} installed locally:
142
+ `);let n=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);w(ge(n)),w(`
143
+ Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}se();function ao(r){r.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let n=M()?"/api/cli/resource":"/api/public/resource",s=await G(`${n}/${e}/preview`);s.ok||(x()?P("preview",s.error.code,s.error.message):R(`Preview failed: ${s.error.message}`),process.exit(1)),x()?j("preview",s.data):w(s.data.content)})}se();function co(r){r.command("check").description("Check for skill updates").action(async()=>{M()||(x()?P("check","AUTH_MISSING","Login required to check for updates."):R("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await G("/api/cli/updates");e.ok||(x()?P("check",e.error.code,e.error.message):R(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:n}=e.data;if(x()){j("check",{updates:t,count:n});return}if(n===0){w("All skills are up to date.");return}w(`${n} update${n===1?"":"s"} available:
144
+ `);let s=t.map(o=>{let a=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${a}`:o.orgSlug?`skills/${o.orgSlug}/${a}`:`skills/${a}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});w(ge(s)),w(`
145
+ Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var Xr=require("path"),uo=require("child_process");se();me();var ca={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function lo(r){let e=r.slug||r.resourceId;return`${ca[r.resourceType]||r.resourceType+"s"}/${e}`}function fo(r){r.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,n)=>{let s=n.optsWithGlobals();M()||(x()?P("update","AUTH_MISSING","Login required to update resources."):R("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=be(s.agent);if(!o){let l=Pe();x()?P("update","NO_AGENTS",l):R(l),process.exit(1)}let a=await G("/api/cli/updates");a.ok||(x()?P("update",a.error.code,a.error.message):R(`Failed to check updates: ${a.error.message}`),process.exit(1));let c=a.data.updates;if(e&&(c=c.filter(l=>lo(l)===e||l.slug===e||l.resourceId===e),c.length===0)){x()?P("update","SKILL_NOT_FOUND",`No update available for "${e}".`):w(`No update available for "${e}".`);return}if(c.length===0){x()?j("update",{updated:[],count:0}):w("All resources are up to date.");return}let u=[];for(let l of c){let h=lo(l),_=Y().installations.find(f=>f.resourceId===l.resourceId&&f.agent===o.id);if(_?.installMode==="plugin"&&l.resourceType==="collection"){try{let f=l.orgSlug||"",g=l.slug||l.resourceId,C=xt(o.id),i=`/api/cli/resource/collections/${f}/${g}?format=plugin&platform=${C}`,y=await bt(i,g),E=Qe(o.id);E&&(0,uo.execSync)(`${E} plugin install "${y}"`,{stdio:"pipe"}),l.latestSha&&await L("/api/cli/update",{resourceId:l.resourceId,installedSha:l.latestSha}),ue({..._,sha:l.latestSha,installedAt:new Date().toISOString()}),u.push({installPath:h,title:l.title}),x()||w(` Updated plugin: ${h}`)}catch(f){x()||R(` Plugin update failed for ${h}: ${f}`)}continue}let d=await G(`/api/cli/resource/${h}`);if(!d.ok){x()||R(` Failed to fetch ${h}: ${d.error.message}`);continue}let m=d.data,p=h.split("/").slice(1);if(m.resource.resourceType==="agent"){let f=te(o,!!s.project),g=(0,Xr.join)(f,...p);V(g,m.files)}else if(m.resource.resourceType==="mcp")Ir(o,!!s.project,m);else{let f=W(o,!!s.project),g=(0,Xr.join)(f,...p);V(g,m.files)}m.resource.latestSha&&await L("/api/cli/update",{resourceId:m.resource.id,installedSha:m.resource.latestSha}),ue({resourceId:m.resource.id,slug:m.resource.slug||m.resource.id,installPath:h,title:m.resource.title,sha:m.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString()}),u.push({installPath:h,title:m.resource.title}),x()||w(` Updated ${h}`)}x()?j("update",{updated:u,count:u.length}):u.length>0&&w(`
146
+ ${u.length} resource${u.length===1?"":"s"} updated.`)})}var ee=require("fs"),st=require("path"),po=require("child_process");se();me();function mo(r){r.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{if(!e){let m=Y().installations;if(m.length===0&&(x()?P("uninstall","NOTHING_INSTALLED","No resources installed."):w("No resources installed."),process.exit(0)),x())j("uninstall",{installations:m.map(p=>({path:p.installPath||p.slug,title:p.title,agent:p.agent}))});else{w(`Installed resources:
147
+ `);let p=m.map(f=>[f.installPath||f.slug,f.title||"",`(${f.agent})`]);w(ge(p)),w(`
148
+ Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=be(s.agent);if(!o){let d=Pe();x()?P("uninstall","NO_AGENTS",d):R(d),process.exit(1)}let c=Y().installations.find(d=>d.installPath===e||d.slug===e||d.resourceId===e),u=e.split("/"),h=["skills","files","commands","hooks","collections","agents","mcps"].includes(u[0])?u[0]:null,S=h?u.slice(1):u,_=!1;if(h==="collections")if(c?.installMode==="plugin"){let d=Qe(o.id);if(d)try{(0,po.execSync)(`${d} plugin uninstall "${c.slug}"`,{stdio:"pipe"}),x()||w(`Uninstalled native ${d} plugin: ${c.slug}`)}catch(m){x()||R(`Native uninstall failed: ${m}. Removing tracking only.`)}at(c.resourceId,o.id),M()&&await L("/api/cli/uninstall",{resourceId:c.resourceId,agentPlatform:o.platform}).catch(()=>{}),x()?j("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`);return}else{let d=Ie(o),m=S[S.length-1],p=s.project?"project":"user",f=await d.uninstall(m,p,o,c?.resourceId);if(_=f.removed,!x())for(let g of f.warnings)R(`Warning: ${g}`);if(c){let C=Y().installations.filter(i=>i.collectionId===c.resourceId&&i.agent===o.id);for(let i of C){let y=i.installPath.split("/"),E=y[0],b=y.slice(1);if(E==="agents"){let A=te(o,!!s.project),I=(0,st.join)(A,...b);(0,ee.existsSync)(I)&&(0,ee.rmSync)(I,{recursive:!0,force:!0})}else if(E==="mcps"){let A=b[b.length-1],I=re(o,!!s.project);if((0,ee.existsSync)(I))try{let O=JSON.parse((0,ee.readFileSync)(I,"utf-8"));if(typeof O.mcpServers=="object"&&O.mcpServers&&!Array.isArray(O.mcpServers)){let T=O.mcpServers;A in T&&(delete T[A],O.mcpServers=T,(0,ee.writeFileSync)(I,JSON.stringify(O,null,2)+`
149
+ `,"utf-8"))}}catch{}}else if(E==="hooks")kr(fe(o,!!s.project),i.installPath);else{let A=W(o,!!s.project),I=(0,st.join)(A,...b);(0,ee.existsSync)(I)&&(0,ee.rmSync)(I,{recursive:!0,force:!0})}at(i.resourceId,o.id)}}}else if(h==="agents"){let d=te(o,!!s.project),m=(0,st.join)(d,...S);_=(0,ee.existsSync)(m),_&&(0,ee.rmSync)(m,{recursive:!0,force:!0})}else if(h==="mcps"){let d=S[S.length-1],m=re(o,!!s.project);if((0,ee.existsSync)(m))try{let p=JSON.parse((0,ee.readFileSync)(m,"utf-8"));if(typeof p.mcpServers=="object"&&p.mcpServers&&!Array.isArray(p.mcpServers)){let f=p.mcpServers;d in f&&(delete f[d],p.mcpServers=f,(0,ee.writeFileSync)(m,JSON.stringify(p,null,2)+`
150
+ `,"utf-8"),_=!0)}}catch{}}else if(h==="hooks"){let d=fe(o,!!s.project);_=kr(d,e),!_&&!x()&&R(`Note: No tagged hook entries found in ${d} \u2014 may need manual removal if installed before v0.1.10`)}else{let d=W(o,!!s.project),m=(0,st.join)(d,...S);if(_=(0,ee.existsSync)(m),_&&(0,ee.rmSync)(m,{recursive:!0,force:!0}),!_&&c?.slug){let p=(0,st.join)(d,c.slug);(0,ee.existsSync)(p)&&(0,ee.rmSync)(p,{recursive:!0,force:!0})}}if(M()&&c){let d=await L("/api/cli/uninstall",{resourceId:c.resourceId});!d.ok&&!x()&&R(`Warning: Could not record uninstall on server: ${d.error.message}`)}c&&at(c.resourceId,o.id),x()?j("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`)})}me();se();function ho(r){r.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=Se(),t=Re(),n=Y(),s=De(),o=xe(),a=n.installations.filter(S=>!S.projectId),c=n.installations.filter(S=>S.projectId),u=new Map;for(let S of c){let _=S.projectId;u.has(_)||u.set(_,[]),u.get(_).push(S)}let l=[];if(M()&&u.size>0)for(let[S,_]of u){let d=await G(`/api/cli/projects/${S}/resources`).catch(()=>null),m=d&&d.ok?d.data.resources.length:_.length,p=o?.projectId===S?o.projectName:`Project ${S.slice(0,8)}`;l.push({projectId:S,projectName:p,localCount:_.length,serverCount:m,synced:_.length>=m})}let h={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(S=>S.id),installedCount:n.installations.length,globalCount:a.length,projects:l};if(x()){j("status",h);return}if(w("Shared Context CLI Status"),w("\u2500".repeat(40)),e?.token?w(` Auth: ${e.email} (${e.orgSlug})`):w(" Auth: Not logged in"),w(` API: ${t.apiBase}`),s.length>0?w(` Agents: ${s.map(S=>S.label).join(", ")}`):w(" Agents: None detected"),w(` Global: ${a.length} resource${a.length===1?"":"s"} installed`),l.length>0){w(""),w("Projects:");for(let S of l){let _=S.synced?"\u2713 synced":`\u26A0 ${S.serverCount-S.localCount} new`;w(` ${S.projectName}: ${S.localCount}/${S.serverCount} resources (${_})`)}}else o&&(w(""),w(` Project: ${o.projectName} (linked)`))})}me();se();function go(r){r.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=Se();e.revoke&&M()&&await yr("/api/cli/auth"),pr(),x()?j("logout",{email:t?.email||null}):w("Logged out.")})}var Vt=require("fs"),yo=require("path");se();function Eo(r){r.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=t.github;if(o&&e&&(x()?P("import","INVALID_ARGS","Cannot use --github with a local path"):R("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(x()?P("import","INVALID_ARGS","Provide a local path or --github <url>"):R("Error: Provide a local path or --github <url>"),process.exit(1)),M()||(x()?P("import","AUTH_MISSING","Authentication required for import"):R("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(x()?P("import","INVALID_ARGS","--on-conflict is not supported with --github"):R("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(x()?P("import","INVALID_ARGS","--dry-run is not supported with --github"):R("Error: --dry-run is not supported with --github"),process.exit(1));let m={url:o};t.resourceType&&(m.resourceType=t.resourceType),x()||w(`
151
+ Importing from GitHub: ${o}`);let p=await L("/api/cli/github-import",m);p.ok||(x()?P("import",p.error.code,p.error.message):R(`
152
+ Import failed: ${p.error.message}`),process.exit(1));let f=p.data;if(x()){j("import",f);return}w(""),w(` Source: ${f.source.owner}/${f.source.repo}`),w(` Type: ${f.resourceType}`),w(` Title: ${f.title}`),f.slug&&w(` Slug: ${f.slug}`),w(` URL: ${f.url}`),w(""),w("Import complete: 1 created");return}let a=(0,yo.resolve)(e);(!(0,Vt.existsSync)(a)||!(0,Vt.statSync)(a).isDirectory())&&(x()?P("import","INVALID_PATH",`Not a directory: ${a}`):R(`Error: Not a directory: ${a}`),process.exit(1));let c=rt(a);if(c.resources.length===0){x()?j("import",{resources:[],message:"No resources found"}):w("No resources found in the specified directory.");return}if(!x()){let m=new Map;for(let f of c.resources)m.set(f.resourceType,(m.get(f.resourceType)||0)+1);let p=[...m.entries()].map(([f,g])=>`${g} ${f}${g===1?"":"s"}`).join(", ");w(`
153
+ Discovered ${c.resources.length} resources in ${e}:`),w(` ${p}`),c.formatLabel&&c.pluginName?w(` ${c.formatLabel}: ${c.pluginName}`):c.pluginName&&w(` Plugin: ${c.pluginName}`)}let u=t.tags?t.tags.split(",").map(m=>m.trim()).filter(Boolean):void 0,l={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:u,resources:c.resources,collectionMemberships:c.collectionMemberships.length>0?c.collectionMemberships:void 0};!x()&&!t.dryRun?w(`
154
+ Executing import...`):x()||w(`
155
+ Dry run \u2014 previewing changes...`);let h=await L("/api/cli/import",l,12e4);h.ok||(x()?P("import",h.error.code,h.error.message):R(`
156
+ Import failed: ${h.error.message}`),process.exit(1));let S=h.data;if(x()){j("import",S);return}let _=[...S.created.map(m=>({...m,action:"created"})),...S.updated.map(m=>({...m,action:"updated"})),...S.installed.map(m=>({...m,action:"installed"})),...S.cloned.map(m=>({...m,action:"cloned"})),...S.skipped.map(m=>({...m,action:"skipped"})),...S.errors.map(m=>({...m,action:"error"}))];if(_.length>0){w("");let m=_.length,p=_.map((f,g)=>{let C=`[${String(g+1).padStart(String(m).length)}/${m}]`,i=(f.resourceType||"").padEnd(10),y=(f.importPath.split("/").pop()||"").padEnd(24),E="";switch(f.action){case"created":E=`\u2713 created${f.slug?` (slug: ${f.slug})`:""}`;break;case"updated":E="\u2713 updated";break;case"installed":{let b=f.versionsBehind;E=`\u2713 installed${b?` (${b} versions behind)`:""}`;break}case"cloned":E=`\u2713 cloned${f.slug?` (slug: ${f.slug})`:""}`;break;case"skipped":E=`\u2713 skipped (${f.reason||"up to date"})`;break;case"error":E=`\u2717 error: ${f.error||"unknown"}`;break}return` ${C} ${i} ${y} ${E}`});for(let f of p)w(f)}if(S.collections.length>0)for(let m of S.collections){let p=m.importPath.split("/").pop()||m.importPath;w(` collection ${p.padEnd(20)} \u2713 ${m.membersLinked} members linked${m.membersFailed>0?`, ${m.membersFailed} failed`:""}`)}w("");let d=[S.created.length>0?`${S.created.length} created`:null,S.installed.length>0?`${S.installed.length} installed`:null,S.cloned.length>0?`${S.cloned.length} cloned`:null,S.updated.length>0?`${S.updated.length} updated`:null,S.skipped.length>0?`${S.skipped.length} skipped`:null,S.errors.length>0?`${S.errors.length} errors`:null].filter(Boolean);t.dryRun?w(`Dry run complete: ${d.join(", ")}`):w(`Import complete: ${d.join(", ")}`),S.errors.length>0&&process.exit(1)})}var wo=require("path"),Ao=require("os");se();me();function _o(r){r.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(!n.force&&!hr()){let I=Et();if(I){let O={...I.lastResult,updates:[],untracked:[],summary:So(I.lastResult.updatesAvailable,I.lastResult.untrackedResources),throttled:!0};Co(O,!!n.quiet);return}}M()||(x()?P("sync","AUTH_MISSING","Login required to sync."):R("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=be(n.agent),o=[],a=await G("/api/cli/updates");a.ok&&(o=a.data.updates);let c=s?[s]:De();c.length===0&&!x()&&!n.quiet&&R("No AI agents detected \u2014 resource discovery skipped. Use --agent to specify one.");let u=[],l=[],h=new Set;for(let I of c){let O=(0,wo.join)((0,Ao.homedir)(),I.dir),T=rt(O,{settingsPath:fe(I,!!n.project),mcpConfigPath:re(I,!!n.project)});for(let k of T.resources)h.has(k.importPath)||(h.add(k.importPath),u.push(k));for(let k of T.collectionMemberships)h.has(`cm:${k.collectionImportPath}`)||(h.add(`cm:${k.collectionImportPath}`),l.push(k))}let S={resources:u,collectionMemberships:l},_=Y(),d=new Set(_.installations.map(I=>I.installPath)),m=new Map;for(let I of _.installations){let O=I.installPath.split("/"),T=O[0],k=O[O.length-1];m.has(T)||m.set(T,new Set),m.get(T).add(k)}let p=new Set(["context-manager",".claude-plugin"]),f=S.resources.filter(I=>{if(d.has(I.importPath))return!1;let O=I.importPath.split("/"),T=O[0],k=O[O.length-1];return!((T==="mcps"||T==="hooks")&&m.get(T)?.has(k)||I.importPath.startsWith(".")||p.has(k))}),g=f.length;if(n.import!==!1&&f.length>0){let I={dryRun:!1,onConflict:"auto",visibility:"org",resources:f,collectionMemberships:S.collectionMemberships},O=await L("/api/cli/import",I,12e4);if(O.ok){let T=[...O.data.created,...O.data.updated,...O.data.installed];if(!x()&&!n.quiet){if(T.length>0){w(`
157
+ Imported ${T.length} resource${T.length===1?"":"s"}:`);let k=T.map(N=>[` ${(N.resourceType||"").padEnd(12)}`,(N.slug||N.importPath.split("/").pop()||"").padEnd(24),N.importPath]);w(ge(k))}O.data.errors.length>0&&R(`
158
+ ${O.data.errors.length} import error(s)`)}f.length=0}else x()||R(`Import failed: ${O.error.message}`)}let C=xe(),i=0;if(C){let I=await G(`/api/cli/projects/${C.projectId}/resources`);if(!I.ok)!x()&&!n.quiet&&(R(`Warning: Project "${C.projectName}" not found on server (may have been deleted).`),R(" Remove .shared-context/project.json to unlink this directory."));else{let O=I.data.resources,k=Y().installations.filter(F=>F.projectId===C.projectId),N=new Set(k.map(F=>F.resourceId)),D=O.filter(F=>!N.has(F.id));if(D.length>0)if(!s)!x()&&!n.quiet&&R(`
159
+ Project "${C.projectName}" has ${D.length} new resource${D.length===1?"":"s"} \u2014 use --agent to install them.`);else{let F=Ie(s);for(let B of D){let pe=B.installPath;try{let He=await G(`/api/cli/resource/${pe}`);if(!He.ok)continue;await F.install(He.data,"project",s),ue({resourceId:B.id,slug:B.slug||B.id,installPath:pe,title:B.title,sha:B.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:C.projectId}),B.latestSha&&await L("/api/cli/install",{resourceId:B.id,agentPlatform:s.platform,installedSha:B.latestSha}).catch(()=>{}),i++}catch{}}!x()&&!n.quiet&&i>0&&w(`
160
+ Project "${C.projectName}": installed ${i} new resource${i===1?"":"s"}`)}await L(`/api/cli/projects/${C.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let y=g-f.length,E={updatesAvailable:o.length,untrackedResources:f.length};Ze({lastSyncAt:new Date().toISOString(),lastResult:E});let b=Se();b?.connectionId&&L("/api/cli/sync-report",{connectionId:b.connectionId,lastSyncResult:{updatesAvailable:o.length,importedCount:y}}).catch(()=>{});let A={...E,updates:o,untracked:f.map(I=>({importPath:I.importPath,resourceType:I.resourceType,title:I.title})),summary:So(o.length,f.length),throttled:!1};Co(A,!!n.quiet)})}function So(r,e){let t=[];return r>0&&t.push(`${r} update${r===1?"":"s"} available`),e>0&&t.push(`${e} untracked resource${e===1?"":"s"}`),t.length===0?"Everything is up to date.":t.join(", ")}function Co(r,e){if(x()){j("sync",r);return}if(e){let t=r.summary;r.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),r.untrackedResources>0&&(t+=` \u2014 ${r.untrackedResources} untracked`),w(t);return}if(w(""),r.updates.length>0){w(`${r.updates.length} update${r.updates.length===1?"":"s"} available:
161
+ `);let t=r.updates.map(n=>{let s=n.slug||n.resourceId;return[` ${`${n.resourceType==="skill"?"skills":`${n.resourceType}s`}/${s}`}`,n.title,`${n.installedSha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]});w(ge(t)),w("")}if(r.untracked.length>0){w(`${r.untracked.length} untracked resource${r.untracked.length===1?"":"s"}:
162
+ `);let t=r.untracked.map(n=>[` ${n.resourceType.padEnd(12)}`,n.importPath.padEnd(30),n.title]);w(ge(t)),w("")}r.updatesAvailable===0&&r.untrackedResources===0?w("Everything is up to date."):(r.updatesAvailable>0&&w("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&w("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),w("")}var bo=require("path");se();se();function xo(r){r.command("project").description("Manage projects").command("create").description("Create a project for the current folder").argument("[name]","Project name (defaults to folder name)").action(async t=>{if(!M()){let l="Not authenticated. Run 'shared-context-ai login' first.";x()?P("project create","AUTH_MISSING",l):R(l),process.exit(1)}let n=xe();if(n){x()?j("project create",{alreadyExists:!0,project:{id:n.projectId,name:n.projectName,slug:n.projectSlug}}):w(`Project already linked: ${n.projectName}`);return}let s=t?.trim()||(0,bo.basename)(process.cwd());if(!s||s==="/"){let l='Could not determine project name. Provide one: shared-context-ai project create "My Project"';x()?P("project create","INVALID_NAME",l):R(l),process.exit(1)}let o=await L("/api/cli/projects",{name:s});o.ok||(x()?P("project create",o.error.code,o.error.message):R(`Failed to create project: ${o.error.message}`),process.exit(1));let{id:a,name:c,slug:u}=o.data;lt({projectId:a,projectName:c,projectSlug:u}),x()?j("project create",{id:a,name:c,slug:u}):(w(`Created project: ${c}`),w(""),w("Quick reference:"),w(" shared-context-ai install <installPath> Add a resource to this project"),w(" shared-context-ai sync Check for resource updates"),w(" shared-context-ai status View project sync status"))})}var Io={AUTH_MISSING:"Run 'shared-context-ai login' to authenticate.",AUTH_EXPIRED:"Run 'shared-context-ai login' to re-authenticate.",SKILL_NOT_FOUND:"Check the skill slug and try again.",ALREADY_INSTALLED:"Use 'shared-context-ai update <slug>' to update instead.",NO_AGENTS:"No AI coding agents detected. Run 'shared-context-ai init --agent <name>' to set up manually.",API_ERROR:"The server returned an error. Try again later.",WRITE_FAILED:"Could not write files to disk. Check permissions."},Gt=class extends Error{constructor(t,n){super(n||Io[t]);this.code=t;this.name="CliError"}get recovery(){return Io[this.code]}};var le=new fn;le.name("shared-context-ai").description("CLI for Shared Context - search, install, and manage AI skills").version("0.1.0").option("--json","Output as JSON (default when piped)").option("--human","Output as human-readable text (default in TTY)").option("--agent <name>","Override agent detection").option("--project","Use project-local directory instead of global").hook("preAction",r=>{let e=r.opts();mn(!!e.json,!!e.human)});_s(le);ro(le);so(le);ps(le);io(le);ao(le);co(le);fo(le);mo(le);ho(le);go(le);Eo(le);_o(le);xo(le);process.on("uncaughtException",r=>{r instanceof Gt?x()?P(process.argv[2]||"unknown",r.code,r.message):(R(`Error: ${r.message}`),R(r.recovery)):x()?P(process.argv[2]||"unknown","UNEXPECTED",r.message||"Unexpected error"):R(`Error: ${r.message||r}`),process.exit(1)});le.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shared-context-ai",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
4
4
  "description": "CLI for Shared Context - search, install, and manage AI skills",
5
5
  "bin": {
6
6
  "shared-context-ai": "dist/index.js"
@@ -20,9 +20,13 @@
20
20
  ],
21
21
  "license": "MIT",
22
22
  "devDependencies": {
23
+ "@types/adm-zip": "^0.5.8",
23
24
  "commander": "^13.1.0",
24
25
  "open": "^10.1.0",
25
26
  "tsup": "^8.4.0",
26
27
  "typescript": "^5.8.0"
28
+ },
29
+ "dependencies": {
30
+ "adm-zip": "^0.5.16"
27
31
  }
28
32
  }