shared-context-ai 0.1.5 → 0.1.7

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 +102 -59
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,44 +1,51 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Hi=Object.create;var _e=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var Di=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var O=(n,e)=>()=>(n&&(e=n(n=0)),e);var B=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),we=(n,e)=>{for(var t in e)_e(n,t,{get:e[t],enumerable:!0})},Mi=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Di(e))!Li.call(n,r)&&r!==t&&_e(n,r,{get:()=>e[r],enumerable:!(i=Fi(e,r))||i.enumerable});return n};var C=(n,e,t)=>(t=n!=null?Hi(Ni(n)):{},Mi(e||!n||!n.__esModule?_e(t,"default",{value:n,enumerable:!0}):t,n));var X=B(ye=>{"use strict";var ie=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},xe=class extends ie{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ye.CommanderError=ie;ye.InvalidArgumentError=xe});var re=B(Ae=>{"use strict";var{InvalidArgumentError:Ri}=X(),Ce=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,i)=>{if(!this.argChoices.includes(t))throw new Ri(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Vi(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Ae.Argument=Ce;Ae.humanReadableArgName=Vi});var Se=B(be=>{"use strict";var{humanReadableArgName:ji}=re(),Oe=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(r=>!r._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((r,s)=>r.name().localeCompare(s.name())),t}compareOptions(e,t){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),i=e._getHelpOption();if(i&&!i.hidden){let r=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!r&&!s?t.push(i):i.long&&!s?t.push(e.createOption(i.long,i.description)):i.short&&!r&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let r=i.options.filter(s=>!s.hidden);t.push(...r)}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(i=>ji(i)).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((i,r)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,r)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let r=e.parent;r;r=r.parent)i=r.name()+" "+i;return i+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(i=>JSON.stringify(i)).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(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),r=t.helpWidth??80;function s(p,_){return t.formatItem(p,i,_,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],l=t.commandDescription(e);l.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(l),r),""]));let a=t.visibleArguments(e).map(p=>s(t.styleArgumentTerm(t.argumentTerm(p)),t.styleArgumentDescription(t.argumentDescription(p))));a.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...a,""]));let c=t.visibleOptions(e).map(p=>s(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));if(c.length>0&&(o=o.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(_=>s(t.styleOptionTerm(t.optionTerm(_)),t.styleOptionDescription(t.optionDescription(_))));p.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...p,""]))}let h=t.visibleCommands(e).map(p=>s(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));return h.length>0&&(o=o.concat([t.styleTitle("Commands:"),...h,""])),o.join(`
3
- `)}displayWidth(e){return mt(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,i,r){let o=" ".repeat(2);if(!i)return o+e;let l=e.padEnd(t+e.length-r.displayWidth(e)),a=2,h=(this.helpWidth??80)-t-a-2,p;return h<this.minWidthToWrap||r.preformatted(i)?p=i:p=r.boxWrap(i,h).replace(/\n/g,`
4
- `+" ".repeat(t+a)),o+l+" ".repeat(a)+p.replace(/\n/g,`
5
- ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let l=o.match(r);if(l===null){s.push("");return}let a=[l.shift()],c=this.displayWidth(a[0]);l.forEach(h=>{let p=this.displayWidth(h);if(c+p<=t){a.push(h),c+=p;return}s.push(a.join(""));let _=h.trimStart();a=[_],c=this.displayWidth(_)}),s.push(a.join(""))}),s.join(`
6
- `)}};function mt(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}be.Help=Oe;be.stripColor=mt});var Te=B(ve=>{"use strict";var{InvalidArgumentError:Wi}=X(),Ee=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 i=Ui(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}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,i)=>{if(!this.argChoices.includes(t))throw new Wi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?ft(this.name().replace(/^no-/,"")):ft(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ke=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,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let r=this.negativeOptions.get(i).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}};function ft(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ui(n){let e,t,i=/^-[^-]$/,r=/^--[^-]/,s=n.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(e=s.shift()),r.test(s[0])&&(t=s.shift()),!e&&i.test(s[0])&&(e=s.shift()),!e&&r.test(s[0])&&(e=t,t=s.shift()),s[0].startsWith("-")){let o=s[0],l=`option creation failed due to '${o}' in option flags '${n}'`;throw/^-[^-][^-]/.test(o)?new Error(`${l}
2
+ "use strict";var ks=Object.create;var nt=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var $s=Object.getOwnPropertyNames;var Ps=Object.getPrototypeOf,Ts=Object.prototype.hasOwnProperty;var L=(n,e)=>()=>(n&&(e=n(n=0)),e);var pe=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),it=(n,e)=>{for(var t in e)nt(n,t,{get:e[t],enumerable:!0})},Is=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $s(e))!Ts.call(n,s)&&s!==t&&nt(n,s,{get:()=>e[s],enumerable:!(r=Es(e,s))||r.enumerable});return n};var N=(n,e,t)=>(t=n!=null?ks(Ps(n)):{},Is(e||!n||!n.__esModule?nt(t,"default",{value:n,enumerable:!0}):t,n));var Ee=pe(at=>{"use strict";var Te=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}},ot=class extends Te{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};at.CommanderError=Te;at.InvalidArgumentError=ot});var Ie=pe(ct=>{"use strict";var{InvalidArgumentError:Rs}=Ee(),lt=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 Rs(`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 js(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}ct.Argument=lt;ct.humanReadableArgName=js});var mt=pe(pt=>{"use strict";var{humanReadableArgName:Fs}=Ie(),ut=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,i)=>s.name().localeCompare(i.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),i=r.long&&e._findOption(r.long);!s&&!i?t.push(r):r.long&&!i?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(i=>!i.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=>Fs(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 i(p,m){return t.formatItem(p,r,m,t)}let a=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],l=t.commandDescription(e);l.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(l),s),""]));let o=t.visibleArguments(e).map(p=>i(t.styleArgumentTerm(t.argumentTerm(p)),t.styleArgumentDescription(t.argumentDescription(p))));o.length>0&&(a=a.concat([t.styleTitle("Arguments:"),...o,""]));let c=t.visibleOptions(e).map(p=>i(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));if(c.length>0&&(a=a.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(m=>i(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));p.length>0&&(a=a.concat([t.styleTitle("Global Options:"),...p,""]))}let u=t.visibleCommands(e).map(p=>i(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 rr(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 l=e.padEnd(t+e.length-s.displayWidth(e)),o=2,u=(this.helpWidth??80)-t-o-2,p;return u<this.minWidthToWrap||s.preformatted(r)?p=r:p=s.boxWrap(r,u).replace(/\n/g,`
4
+ `+" ".repeat(t+o)),a+l+" ".repeat(o)+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,i=[];return r.forEach(a=>{let l=a.match(s);if(l===null){i.push("");return}let o=[l.shift()],c=this.displayWidth(o[0]);l.forEach(u=>{let p=this.displayWidth(u);if(c+p<=t){o.push(u),c+=p;return}i.push(o.join(""));let m=u.trimStart();o=[m],c=this.displayWidth(m)}),i.push(o.join(""))}),i.join(`
6
+ `)}};function rr(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}pt.Help=ut;pt.stripColor=rr});var gt=pe(ft=>{"use strict";var{InvalidArgumentError:Ds}=Ee(),dt=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=Ns(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 Ds(`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?sr(this.name().replace(/^no-/,"")):sr(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ht=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,i=s!==void 0?s:!1;return t.negate===(i===e)}};function sr(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ns(n){let e,t,r=/^-[^-]$/,s=/^--[^-]/,i=n.split(/[ |,]+/).concat("guard");if(r.test(i[0])&&(e=i.shift()),s.test(i[0])&&(t=i.shift()),!e&&r.test(i[0])&&(e=i.shift()),!e&&s.test(i[0])&&(e=t,t=i.shift()),i[0].startsWith("-")){let a=i[0],l=`option creation failed due to '${a}' in option flags '${n}'`;throw/^-[^-][^-]/.test(a)?new Error(`${l}
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')`):i.test(o)?new Error(`${l}
10
- - too many short flags`):r.test(o)?new Error(`${l}
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(a)?new Error(`${l}
10
+ - too many short flags`):s.test(a)?new Error(`${l}
11
11
  - too many long flags`):new Error(`${l}
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}}ve.Option=Ee;ve.DualOptions=ke});var _t=B(gt=>{"use strict";function Bi(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let i=0;i<=n.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let r=1;r<=n.length;r++){let s=1;n[r-1]===e[i-1]?s=0:s=1,t[r][i]=Math.min(t[r-1][i]+1,t[r][i-1]+1,t[r-1][i-1]+s),r>1&&i>1&&n[r-1]===e[i-2]&&n[r-2]===e[i-1]&&(t[r][i]=Math.min(t[r][i],t[r-2][i-2]+1))}return t[n.length][e.length]}function qi(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(o=>o.slice(2)));let i=[],r=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let l=Bi(n,o),a=Math.max(n.length,o.length);(a-l)/a>s&&(l<r?(r=l,i=[o]):l===r&&i.push(o))}),i.sort((o,l)=>o.localeCompare(l)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
13
- (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
14
- (Did you mean ${i[0]}?)`:""}gt.suggestSimilar=qi});var Ct=B(Fe=>{"use strict";var Gi=require("events").EventEmitter,$e=require("child_process"),H=require("path"),ne=require("fs"),m=require("process"),{Argument:Ji,humanReadableArgName:Yi}=re(),{CommanderError:Ie}=X(),{Help:Ki,stripColor:zi}=Se(),{Option:wt,DualOptions:Xi}=Te(),{suggestSimilar:xt}=_t(),Pe=class n extends Gi{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=>m.stdout.write(t),writeErr:t=>m.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>He()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>He()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:t=>zi(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,i){let r=t,s=i;typeof r=="object"&&r!==null&&(s=r,r=null),s=s||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return r&&(a.description(r),a._executableHandler=!0),s.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(s.noHelp||s.hidden),a._executableFile=s.executableFile||null,l&&a.arguments(l),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),r?this:a}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Ki,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 Ji(e,t)}argument(e,t,i,r){let s=this.createArgument(e,t);return typeof i=="function"?s.default(r).argParser(i):s.default(i),this.addArgument(s),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[,i,r]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(i);return o.helpOption(!1),r&&o.arguments(r),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,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 i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
- Expecting one of '${i.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,i){this._exitCallback&&this._exitCallback(new Ie(e,t,i)),m.exit(e)}action(e){let t=i=>{let r=this.registeredArguments.length,s=i.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new wt(e,t)}_callParseArg(e,t,i,r){try{return e.parseArg(t,i)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=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 '${i}'
17
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),i=t(e).find(r=>this._findCommand(r));if(i){let r=t(this._findCommand(i)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let r=(s,o,l)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let a=this.getOptionValue(i);s!==null&&e.parseArg?s=this._callParseArg(e,s,a,o):s!==null&&e.variadic&&(s=e._concatValue(s,a)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,l)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,o,"env")}),this}_optionEx(e,t,i,r,s){if(typeof t=="object"&&t instanceof wt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(s).argParser(r);else if(r instanceof RegExp){let l=r;r=(a,c)=>{let h=l.exec(a);return h?h[0]:c},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,i,r){return this._optionEx({},e,t,i,r)}requiredOption(e,t,i,r){return this._optionEx({mandatory:!0},e,t,i,r)}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,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.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){m.versions?.electron&&(t.from="electron");let r=m.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=m.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=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",i}parse(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),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,i){if(ne.existsSync(e))return;let r=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
19
- - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
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}}ft.Option=dt;ft.DualOptions=ht});var ir=pe(nr=>{"use strict";function Ms(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 i=1;n[s-1]===e[r-1]?i=0:i=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+i),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 Hs(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,i=.4;return e.forEach(a=>{if(a.length<=1)return;let l=Ms(n,a),o=Math.max(n.length,a.length);(o-l)/o>i&&(l<s?(s=l,r=[a]):l===s&&r.push(a))}),r.sort((a,l)=>a.localeCompare(l)),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]}?)`:""}nr.suggestSimilar=Hs});var cr=pe(xt=>{"use strict";var Ls=require("events").EventEmitter,yt=require("child_process"),re=require("path"),Re=require("fs"),x=require("process"),{Argument:Ws,humanReadableArgName:Vs}=Ie(),{CommanderError:bt}=Ee(),{Help:Us,stripColor:Bs}=mt(),{Option:or,DualOptions:qs}=gt(),{suggestSimilar:ar}=ir(),wt=class n extends Ls{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=>x.stdout.write(t),writeErr:t=>x.stderr.write(t),outputError:(t,r)=>r(t),getOutHelpWidth:()=>x.stdout.isTTY?x.stdout.columns:void 0,getErrHelpWidth:()=>x.stderr.isTTY?x.stderr.columns:void 0,getOutHasColors:()=>St()??(x.stdout.isTTY&&x.stdout.hasColors?.()),getErrHasColors:()=>St()??(x.stderr.isTTY&&x.stderr.hasColors?.()),stripColor:t=>Bs(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,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,a,l]=e.match(/([^ ]+) *(.*)/),o=this.createCommand(a);return s&&(o.description(s),o._executableHandler=!0),i.isDefault&&(this._defaultCommandName=o._name),o._hidden=!!(i.noHelp||i.hidden),o._executableFile=i.executableFile||null,l&&o.arguments(l),this._registerCommand(o),o.parent=this,o.copyInheritedSettings(this),s?this:o}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Us,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 Ws(e,t)}argument(e,t,r,s){let i=this.createArgument(e,t);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),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(/([^ ]+) *(.*)/),i=t??"display help for command",a=this.createCommand(r);return a.helpOption(!1),s&&a.arguments(s),i&&a.description(i),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 bt(e,t,r)),x.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new or(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let a=`${s} ${i.message}`;this.error(a,{exitCode:i.exitCode,code:i.code})}throw i}}_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("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' 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 i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,a,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let o=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,o,a):i!==null&&e.variadic&&(i=e._concatValue(i,o)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+t,i=>{let a=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let a=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,a,"env")}),this}_optionEx(e,t,r,s,i){if(typeof t=="object"&&t instanceof or)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(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(o,c)=>{let u=l.exec(o);return u?u[0]:c},a.default(i).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){x.versions?.electron&&(t.from="electron");let s=x.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=x.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":x.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(Re.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",i=`'${e}' does not exist
19
+ - if '${r}' 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
- - ${r}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(h,p){let _=H.resolve(h,p);if(ne.existsSync(_))return _;if(r.includes(H.extname(p)))return;let T=r.find(x=>ne.existsSync(`${_}${x}`));if(T)return`${_}${T}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let h;try{h=ne.realpathSync(this._scriptPath)}catch{h=this._scriptPath}l=H.resolve(H.dirname(h),l)}if(l){let h=s(l,o);if(!h&&!e._executableFile&&this._scriptPath){let p=H.basename(this._scriptPath,H.extname(this._scriptPath));p!==this._name&&(h=s(l,`${p}-${e._name}`))}o=h||o}i=r.includes(H.extname(o));let a;m.platform!=="win32"?i?(t.unshift(o),t=yt(m.execArgv).concat(t),a=$e.spawn(m.argv[0],t,{stdio:"inherit"})):a=$e.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,l,e._name),t.unshift(o),t=yt(m.execArgv).concat(t),a=$e.spawn(m.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{m.on(p,()=>{a.killed===!1&&a.exitCode===null&&a.kill(p)})});let c=this._exitCallback;a.on("close",h=>{h=h??1,c?c(new Ie(h,"commander.executeSubCommandAsync","(close)")):m.exit(h)}),a.on("error",h=>{if(h.code==="ENOENT")this._checkForMissingExecutable(o,l,e._name);else if(h.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)m.exit(1);else{let p=new Ie(1,"commander.executeSubCommandAsync","(error)");p.nestedError=h,c(p)}}),this.runningCommand=a}_dispatchSubcommand(e,t,i){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(i));else return r._parseCommand(t,i)}),s}_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=(i,r,s)=>{let o=r;if(r!==null&&i.parseArg){let l=`error: command-argument value '${r}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,r,s,l)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,r)=>{let s=i.defaultValue;i.variadic?r<this.args.length?(s=this.args.slice(r),i.parseArg&&(s=s.reduce((o,l)=>e(i,l,o),i.defaultValue))):s===void 0&&(s=[]):r<this.args.length&&(s=this.args[r],i.parseArg&&(s=e(i,s,i.defaultValue))),t[r]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,r=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:s,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let r=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{r=this._chainOrCall(r,()=>s(this,t))}),r}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.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(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))r(),this._processArguments(),this.parent.emit(s,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():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),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(i=>{let r=i.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let r=e.find(s=>i.conflictsWith.includes(s.attributeName()));r&&this._conflictingOption(i,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],r=t,s=e.slice();function o(a){return a.length>1&&a[0]==="-"}let l=null;for(;s.length;){let a=s.shift();if(a==="--"){r===i&&r.push(a),r.push(...s);break}if(l&&!o(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,o(a)){let c=this._findOption(a);if(c){if(c.required){let h=s.shift();h===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,h)}else if(c.optional){let h=null;s.length>0&&!o(s[0])&&(h=s.shift()),this.emit(`option:${c.name()}`,h)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),s.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),h=this._findOption(a.slice(0,c));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,a.slice(c+1));continue}}if(o(a)&&(r=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),s.length>0&&i.push(...s);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){i.push(a),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){r.push(a),s.length>0&&r.push(...s);break}r.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let r=this.options[i].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}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(i)}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,p){let m=re.resolve(u,p);if(Re.existsSync(m))return m;if(s.includes(re.extname(p)))return;let h=s.find(y=>Re.existsSync(`${m}${y}`));if(h)return`${m}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let u;try{u=Re.realpathSync(this._scriptPath)}catch{u=this._scriptPath}l=re.resolve(re.dirname(u),l)}if(l){let u=i(l,a);if(!u&&!e._executableFile&&this._scriptPath){let p=re.basename(this._scriptPath,re.extname(this._scriptPath));p!==this._name&&(u=i(l,`${p}-${e._name}`))}a=u||a}r=s.includes(re.extname(a));let o;x.platform!=="win32"?r?(t.unshift(a),t=lr(x.execArgv).concat(t),o=yt.spawn(x.argv[0],t,{stdio:"inherit"})):o=yt.spawn(a,t,{stdio:"inherit"}):(this._checkForMissingExecutable(a,l,e._name),t.unshift(a),t=lr(x.execArgv).concat(t),o=yt.spawn(x.execPath,t,{stdio:"inherit"})),o.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{x.on(p,()=>{o.killed===!1&&o.exitCode===null&&o.kill(p)})});let c=this._exitCallback;o.on("close",u=>{u=u??1,c?c(new bt(u,"commander.executeSubCommandAsync","(close)")):x.exit(u)}),o.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(a,l,e._name);else if(u.code==="EACCES")throw new Error(`'${a}' not executable`);if(!c)x.exit(1);else{let p=new bt(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,c(p)}}),this.runningCommand=o}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),i}_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,i)=>{let a=s;if(s!==null&&r.parseArg){let l=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;a=this._callParseArg(r,s,i,l)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((a,l)=>e(r,l,a),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),t[s]=i}),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(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(a=>{s.push({hookedCommand:i,callback:a})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(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])},i=`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(i,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,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(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],s=t,i=e.slice();function a(o){return o.length>1&&o[0]==="-"}let l=null;for(;i.length;){let o=i.shift();if(o==="--"){s===r&&s.push(o),s.push(...i);break}if(l&&!a(o)){this.emit(`option:${l.name()}`,o);continue}if(l=null,a(o)){let c=this._findOption(o);if(c){if(c.required){let u=i.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;i.length>0&&!a(i[0])&&(u=i.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(o.length>2&&o[0]==="-"&&o[1]!=="-"){let c=this._findOption(`-${o[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,o.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${o.slice(2)}`));continue}}if(/^--[^=]+=/.test(o)){let c=o.indexOf("="),u=this._findOption(o.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,o.slice(c+1));continue}}if(a(o)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(o)){t.push(o),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&o===this._getHelpCommand().name()){t.push(o),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){r.push(o),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(o),i.length>0&&s.push(...i);break}s.push(o)}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}
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 i=t||{},r=i.exitCode||1,s=i.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in m.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()}`,m.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Xi(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,i.implied[r],"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 i=o=>{let l=o.attributeName(),a=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),h=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:h||o},r=o=>{let l=i(o),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(l=>l.long).map(l=>l.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=xt(e,r)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(s=>{r.push(s.name()),s.alias()&&r.push(s.alias())}),t=xt(e,r)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let r=this.createOption(t,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.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 i=this.parent?._findCommand(e);if(i){let r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}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(i=>Yi(i));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=H.basename(e,H.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),i=this._getOutputContext(e);t.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let r=t.formatHelp(this,t);return i.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,i,r,s;return t?(i=l=>this._outputConfiguration.writeErr(l),r=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=l=>this._outputConfiguration.writeOut(l),r=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:l=>(r||(l=this._outputConfiguration.stripColor(l)),i(l)),hasColors:r,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getOutputContext(e),r={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation({error:i.error});if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",r))}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(m.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
- Expecting one of '${i.join("', '")}'`);let r=`${e}Help`;return this.on(r,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
27
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function yt(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",r="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?r=s[3]:i=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],i=s[3],r=s[4]),t&&r!=="0"?`${t}=${i}:${parseInt(r)+1}`:e})}function He(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}Fe.Command=Pe;Fe.useColor=He});var St=B(S=>{"use strict";var{Argument:At}=re(),{Command:De}=Ct(),{CommanderError:Qi,InvalidArgumentError:Ot}=X(),{Help:Zi}=Se(),{Option:bt}=Te();S.program=new De;S.createCommand=n=>new De(n);S.createOption=(n,e)=>new bt(n,e);S.createArgument=(n,e)=>new At(n,e);S.Command=De;S.Option=bt;S.Argument=At;S.Help=Zi;S.CommanderError=Qi;S.InvalidArgumentError=Ot;S.InvalidOptionArgumentError=Ot});var Dt={};we(Dt,{addToManifest:()=>N,clearAuth:()=>Ve,getAuth:()=>P,getConfig:()=>D,getManifest:()=>F,removeFromManifest:()=>We,saveAuth:()=>Re,saveConfig:()=>Ft,saveManifest:()=>je,updateConfig:()=>ir});function er(){(0,$.mkdirSync)(se,{recursive:!0})}function Le(n,e){try{return(0,$.existsSync)(n)?JSON.parse((0,$.readFileSync)(n,"utf-8")):e}catch{return e}}function Me(n,e,t=!1){if(er(),(0,$.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
- `,"utf-8"),t)try{(0,$.chmodSync)(n,384)}catch{}}function P(){return Le(Ne,null)}function Re(n){Me(Ne,n,!0)}function Ve(){try{(0,$.writeFileSync)(Ne,"{}","utf-8")}catch{}}function D(){return Le(Pt,tr)}function Ft(n){Me(Pt,n)}function ir(n){let e=D();Ft({...e,...n})}function F(){return Le(Ht,rr)}function je(n){Me(Ht,n)}function N(n){let e=F(),t=e.installations.findIndex(i=>i.resourceId===n.resourceId&&i.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),je(e)}function We(n,e){let t=F();t.installations=t.installations.filter(i=>!(i.resourceId===n&&(!e||i.agent===e))),je(t)}var $,Q,It,se,Ne,Pt,Ht,tr,rr,E=O(()=>{"use strict";$=require("fs"),Q=require("path"),It=require("os"),se=(0,Q.join)((0,It.homedir)(),".config","shared-context"),Ne=(0,Q.join)(se,"auth.json"),Pt=(0,Q.join)(se,"config.json"),Ht=(0,Q.join)(se,"manifest.json");tr={apiBase:"https://sharedcontext.ai"};rr={installations:[]}});var Nt={};we(Nt,{del:()=>Ue,get:()=>A,isAuthenticated:()=>y,patch:()=>or,post:()=>k});function nr(){return D().apiBase||"https://sharedcontext.ai"}function sr(){let n={"Content-Type":"application/json"},e=P();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function y(){return!!P()?.token}async function oe(n,e,t){let i=`${nr()}${e}`;try{let r=await fetch(i,{method:n,headers:sr(),body:t?JSON.stringify(t):void 0}),s=r.headers.get("content-type")||"";if(!s.includes("application/json"))return r.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${s||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${r.status}`,message:r.statusText}};let o=await r.json();return r.ok?{ok:!0,data:o.data??o}:{ok:!1,error:{code:o?.error?.code||`HTTP_${r.status}`,message:o?.error?.message||o?.message||r.statusText}}}catch(r){return{ok:!1,error:{code:"NETWORK_ERROR",message:r instanceof Error?r.message:"Network request failed"}}}}function A(n){return oe("GET",n)}function k(n,e){return oe("POST",n,e)}function or(n,e){return oe("PATCH",n,e)}function Ue(n,e){return oe("DELETE",n,e)}var v=O(()=>{"use strict";E()});function lr(){try{return Je.default.statSync("/.dockerenv"),!0}catch{return!1}}function cr(){try{return Je.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Ye(){return Ge===void 0&&(Ge=lr()||cr()),Ge}var Je,Ge,Vt=O(()=>{"use strict";Je=C(require("fs"),1)});function G(){return Ke===void 0&&(Ke=ur()||Ye()),Ke}var jt,Ke,ur,ze=O(()=>{"use strict";jt=C(require("fs"),1);Vt();ur=()=>{try{return jt.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Xe,Ut,ue,Wt,V,Qe=O(()=>{"use strict";Xe=C(require("process"),1),Ut=C(require("os"),1),ue=C(require("fs"),1);ze();Wt=()=>{if(Xe.default.platform!=="linux")return!1;if(Ut.default.release().toLowerCase().includes("microsoft"))return!G();try{if(ue.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!G()}catch{}return ue.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||ue.default.existsSync("/run/WSL")?!G():!1},V=Xe.default.env.__IS_WSL_TEST__?Wt:Wt()});var Ze,ee,hr,dr,et,Bt=O(()=>{"use strict";Ze=C(require("process"),1),ee=C(require("fs/promises"),1);Qe();Qe();hr=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await ee.default.access(t,ee.constants.F_OK),i=!0}catch{}if(!i)return n;let r=await ee.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(r);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):n}})(),dr=async()=>`${await hr()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,et=async()=>V?dr():`${Ze.default.env.SYSTEMROOT||Ze.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function j(n,e,t){let i=r=>Object.defineProperty(n,e,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get(){let r=t();return i(r),r},set(r){i(r)}}),n}var qt=O(()=>{"use strict"});async function tt(){if(Jt.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await pr("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 Gt,Jt,Yt,pr,Kt=O(()=>{"use strict";Gt=require("util"),Jt=C(require("process"),1),Yt=require("child_process"),pr=(0,Gt.promisify)(Yt.execFile)});async function Qt(n,{humanReadableOutput:e=!0,signal:t}={}){if(zt.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],r={};t&&(r.signal=t);let{stdout:s}=await mr("osascript",["-e",n,i],r);return s.trim()}var zt,Xt,it,mr,Zt=O(()=>{"use strict";zt=C(require("process"),1),Xt=require("util"),it=require("child_process"),mr=(0,Xt.promisify)(it.execFile)});async function rt(n){return Qt(`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 ei=O(()=>{"use strict";Zt()});async function st(n=fr){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 nt(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,r=i.lastIndexOf("."),s=i.lastIndexOf("-"),o=r===-1?void 0:i.slice(0,r),l=s===-1?void 0:i.slice(0,s);return he[i]??he[o]??he[l]??{name:i,id:i}}var ti,ii,fr,he,wn,nt,ri=O(()=>{"use strict";ti=require("util"),ii=require("child_process"),fr=(0,ti.promisify)(ii.execFile),he={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"}},wn=new Map(Object.entries(he)),nt=class extends Error{}});async function ot(){if(de.default.platform==="darwin"){let n=await tt();return{name:await rt(n),id:n}}if(de.default.platform==="linux"){let{stdout:n}=await gr("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:_r(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(de.default.platform==="win32")return st();throw new Error("Only macOS, Linux, and Windows are supported")}var ni,de,si,gr,_r,oi=O(()=>{"use strict";ni=require("util"),de=C(require("process"),1),si=require("child_process");Kt();ei();ri();gr=(0,ni.promisify)(si.execFile),_r=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var pi={};we(pi,{apps:()=>W,default:()=>Ar,openApp:()=>Cr});async function xr(){let n=await et(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=ct.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await wr(n,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),r=i.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[r]?{id:s[r]}:{}}function ui(n){if(typeof n=="string"||Array.isArray(n))return n;let{[li]:e}=n;if(!e)throw new Error(`${li} is not supported`);return e}function me({[K]:n},{wsl:e}){if(e&&V)return ui(e);if(!n)throw new Error(`${K} is not supported`);return ui(n)}var lt,ct,ut,hi,di,ht,pe,Or,wr,at,ai,K,li,ci,te,yr,Cr,W,Ar,mi=O(()=>{"use strict";lt=C(require("process"),1),ct=require("buffer"),ut=C(require("path"),1),hi=require("url"),di=require("util"),ht=C(require("child_process"),1),pe=C(require("fs/promises"),1);Bt();qt();oi();ze();Or={},wr=(0,di.promisify)(ht.default.execFile),at=ut.default.dirname((0,hi.fileURLToPath)(Or.url)),ai=ut.default.join(at,"xdg-open"),{platform:K,arch:li}=lt.default;ci=async(n,e)=>{let t;for(let i of n)try{return await e(i)}catch(r){t=r}throw t},te=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return ci(n.app,l=>te({...n,app:l}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return ci(e,l=>te({...n,app:{name:l,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let l={"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"},a={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},c=V?await xr():await ot();if(c.id in l){let h=l[c.id];return e==="browserPrivate"&&t.push(a[h]),te({...n,app:{name:W[h],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let i,r=[],s={};if(K==="darwin")i="open",n.wait&&r.push("--wait-apps"),n.background&&r.push("--background"),n.newInstance&&r.push("--new"),e&&r.push("-a",e);else if(K==="win32"||V&&!G()&&!e){i=await et(),r.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),V||(s.windowsVerbatimArguments=!0);let l=["Start"];n.wait&&l.push("-Wait"),e?(l.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&l.push(`"${n.target}"`),t.length>0&&(t=t.map(a=>`"\`"${a}\`""`),l.push("-ArgumentList",t.join(","))),n.target=ct.Buffer.from(l.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let l=!at||at==="/",a=!1;try{await pe.default.access(ai,pe.constants.X_OK),a=!0}catch{}i=lt.default.versions.electron??(K==="android"||l||!a)?"xdg-open":ai}t.length>0&&r.push(...t),n.wait||(s.stdio="ignore",s.detached=!0)}K==="darwin"&&t.length>0&&r.push("--args",...t),n.target&&r.push(n.target);let o=ht.default.spawn(i,r,s);return n.wait?new Promise((l,a)=>{o.once("error",a),o.once("close",c=>{if(!n.allowNonzeroExitCode&&c>0){a(new Error(`Exited with code ${c}`));return}l(o)})}):(o.unref(),o)},yr=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return te({...e,target:n})},Cr=(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 te({...e,app:{name:n,arguments:t}})};W={};j(W,"chrome",()=>me({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"]}}));j(W,"brave",()=>me({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"]}}));j(W,"firefox",()=>me({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));j(W,"edge",()=>me({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));j(W,"browser",()=>"browser");j(W,"browserPrivate",()=>"browserPrivate");Ar=yr});var Et=C(St(),1),{program:Lr,createCommand:Mr,createArgument:Rr,createOption:Vr,CommanderError:jr,InvalidArgumentError:Wr,InvalidOptionArgumentError:Ur,Command:kt,Argument:Br,Option:qr,Help:Gr}=Et.default;var vt=!1,Tt=!1;function $t(n,e){vt=n,Tt=e}function d(){return vt?!0:Tt?!1:!process.stdout.isTTY}function w(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function g(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function u(n){console.log(n)}function f(n){console.error(n)}function q(n,e=2){if(n.length===0)return"";let t=[];for(let i of n)for(let r=0;r<i.length;r++)t[r]=Math.max(t[r]||0,i[r].length);return n.map(i=>i.map((r,s)=>s<i.length-1?r.padEnd(t[s]+e):r).join("")).join(`
30
- `)}var ce=require("fs"),le=require("path");E();v();var Be=require("fs"),Z=require("path"),ae=require("os"),J=[{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 L(n){if(n){let i=J.find(s=>s.id===n);if(i)return i;let r=J.find(s=>s.dir===`.${n}`||s.dir===n);return r||null}for(let i of J)if(i.envVars.some(r=>process.env[r]))return i;let e=(0,ae.homedir)(),t=[];for(let i of J)(0,Be.existsSync)((0,Z.join)(e,i.dir))&&t.push(i);return t.length===1?t[0]:null}function qe(){let n=[],e=(0,ae.homedir)();for(let t of J)(t.envVars.some(i=>process.env[i])||(0,Be.existsSync)((0,Z.join)(e,t.dir)))&&n.push(t);return n}function M(){let n=qe();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 (${J.map(e=>e.id).join(", ")})`}function R(n,e){return e?(0,Z.join)(process.cwd(),n.dir,n.skillsSubdir):(0,Z.join)((0,ae.homedir)(),n.dir,n.skillsSubdir)}var Lt=`---
31
- title: Skill Manager
32
- description: Browse, install, and manage AI skills from the Shared Context library
24
+ `),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in x.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()}`,x.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new qs(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 l=a.attributeName(),o=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),u=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&o===!1||c.presetArg!==void 0&&o===c.presetArg)?c:u||a},s=a=>{let l=r(a),o=l.attributeName();return this.getOptionValueSource(o)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let a=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(a),i=i.parent}while(i&&!i._enablePositionalOptions);t=ar(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",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=ar(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=>Vs(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=re.basename(e,re.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,i;return t?(r=l=>this._outputConfiguration.writeErr(l),s=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(r=l=>this._outputConfiguration.writeOut(l),s=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:l=>(s||(l=this._outputConfiguration.stripColor(l)),r(l)),hasColors:s,helpWidth:i}}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 i=this.helpInformation({error:r.error});if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(i),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(x.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,i=>{let a;typeof t=="function"?a=t({error:i.error,command:i.command}):a=t,a&&i.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 lr(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}function St(){if(x.env.NO_COLOR||x.env.FORCE_COLOR==="0"||x.env.FORCE_COLOR==="false")return!1;if(x.env.FORCE_COLOR||x.env.CLICOLOR_FORCE!==void 0)return!0}xt.Command=wt;xt.useColor=St});var dr=pe(U=>{"use strict";var{Argument:ur}=Ie(),{Command:Ct}=cr(),{CommanderError:Js,InvalidArgumentError:pr}=Ee(),{Help:Gs}=mt(),{Option:mr}=gt();U.program=new Ct;U.createCommand=n=>new Ct(n);U.createOption=(n,e)=>new mr(n,e);U.createArgument=(n,e)=>new ur(n,e);U.Command=Ct;U.Option=mr;U.Argument=ur;U.Help=Gs;U.CommanderError=Js;U.InvalidArgumentError=pr;U.InvalidOptionArgumentError=pr});var _r={};it(_r,{addToManifest:()=>J,clearAuth:()=>kt,getAuth:()=>X,getConfig:()=>ie,getManifest:()=>Q,removeFromManifest:()=>Fe,saveAuth:()=>vt,saveConfig:()=>Ar,saveManifest:()=>Et,updateConfig:()=>zs});function je(){let n=process.env.SC_PROFILE;return n?(0,ye.join)(wr,"profiles",n):wr}function At(){return(0,ye.join)(je(),"auth.json")}function xr(){return(0,ye.join)(je(),"config.json")}function Cr(){return(0,ye.join)(je(),"manifest.json")}function Ys(){(0,q.mkdirSync)(je(),{recursive:!0})}function _t(n,e){try{return(0,q.existsSync)(n)?JSON.parse((0,q.readFileSync)(n,"utf-8")):e}catch{return e}}function Ot(n,e,t=!1){if(Ys(),(0,q.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
+ `,"utf-8"),t)try{(0,q.chmodSync)(n,384)}catch{}}function X(){return _t(At(),null)}function vt(n){Ot(At(),n,!0)}function kt(){try{(0,q.writeFileSync)(At(),"{}","utf-8")}catch{}}function ie(){return _t(xr(),Ks)}function Ar(n){Ot(xr(),n)}function zs(n){let e=ie();Ar({...e,...n})}function Q(){return _t(Cr(),Xs)}function Et(n){Ot(Cr(),n)}function J(n){let e=Q(),t=e.installations.findIndex(r=>r.resourceId===n.resourceId&&r.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),Et(e)}function Fe(n,e){let t=Q();t.installations=t.installations.filter(r=>!(r.resourceId===n&&(!e||r.agent===e))),Et(t)}var q,ye,Sr,wr,Ks,Xs,B=L(()=>{"use strict";q=require("fs"),ye=require("path"),Sr=require("os"),wr=(0,ye.join)((0,Sr.homedir)(),".config","shared-context");Ks={apiBase:"https://sharedcontext.ai"};Xs={installations:[]}});var Or={};it(Or,{del:()=>$t,get:()=>j,isAuthenticated:()=>$,patch:()=>en,post:()=>I});function Qs(){return ie().apiBase||"https://sharedcontext.ai"}function Zs(){let n={"Content-Type":"application/json"},e=X();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function $(){return!!X()?.token}async function De(n,e,t,r){let s=`${Qs()}${e}`;try{let i={method:n,headers:Zs(),body:t?JSON.stringify(t):void 0};r&&(i.signal=AbortSignal.timeout(r));let a=await fetch(s,i),l=a.headers.get("content-type")||"";if(!l.includes("application/json"))return a.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${l||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${a.status}`,message:a.statusText}};let o=await a.json();return a.ok?{ok:!0,data:o.data??o}:{ok:!1,error:{code:o?.error?.code||`HTTP_${a.status}`,message:o?.error?.message||o?.message||a.statusText}}}catch(i){return{ok:!1,error:{code:"NETWORK_ERROR",message:i instanceof Error?i.message:"Network request failed"}}}}function j(n){return De("GET",n)}function I(n,e,t){return De("POST",n,e,t)}function en(n,e){return De("PATCH",n,e)}function $t(n,e){return De("DELETE",n,e)}var W=L(()=>{"use strict";B()});function gn(){try{return Dt.default.statSync("/.dockerenv"),!0}catch{return!1}}function yn(){try{return Dt.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Nt(){return Ft===void 0&&(Ft=gn()||yn()),Ft}var Dt,Ft,Ir=L(()=>{"use strict";Dt=N(require("fs"),1)});function he(){return Mt===void 0&&(Mt=bn()||Nt()),Mt}var Rr,Mt,bn,Ht=L(()=>{"use strict";Rr=N(require("fs"),1);Ir();bn=()=>{try{return Rr.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Lt,Fr,Je,jr,le,Wt=L(()=>{"use strict";Lt=N(require("process"),1),Fr=N(require("os"),1),Je=N(require("fs"),1);Ht();jr=()=>{if(Lt.default.platform!=="linux")return!1;if(Fr.default.release().toLowerCase().includes("microsoft"))return!he();try{if(Je.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!he()}catch{}return Je.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Je.default.existsSync("/run/WSL")?!he():!1},le=Lt.default.env.__IS_WSL_TEST__?jr:jr()});var Vt,$e,wn,Sn,Ut,Dr=L(()=>{"use strict";Vt=N(require("process"),1),$e=N(require("fs/promises"),1);Wt();Wt();wn=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",r=!1;try{await $e.default.access(t,$e.constants.F_OK),r=!0}catch{}if(!r)return n;let s=await $e.default.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return i?(e=i.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):n}})(),Sn=async()=>`${await wn()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ut=async()=>le?Sn():`${Vt.default.env.SYSTEMROOT||Vt.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function ce(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 Nr=L(()=>{"use strict"});async function Bt(){if(Hr.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await xn("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 Mr,Hr,Lr,xn,Wr=L(()=>{"use strict";Mr=require("util"),Hr=N(require("process"),1),Lr=require("child_process"),xn=(0,Mr.promisify)(Lr.execFile)});async function Br(n,{humanReadableOutput:e=!0,signal:t}={}){if(Vr.default.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await Cn("osascript",["-e",n,r],s);return i.trim()}var Vr,Ur,qt,Cn,qr=L(()=>{"use strict";Vr=N(require("process"),1),Ur=require("util"),qt=require("child_process"),Cn=(0,Ur.promisify)(qt.execFile)});async function Jt(n){return Br(`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 Jr=L(()=>{"use strict";qr()});async function Yt(n=An){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 Gt(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,s=r.lastIndexOf("."),i=r.lastIndexOf("-"),a=s===-1?void 0:r.slice(0,s),l=i===-1?void 0:r.slice(0,i);return Ge[r]??Ge[a]??Ge[l]??{name:r,id:r}}var Gr,Yr,An,Ge,so,Gt,Kr=L(()=>{"use strict";Gr=require("util"),Yr=require("child_process"),An=(0,Gr.promisify)(Yr.execFile),Ge={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"}},so=new Map(Object.entries(Ge)),Gt=class extends Error{}});async function Kt(){if(Ye.default.platform==="darwin"){let n=await Bt();return{name:await Jt(n),id:n}}if(Ye.default.platform==="linux"){let{stdout:n}=await _n("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:On(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Ye.default.platform==="win32")return Yt();throw new Error("Only macOS, Linux, and Windows are supported")}var zr,Ye,Xr,_n,On,Qr=L(()=>{"use strict";zr=require("util"),Ye=N(require("process"),1),Xr=require("child_process");Wr();Jr();Kr();_n=(0,zr.promisify)(Xr.execFile),On=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var is={};it(is,{apps:()=>ue,default:()=>Pn,openApp:()=>$n});async function kn(){let n=await Ut(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Qt.Buffer.from(e,"utf16le").toString("base64"),{stdout:r}=await vn(n,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=r.trim(),i={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return i[s]?{id:i[s]}:{}}function rs(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 ze({[_e]:n},{wsl:e}){if(e&&le)return rs(e);if(!n)throw new Error(`${_e} is not supported`);return rs(n)}var Xt,Qt,Zt,ss,ns,er,Ke,Tn,vn,zt,Zr,_e,es,ts,Pe,En,$n,ue,Pn,os=L(()=>{"use strict";Xt=N(require("process"),1),Qt=require("buffer"),Zt=N(require("path"),1),ss=require("url"),ns=require("util"),er=N(require("child_process"),1),Ke=N(require("fs/promises"),1);Dr();Nr();Qr();Ht();Tn={},vn=(0,ns.promisify)(er.default.execFile),zt=Zt.default.dirname((0,ss.fileURLToPath)(Tn.url)),Zr=Zt.default.join(zt,"xdg-open"),{platform:_e,arch:es}=Xt.default;ts=async(n,e)=>{let t;for(let r of n)try{return await e(r)}catch(s){t=s}throw t},Pe=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return ts(n.app,l=>Pe({...n,app:l}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return ts(e,l=>Pe({...n,app:{name:l,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let l={"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"},o={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},c=le?await kn():await Kt();if(c.id in l){let u=l[c.id];return e==="browserPrivate"&&t.push(o[u]),Pe({...n,app:{name:ue[u],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let r,s=[],i={};if(_e==="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(_e==="win32"||le&&!he()&&!e){r=await Ut(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),le||(i.windowsVerbatimArguments=!0);let l=["Start"];n.wait&&l.push("-Wait"),e?(l.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&l.push(`"${n.target}"`),t.length>0&&(t=t.map(o=>`"\`"${o}\`""`),l.push("-ArgumentList",t.join(","))),n.target=Qt.Buffer.from(l.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let l=!zt||zt==="/",o=!1;try{await Ke.default.access(Zr,Ke.constants.X_OK),o=!0}catch{}r=Xt.default.versions.electron??(_e==="android"||l||!o)?"xdg-open":Zr}t.length>0&&s.push(...t),n.wait||(i.stdio="ignore",i.detached=!0)}_e==="darwin"&&t.length>0&&s.push("--args",...t),n.target&&s.push(n.target);let a=er.default.spawn(r,s,i);return n.wait?new Promise((l,o)=>{a.once("error",o),a.once("close",c=>{if(!n.allowNonzeroExitCode&&c>0){o(new Error(`Exited with code ${c}`));return}l(a)})}):(a.unref(),a)},En=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return Pe({...e,target:n})},$n=(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 Pe({...e,app:{name:n,arguments:t}})};ue={};ce(ue,"chrome",()=>ze({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"]}}));ce(ue,"brave",()=>ze({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"]}}));ce(ue,"firefox",()=>ze({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));ce(ue,"edge",()=>ze({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));ce(ue,"browser",()=>"browser");ce(ue,"browserPrivate",()=>"browserPrivate");Pn=En});var hr=N(dr(),1),{program:Kn,createCommand:zn,createArgument:Xn,createOption:Qn,CommanderError:Zn,InvalidArgumentError:ei,InvalidOptionArgumentError:ti,Command:fr,Argument:ri,Option:si,Help:ni}=hr.default;var gr=!1,yr=!1;function br(n,e){gr=n,yr=e}function g(){return gr?!0:yr?!1:!process.stdout.isTTY}function _(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function S(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function d(n){console.log(n)}function w(n){console.error(n)}function me(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,i)=>i<r.length-1?s.padEnd(t[i]+e):s).join("")).join(`
30
+ `)}var qe=require("fs"),Be=require("path");B();W();var Pt=require("fs"),G=require("path"),de=require("os"),be=[{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 oe(n){if(n){let r=be.find(i=>i.id===n);if(r)return r;let s=be.find(i=>i.dir===`.${n}`||i.dir===n);return s||null}for(let r of be)if(r.envVars.some(s=>process.env[s]))return r;let e=(0,de.homedir)(),t=[];for(let r of be)(0,Pt.existsSync)((0,G.join)(e,r.dir))&&t.push(r);return t.length===1?t[0]:null}function Tt(){let n=[],e=(0,de.homedir)();for(let t of be)(t.envVars.some(r=>process.env[r])||(0,Pt.existsSync)((0,G.join)(e,t.dir)))&&n.push(t);return n}function ae(){let n=Tt();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 (${be.map(e=>e.id).join(", ")})`}function A(n,e){return e?(0,G.join)(process.cwd(),n.dir,n.skillsSubdir):(0,G.join)((0,de.homedir)(),n.dir,n.skillsSubdir)}function F(n,e){return e?(0,G.join)(process.cwd(),n.dir,"agents"):(0,G.join)((0,de.homedir)(),n.dir,"agents")}function M(n,e){return e?(0,G.join)(process.cwd(),".mcp.json"):n.id==="claude-code"?(0,G.join)((0,de.homedir)(),".claude.json"):n.id==="cursor"?(0,G.join)((0,de.homedir)(),".cursor","mcp.json"):(0,G.join)(process.cwd(),".mcp.json")}var Y=require("fs"),Se=require("path");var ee=require("fs"),Z=require("path");W();B();var kr={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function v(n,e){let t=(0,Z.resolve)(n);for(let r of e){let s=(0,Z.resolve)((0,Z.join)(n,r.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${r.path}`);(0,ee.mkdirSync)((0,Z.dirname)(s),{recursive:!0}),(0,ee.writeFileSync)(s,r.content,"utf-8")}}function tn(n){let e=n.resource.slug||n.resource.id,t=kr[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 vr(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 It(n,e,t){let r=t.files.find(c=>c.path.endsWith(".json")&&!c.path.includes("/"))||t.files.find(c=>c.path.endsWith(".json")&&c.path.includes("resources/"));if(!r)throw new Error("MCP package does not contain a config file");let s=JSON.parse(r.content),i=M(n,e),a=t.resource.slug||t.resource.id,l={};if((0,ee.existsSync)(i))try{l=JSON.parse((0,ee.readFileSync)(i,"utf-8"))}catch{l={}}let o=typeof l.mcpServers=="object"&&l.mcpServers&&!Array.isArray(l.mcpServers)?l.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(o,s.mcpServers):o[a]=s,l.mcpServers=o,(0,ee.mkdirSync)((0,Z.dirname)(i),{recursive:!0}),(0,ee.writeFileSync)(i,JSON.stringify(l,null,2)+`
31
+ `,"utf-8")}function Er(n){n.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),i=oe(s.agent);if(!i){let f=ae();g()?S("install","NO_AGENTS",f):w(f),process.exit(1)}let a=$(),o=await j(`${a?"/api/cli/resource":"/api/public/resource"}/${e}`);o.ok||(g()?S("install",o.error.code,o.error.message):w(`Install failed: ${o.error.message}`),process.exit(1));let c=o.data,u=c.resource.slug||c.resource.id,p=tn(c),m;if(c.resource.resourceType==="agent"){let f=F(i,!!s.project);m=(0,Z.join)(f,...vr(c));try{v(m,c.files)}catch(O){g()?S("install","WRITE_FAILED",`Failed to write files: ${O}`):w(`Failed to write files: ${O}`),process.exit(1)}}else if(c.resource.resourceType==="mcp"){m="";try{It(i,!!s.project,c)}catch(f){g()?S("install","WRITE_FAILED",`Failed to install MCP config: ${f}`):w(`Failed to install MCP config: ${f}`),process.exit(1)}}else{let f=A(i,!!s.project);m=(0,Z.join)(f,...vr(c));try{if(c.resource.resourceType==="collection"){let E=await we(i).install(c,s.project?"project":"user",i);if(m=E.installDir,!g())for(let C of E.warnings)w(`Warning: ${C}`)}else v(m,c.files)}catch(O){g()?S("install","WRITE_FAILED",`Failed to write files: ${O}`):w(`Failed to write files: ${O}`),process.exit(1)}}let h;if(a&&c.resource.latestSha){let f=await I("/api/cli/install",{resourceId:c.resource.id,agentPlatform:i.platform,installedSha:c.resource.latestSha});f.ok||(h=`Could not record install on server: ${f.error.message}`,g()||w(`Warning: ${h}`))}let y={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},b=c.resource.resourceType==="collection";if(J({resourceId:c.resource.id,slug:u,installPath:p,title:c.resource.title,sha:c.resource.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString(),...b?{pluginFormat:y[i.id]||"directory",memberCount:c.memberResources?.length}:{}}),c.memberResources&&c.resource.resourceType==="collection")for(let f of c.memberResources){let O=f.slug||f.id,E=kr[f.resourceType]||f.resourceType+"s",C=f.orgSlug||c.resource.orgSlug,ne=C?`${E}/${C}/${O}`:`${E}/${O}`;J({resourceId:f.id,slug:O,installPath:ne,title:f.title,sha:f.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString(),collectionId:c.resource.id}),a&&f.latestSha&&await I("/api/cli/install",{resourceId:f.id,agentPlatform:i.platform,installedSha:f.latestSha}).catch(()=>{})}g()?_("install",{installPath:p,title:c.resource.title,path:m||void 0,files:c.files.length,...c.resource.resourceType==="mcp"?{mcpConfigPath:M(i,!!s.project)}:{},...c.memberResources?{memberResources:c.memberResources.length}:{},...h&&{warning:h}}):(c.resource.resourceType==="mcp"?d(`Installed MCP "${c.resource.title}" to ${M(i,!!s.project)}`):d(`Installed "${c.resource.title}" to ${m}`),c.resource.resourceType!=="mcp"&&d(` ${c.files.length} file${c.files.length===1?"":"s"} written`),c.memberResources&&c.memberResources.length>0&&d(` ${c.memberResources.length} member resource${c.memberResources.length===1?"":"s"} included`),a||(d(""),d("Tip: Sign up at sharedcontext.ai to track installations and get updates.")))})}var Ne=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[];for(let l of e.files){let o=l.path.split("/"),c=o[0];if(c==="agents")s.push({path:l.path.slice(7),content:l.content});else if(c==="mcps"){if(l.path.endsWith(".json"))try{let u=JSON.parse(l.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(i,u.mcpServers);else if(l.path.includes("resources/")){let p=o.indexOf("resources"),m=p>0?o[p-1]:o[1];i[m]=u}}catch{t.push(`Failed to parse MCP config: ${l.path}`)}}else if(c==="hooks"){if(l.path.endsWith(".json")){let u=o.length>=3?o[1]:"unknown";try{a.push({name:u,config:JSON.parse(l.content)})}catch{t.push(`Failed to parse hook config: ${l.path}`)}}}else c==="skills"||c==="commands"||c==="files"?r.push({path:l.path.slice(c.length+1),content:l.content}):r.push(l)}if(a.length>0){let l=rn(a);r.push({path:"hooks.json",content:JSON.stringify(l,null,2)+`
32
+ `})}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,l=A(r,i),o=nn(e),c=(0,Se.join)(l,...o),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(h=>!h.path.includes("/")),m=s.mainFiles.filter(h=>h.path.includes("/"));p.length>0&&(v(c,p),u+=p.length),m.length>0&&(v(l,m),u+=m.length)}if(s.agentFiles.length>0){let p=F(r,i);v(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&sn(M(r,i),s.mcpEntries),{installDir:c,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r,s){let i=[],l=A(r,t==="project"),o=(0,Se.join)(l,e),c=!1;return(0,Y.existsSync)(o)&&((0,Y.rmSync)(o,{recursive:!0,force:!0}),c=!0),c||i.push(`Collection directory not found at ${o}`),{removed:c,warnings:i}}describeLocation(e,t,r){let s=A(r,t==="project");return(0,Se.join)(s,e)}};function rn(n){let e=[];for(let{config:t}of n)if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.hooks))e.push(...r.hooks);else for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a of i)e.push({event:s,...typeof a=="object"&&a?a:{}})}return{hooks:e}}function sn(n,e){let t={};if((0,Y.existsSync)(n))try{t=JSON.parse((0,Y.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,Y.mkdirSync)((0,Se.dirname)(n),{recursive:!0}),(0,Y.writeFileSync)(n,JSON.stringify(t,null,2)+`
33
+ `,"utf-8")}function nn(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 K=require("fs"),xe=require("path");var Rt={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},Me=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[];for(let l of e.files){let o=l.path.split("/"),c=o[0];if(c==="agents")s.push({path:l.path.slice(7),content:l.content});else if(c==="mcps"){if(l.path.endsWith(".json"))try{let u=JSON.parse(l.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(i,u.mcpServers);else if(l.path.includes("resources/")){let p=o.indexOf("resources"),m=p>0?o[p-1]:o[1];i[m]=u}}catch{t.push(`Failed to parse MCP config: ${l.path}`)}}else if(c==="hooks"){if(l.path.endsWith(".json")){let u=o.length>=3?o[1]:"unknown";try{a.push({name:u,config:JSON.parse(l.content)})}catch{t.push(`Failed to parse hook config: ${l.path}`)}}}else c==="skills"||c==="commands"||c==="files"?r.push({path:l.path.slice(c.length+1),content:l.content}):r.push(l)}if(a.length>0){let l=on(a);r.push({path:"hooks/hooks.json",content:JSON.stringify(l,null,2)+`
34
+ `})}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,l=A(r,i),o=ln(e),c=(0,xe.join)(l,...o),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(h=>!h.path.includes("/")),m=s.mainFiles.filter(h=>h.path.includes("/"));p.length>0&&(v(c,p),u+=p.length),m.length>0&&(v(l,m),u+=m.length)}if(s.agentFiles.length>0){let p=F(r,i);v(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&an(M(r,i),s.mcpEntries),{installDir:c,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=A(r,t==="project"),l=(0,xe.join)(a,e),o=!1;return(0,K.existsSync)(l)&&((0,K.rmSync)(l,{recursive:!0,force:!0}),o=!0),o||s.push(`Collection directory not found at ${l}`),{removed:o,warnings:s}}describeLocation(e,t,r){let s=A(r,t==="project");return(0,xe.join)(s,e)}};function on(n){let e=[];for(let{config:t}of n)if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.hooks)){for(let s of r.hooks)if(s&&typeof s=="object"){let i=s;typeof i.event=="string"&&Rt[i.event]?e.push({...i,event:Rt[i.event]}):e.push(s)}}else for(let[s,i]of Object.entries(r)){let a=Rt[s]||s;if(Array.isArray(i))for(let l of i)e.push({event:a,...typeof l=="object"&&l?l:{}})}}return{hooks:e}}function an(n,e){let t={};if((0,K.existsSync)(n))try{t=JSON.parse((0,K.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,K.mkdirSync)((0,xe.dirname)(n),{recursive:!0}),(0,K.writeFileSync)(n,JSON.stringify(t,null,2)+`
35
+ `,"utf-8")}function ln(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 R=require("fs"),se=require("path");var He=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[],l=e.resource.slug||e.resource.id;for(let o of e.files){let c=o.path.split("/"),u=c[0];if(u==="agents")s.push({path:o.path.slice(7),content:o.content});else if(u==="mcps"){if(o.path.endsWith(".json"))try{let p=JSON.parse(o.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(i,p.mcpServers);else if(o.path.includes("resources/")){let m=c.indexOf("resources"),h=m>0?c[m-1]:c[1];i[h]=p}}catch{t.push(`Failed to parse MCP config: ${o.path}`)}}else u==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${o.path})`):u==="skills"||u==="commands"||u==="files"?r.push({path:o.path.slice(u.length+1),content:o.content}):r.push(o)}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:a,warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=A(r,i),l=un(e),o=(0,se.join)(a,...l),c=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(m=>!m.path.includes("/")),p=s.mainFiles.filter(m=>m.path.includes("/"));u.length>0&&(v(o,u),c+=u.length),p.length>0&&(v(a,p),c+=p.length)}if(s.agentFiles.length>0){let u=F(r,i);v(u,s.agentFiles),c+=s.agentFiles.length}for(let u of s.customFiles)(0,R.mkdirSync)((0,se.dirname)(u.absolutePath),{recursive:!0}),(0,R.writeFileSync)(u.absolutePath,u.content,"utf-8"),c++;return Object.keys(s.mcpEntries).length>0&&cn(M(r,i),s.mcpEntries),{installDir:o,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=A(r,t==="project"),l=(0,se.join)(a,e),o=!1;(0,R.existsSync)(l)&&((0,R.rmSync)(l,{recursive:!0,force:!0}),o=!0);let c=(0,se.join)(homedir(),".cursor","rules");if((0,R.existsSync)(c))try{let u=(0,R.readdirSync)(c);for(let p of u)p.startsWith(`${e}-`)&&p.endsWith(".mdc")&&((0,R.unlinkSync)((0,se.join)(c,p)),o=!0)}catch{s.push("Could not clean up Cursor rules")}return o||s.push(`Collection not found for Cursor at ${l}`),{removed:o,warnings:s}}describeLocation(e,t,r){let s=A(r,t==="project");return(0,se.join)(s,e)}};function cn(n,e){let t={};if((0,R.existsSync)(n))try{t=JSON.parse((0,R.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,R.mkdirSync)((0,se.dirname)(n),{recursive:!0}),(0,R.writeFileSync)(n,JSON.stringify(t,null,2)+`
36
+ `,"utf-8")}function un(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 Ve=require("fs"),Le=require("path");var We=class{buildFiles(e){let t=[],r=[],s=[];for(let i of e.files){let l=i.path.split("/")[0];l==="agents"?s.push({path:i.path.slice(7),content:i.content}):l==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${i.path})`):l==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${i.path})`):l==="commands"?t.push(`Commands are not supported by Codex (skipped: ${i.path})`):l==="skills"||l==="files"?r.push({path:i.path.slice(l.length+1),content:i.content}):r.push(i)}return{mainFiles:r,agentFiles:s,mcpEntries:{},customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=A(r,i),l=pn(e),o=(0,Le.join)(a,...l),c=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(m=>!m.path.includes("/")),p=s.mainFiles.filter(m=>m.path.includes("/"));u.length>0&&(v(o,u),c+=u.length),p.length>0&&(v(a,p),c+=p.length)}if(s.agentFiles.length>0){let u=F(r,i);v(u,s.agentFiles),c+=s.agentFiles.length}return{installDir:o,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=A(r,t==="project"),l=(0,Le.join)(a,e),o=!1;return(0,Ve.existsSync)(l)&&((0,Ve.rmSync)(l,{recursive:!0,force:!0}),o=!0),o||s.push(`Collection directory not found at ${l}`),{removed:o,warnings:s}}describeLocation(e,t,r){let s=A(r,t==="project");return(0,Le.join)(s,e)}};function pn(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 z=require("fs"),Ce=require("path");var Ue=class{buildFiles(e){let t=[],r=[],s={};for(let i of e.files){let a=i.path.split("/"),l=a[0];if(l==="agents")r.push({path:i.path.slice(7),content:i.content});else if(l==="mcps"){if(i.path.endsWith(".json"))try{let o=JSON.parse(i.content);if(o.mcpServers&&typeof o.mcpServers=="object")Object.assign(s,o.mcpServers);else if(i.path.includes("resources/")){let c=a.indexOf("resources"),u=c>0?a[c-1]:a[1];s[u]=o}}catch{}}else l==="skills"||l==="commands"||l==="hooks"||l==="files"?t.push({path:i.path.slice(l.length+1),content:i.content}):t.push(i)}return{mainFiles:t,agentFiles:r,mcpEntries:s,customFiles:[],warnings:[]}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=A(r,i),l=dn(e),o=(0,Ce.join)(a,...l),c=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(m=>!m.path.includes("/")),p=s.mainFiles.filter(m=>m.path.includes("/"));u.length>0&&(v(o,u),c+=u.length),p.length>0&&(v(a,p),c+=p.length)}if(s.agentFiles.length>0){let u=F(r,i);v(u,s.agentFiles),c+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&mn(M(r,i),s.mcpEntries),{installDir:o,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let i=A(r,t==="project"),a=(0,Ce.join)(i,e),l=!1;return(0,z.existsSync)(a)&&((0,z.rmSync)(a,{recursive:!0,force:!0}),l=!0),{removed:l,warnings:[]}}describeLocation(e,t,r){let s=A(r,t==="project");return(0,Ce.join)(s,e)}};function mn(n,e){let t={};if((0,z.existsSync)(n))try{t=JSON.parse((0,z.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,z.mkdirSync)((0,Ce.dirname)(n),{recursive:!0}),(0,z.writeFileSync)(n,JSON.stringify(t,null,2)+`
37
+ `,"utf-8")}function dn(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 we(n){switch(n.id){case"claude-code":return new Ne;case"gemini-cli":case"antigravity":return new Me;case"cursor":return new He;case"codex":return new We;default:return new Ue}}var $r=`---
38
+ title: Resource Manager
39
+ description: Search, install, and manage AI resources from the Shared Context library
33
40
  ---
34
41
 
35
- # Skill Manager
42
+ # Resource Manager
36
43
 
37
- You have access to the Shared Context skill library \u2014 a curated collection of AI skills you can search, install, and manage via the CLI.
44
+ 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.
38
45
 
39
46
  ## IMPORTANT: Search Before Creating
40
47
 
41
- **Before creating any new skill, ALWAYS search this library first.** A proven, community-tested skill is better than one improvised from scratch.
48
+ **Before creating any new resource, ALWAYS search this library first.** A proven, community-tested resource is better than one improvised from scratch.
42
49
 
43
50
  Search when:
44
51
 
@@ -46,7 +53,7 @@ Search when:
46
53
  - A structured workflow or best-practice approach would be valuable
47
54
  - You want to **do something well** rather than improvise
48
55
 
49
- Do **not** search when you already have an installed skill that covers the task, or when the request is trivially simple.
56
+ Do **not** search when you already have an installed resource that covers the task, or when the request is trivially simple.
50
57
 
51
58
  ## Quick Reference
52
59
 
@@ -64,23 +71,31 @@ Do **not** search when you already have an installed skill that covers the task,
64
71
 
65
72
  ## How to Search Effectively
66
73
 
67
- Use specific, descriptive queries. If the first search returns no good matches, try alternative terms.
74
+ Use specific keywords. Separate multiple keywords with commas \u2014 the search returns results matching **all** terms.
68
75
 
69
76
  \`\`\`bash
70
- # Be specific
71
- npx shared-context-ai search "react component testing"
72
- npx shared-context-ai search "postgresql query optimization"
77
+ # Single keyword
78
+ npx shared-context-ai search "testing"
79
+ npx shared-context-ai search "deployment"
73
80
 
74
- # Try alternatives if needed
75
- npx shared-context-ai search "CI/CD pipeline" # no results?
76
- npx shared-context-ai search "deployment automation" # try broader terms
81
+ # Multiple keywords (comma-separated, AND logic)
82
+ npx shared-context-ai search "react,testing"
83
+ npx shared-context-ai search "CI/CD,pipeline,docker"
77
84
 
78
- # Filter by type or tag
85
+ # Filter by resource type
79
86
  npx shared-context-ai search "code review" --type skill
87
+ npx shared-context-ai search "linting" --type hook
88
+ npx shared-context-ai search "database" --type mcp
89
+ npx shared-context-ai search "onboarding" --type collection
90
+ npx shared-context-ai search "reviewer" --type agent
91
+
92
+ # Filter by tag
80
93
  npx shared-context-ai search "deployment" --tag devops
81
94
  \`\`\`
82
95
 
83
- **Flags:** \`--type <type>\` (skill or file), \`--tag <tag>\`, \`--limit <n>\` (default: 20)
96
+ **Flags:** \`--type <type>\` (skill, agent, hook, mcp, collection), \`--tag <tag>\`, \`--limit <n>\` (default: 20)
97
+
98
+ **Tip:** Use commas to combine keywords, not spaces. \`"react,testing"\` finds resources about both react AND testing. \`"react testing"\` searches for the exact phrase.
84
99
 
85
100
  **JSON output includes \`installPath\` and \`installCommand\`** \u2014 use \`installPath\` directly with \`preview\`, \`install\`, \`update\`, and \`uninstall\` commands. No need to construct paths manually.
86
101
 
@@ -90,34 +105,49 @@ After searching, **show the user what you found before installing**. Let them ch
90
105
 
91
106
  1. Run \`npx shared-context-ai search "query"\` and review the results
92
107
  2. Pick the 1-3 most relevant matches
93
- 3. Tell the user: the skill name, what it does, and install count (as a quality signal)
108
+ 3. Tell the user: the resource name, what it does, type, and install count (as a quality signal)
94
109
  4. Preview with \`npx shared-context-ai preview <installPath>\` to confirm it fits
95
110
  5. Ask the user if they'd like to install it
96
111
 
97
- If no skills match, say so and proceed with your best approach. Don't search repeatedly for the same thing.
112
+ If no resources match, say so and proceed with your best approach. Don't search repeatedly for the same thing.
98
113
 
99
- ## Install & Preview Paths
114
+ ## Install Paths by Resource Type
100
115
 
101
- The \`installPath\` field from search results is the canonical path to use with all commands:
116
+ The \`installPath\` from search results works with all commands:
102
117
 
103
118
  \`\`\`bash
104
- npx shared-context-ai preview skills/acme/api-testing
119
+ # Skills
105
120
  npx shared-context-ai install skills/acme/api-testing
106
- npx shared-context-ai update skills/acme/api-testing
107
- npx shared-context-ai uninstall skills/acme/api-testing
121
+
122
+ # Agents
123
+ npx shared-context-ai install agents/acme/code-reviewer
124
+
125
+ # Hooks
126
+ npx shared-context-ai install hooks/acme/pre-commit-lint
127
+
128
+ # MCPs
129
+ npx shared-context-ai install mcps/acme/postgres-mcp
130
+
131
+ # Collections (installs all member resources)
132
+ npx shared-context-ai install collections/acme/devops-bundle
108
133
  \`\`\`
109
134
 
110
135
  **Flags:** \`--project\` (project-scoped install), \`--agent <agent>\` (override agent detection)
111
136
 
112
- Skills install to your agent's skills directory (e.g., \`~/.claude/skills/acme/api-testing/\`) and are immediately available.
137
+ Resources install to your agent's directory and are immediately available:
138
+ - Skills \u2192 \`~/.claude/skills/{org}/{slug}/\`
139
+ - Agents \u2192 \`~/.claude/agents/{org}/{slug}/\`
140
+ - Hooks \u2192 aggregated into \`hooks.json\`
141
+ - MCPs \u2192 merged into \`.mcp.json\`
142
+ - Collections \u2192 all members installed to their respective locations
113
143
 
114
144
  ## Other Commands
115
145
 
116
146
  \`\`\`bash
117
- npx shared-context-ai list # List installed skills with install paths and update status
147
+ npx shared-context-ai list # List installed resources with paths and update status
118
148
  npx shared-context-ai check # Check for available updates
119
- npx shared-context-ai update # Update all installed skills
120
- npx shared-context-ai update skills/acme/api-testing # Update one skill by path
149
+ npx shared-context-ai update # Update all installed resources
150
+ npx shared-context-ai update skills/acme/api-testing # Update one resource by path
121
151
  npx shared-context-ai uninstall skills/acme/api-testing
122
152
  npx shared-context-ai status # Auth status, detected agents, install count
123
153
  \`\`\`
@@ -149,13 +179,26 @@ npx shared-context-ai status # Auth status, detected agents, install
149
179
  \`\`\`
150
180
 
151
181
  **Error codes:** \`NOT_FOUND\`, \`AUTH_MISSING\`, \`NO_AGENTS\`, \`SKILL_NOT_FOUND\`, \`WRITE_FAILED\`, \`API_ERROR\`, \`UNEXPECTED\`
152
- `;var Y="skill-manager",Mt="Skill Manager";function ar(n,e){let t=R(n,e),i=(0,le.join)(t,Y);return(0,ce.mkdirSync)(i,{recursive:!0}),(0,ce.writeFileSync)((0,le.join)(i,"SKILL.md"),Lt,"utf-8"),(0,le.join)(i,"SKILL.md")}function Rt(n){n.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").action(async(e,t)=>{let i={...e,...t.optsWithGlobals()};if(i.code){let{post:l}=await Promise.resolve().then(()=>(v(),Nt)),{saveAuth:a}=await Promise.resolve().then(()=>(E(),Dt)),c=await l("/api/cli/auth",{code:i.code});c.ok||(d()?g("init",c.error.code,c.error.message):f(`Auth failed: ${c.error.message}`),process.exit(1)),a({token:c.data.token,email:c.data.user.email,orgId:c.data.org.id,orgSlug:c.data.org.slug,orgName:c.data.org.name,createdAt:new Date().toISOString()}),d()||u(`Authenticated as ${c.data.user.email}`)}else y()||(d()?(g("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(f("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let r=L(i.agent);if(!r){let l=M();d()?g("init","NO_AGENTS",l):f(l),process.exit(1)}let s=P();if(s?.token){let l=(await import("os")).hostname(),a=await k("/api/cli/register-agent",{platform:r.platform,name:`CLI (${l})`});!a.ok&&!d()&&f(`Warning: Could not register agent connection: ${a.error.message}`)}let o=ar(r,!!i.project);if(N({resourceId:"skill-manager",slug:Y,installPath:`skills/${Y}`,title:Mt,sha:"",scope:i.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()}),s?.token)try{let l=`skills/shared-context/${Y}`,a=await A(`/api/cli/resource/${l}`);if(a.ok&&a.data.resource){let c=a.data.resource;c.latestSha&&await k("/api/cli/install",{resourceId:c.id,agentPlatform:r.platform,installedSha:c.latestSha}),N({resourceId:c.id,slug:c.slug||Y,installPath:`skills/shared-context/${c.slug||Y}`,title:c.title||Mt,sha:c.latestSha||"",scope:i.project?"project":"global",agent:r.id,installedAt:new Date().toISOString()})}}catch{}d()?w("init",{agent:r.id,skillManagerPath:o,authenticated:y()}):(u(""),u(`Shared Context initialized for ${r.label}`),u(`Skill Manager installed to: ${o}`),u(""),u("Quick reference:"),u(' shared-context-ai search "query" Search for skills'),u(" shared-context-ai install <installPath> Install a skill"),u(" shared-context-ai list List installed skills"),u(" shared-context-ai check Check for updates"),u(" shared-context-ai preview <installPath> Preview before installing"))})}var fi=require("http"),gi=require("crypto");E();v();E();async function _i(n){let e=await k("/api/cli/auth",{code:n});return e.ok?(Re({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()}),d()?w("login",{email:e.data.user.email,org:e.data.org.slug}):u(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(d()?g("login",e.error.code,e.error.message):f(`Login failed: ${e.error.message}`),!1)}async function br(){let n=(0,gi.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,fi.createServer)((i,r)=>{let s=new URL(i.url||"/","http://localhost"),o=s.searchParams.get("code"),l=s.searchParams.get("state");if(!o||l!==n){r.writeHead(400,{"Content-Type":"text/html"}),r.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}r.writeHead(200,{"Content-Type":"text/html"}),r.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),_i(o).then(e)});t.listen(0,"127.0.0.1",async()=>{let i=t.address();if(!i||typeof i=="string"){t.close(),e(!1);return}let r=i.port,o=`${D().apiBase||"https://sharedcontext.ai"}/cli/login?port=${r}&state=${n}`;d()||(u("Opening browser for authentication..."),u(`If the browser doesn't open, visit: ${o}`));try{let l=(await Promise.resolve().then(()=>(mi(),pi))).default;await l(o)}catch{d()||u(`Could not open browser. Please visit:
153
- ${o}`)}setTimeout(()=>{t.close(),d()||f("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function wi(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 _i(e.code):t=await br(),process.exit(t?0:1)})}v();var Sr={skill:"skills",file:"files"};function xi(n){let e=Sr[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 yi(n){n.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let i=new URLSearchParams({q:e});t.type&&i.set("type",t.type),t.tag&&i.set("tag",t.tag),t.limit&&i.set("limit",t.limit);let r=y()?`/api/cli/search?${i}`:`/api/public/search?${i}`,s=await A(r);s.ok||(d()?g("search",s.error.code,s.error.message):u(`Search failed: ${s.error.message}`),process.exit(1));let o=s.data.results;if(d()){let a=o.map(c=>{let h=xi(c);return{installPath:h,installCommand:`npx shared-context-ai install ${h}`,title:c.title,description:c.description,resourceType:c.resourceType,installCount:c.installCount,topicTags:c.topicTags}});w("search",{results:a,count:a.length});return}if(o.length===0){let a=t.type?`${t.type}s`:"results";u(`No ${a} found.`);return}u(`Found ${o.length} result${o.length===1?"":"s"}:
154
- `);let l=o.map(a=>[xi(a),a.title,`\u2193${a.installCount}`]);u(q(l)),u(`
155
- Install a skill: npx shared-context-ai install <installPath>`)})}var fe=require("fs"),U=require("path");v();E();var Er={skill:"skills",file:"files"};function dt(n,e){let t=(0,U.resolve)(n);for(let i of e){let r=(0,U.resolve)((0,U.join)(n,i.path));if(!r.startsWith(t+"/")&&r!==t)throw new Error(`Invalid file path: ${i.path}`);(0,fe.mkdirSync)((0,U.dirname)(r),{recursive:!0}),(0,fe.writeFileSync)(r,i.content,"utf-8")}}function kr(n){let e=n.resource.slug||n.resource.id,t=Er[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 vr(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 Ci(n){n.command("install <path>").description("Install a skill (e.g., skills/acme/api-testing)").action(async(e,t,i)=>{let r=i.optsWithGlobals(),s=L(r.agent);if(!s){let I=M();d()?g("install","NO_AGENTS",I):f(I),process.exit(1)}let o=y(),a=await A(`${o?"/api/cli/resource":"/api/public/resource"}/${e}`);a.ok||(d()?g("install",a.error.code,a.error.message):f(`Install failed: ${a.error.message}`),process.exit(1));let c=a.data,h=c.resource.slug||c.resource.id,p=kr(c),_=R(s,!!r.project),T=(0,U.join)(_,...vr(c));try{dt(T,c.files)}catch(I){d()?g("install","WRITE_FAILED",`Failed to write files: ${I}`):f(`Failed to write files: ${I}`),process.exit(1)}let x;if(o&&c.resource.latestSha){let I=await k("/api/cli/install",{resourceId:c.resource.id,agentPlatform:s.platform,installedSha:c.resource.latestSha});I.ok||(x=`Could not record install on server: ${I.error.message}`,d()||f(`Warning: ${x}`))}N({resourceId:c.resource.id,slug:h,installPath:p,title:c.resource.title,sha:c.resource.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()}),d()?w("install",{installPath:p,title:c.resource.title,path:T,files:c.files.length,...x&&{warning:x}}):(u(`Installed "${c.resource.title}" to ${T}`),u(` ${c.files.length} file${c.files.length===1?"":"s"} written`),o||(u(""),u("Tip: Sign up at sharedcontext.ai to track installations and get updates.")))})}v();E();function Ai(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 Oi(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if(y()){let e=await A("/api/cli/installed");e.ok||(d()?g("list",e.error.code,e.error.message):u(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(d()){let r=t.map(s=>({...s,installPath:Ai(s)}));w("list",{installations:r,count:r.length});return}if(t.length===0){u("No skills installed."),u("Use 'shared-context-ai search' to find skills to install.");return}u(`${t.length} skill${t.length===1?"":"s"} installed:
156
- `);let i=t.map(r=>[Ai(r),r.title,r.hasUpdate?"(update available)":"(current)"]);u(q(i))}else{let t=F().installations;if(d()){w("list",{installations:t,count:t.length});return}if(t.length===0){u("No skills installed locally.");return}u(`${t.length} skill${t.length===1?"":"s"} installed locally:
157
- `);let i=t.map(r=>[r.installPath||r.slug,r.title,`(${r.agent})`]);u(q(i)),u(`
158
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}v();function bi(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let i=y()?"/api/cli/resource":"/api/public/resource",r=await A(`${i}/${e}/preview`);r.ok||(d()?g("preview",r.error.code,r.error.message):f(`Preview failed: ${r.error.message}`),process.exit(1)),d()?w("preview",r.data):u(r.data.content)})}v();function Si(n){n.command("check").description("Check for skill updates").action(async()=>{y()||(d()?g("check","AUTH_MISSING","Login required to check for updates."):f("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await A("/api/cli/updates");e.ok||(d()?g("check",e.error.code,e.error.message):f(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:i}=e.data;if(d()){w("check",{updates:t,count:i});return}if(i===0){u("All skills are up to date.");return}u(`${i} update${i===1?"":"s"} available:
159
- `);let r=t.map(s=>{let o=s.slug||s.resourceId;return[s.storageType==="github"&&s.githubOwner?`skills/external/${s.githubOwner}/${o}`:s.orgSlug?`skills/${s.orgSlug}/${o}`:`skills/${o}`,s.title,`${s.installedSha.slice(0,7)} \u2192 ${s.latestSha.slice(0,7)}`]});u(q(r)),u(`
160
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var ki=require("path");v();E();function Ei(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 vi(n){n.command("update [path]").description("Update installed skills (all or by install path)").action(async(e,t,i)=>{let r=i.optsWithGlobals();y()||(d()?g("update","AUTH_MISSING","Login required to update skills."):f("Login required to update skills. Run 'shared-context-ai login'."),process.exit(1));let s=L(r.agent);if(!s){let c=M();d()?g("update","NO_AGENTS",c):f(c),process.exit(1)}let o=await A("/api/cli/updates");o.ok||(d()?g("update",o.error.code,o.error.message):f(`Failed to check updates: ${o.error.message}`),process.exit(1));let l=o.data.updates;if(e&&(l=l.filter(c=>Ei(c)===e||c.slug===e||c.resourceId===e),l.length===0)){d()?g("update","SKILL_NOT_FOUND",`No update available for "${e}".`):u(`No update available for "${e}".`);return}if(l.length===0){d()?w("update",{updated:[],count:0}):u("All skills are up to date.");return}let a=[];for(let c of l){let h=Ei(c),p=await A(`/api/cli/resource/${h}`);if(!p.ok){d()||f(` Failed to fetch ${h}: ${p.error.message}`);continue}let _=p.data,T=R(s,!!r.project),x=h.split("/").slice(1),I=(0,ki.join)(T,...x);dt(I,_.files),_.resource.latestSha&&await k("/api/cli/update",{resourceId:_.resource.id,installedSha:_.resource.latestSha}),N({resourceId:_.resource.id,slug:resourceSlug,installPath:h,title:_.resource.title,sha:_.resource.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()}),a.push({installPath:h,title:_.resource.title}),d()||u(` Updated ${h}`)}d()?w("update",{updated:a,count:a.length}):a.length>0&&u(`
161
- ${a.length} skill${a.length===1?"":"s"} updated.`)})}var z=require("fs"),pt=require("path");v();E();function Ti(n){n.command("uninstall <path>").description("Uninstall a skill by install path (e.g., skills/acme/api-testing)").action(async(e,t,i)=>{let r=i.optsWithGlobals(),s=L(r.agent);if(!s){let x=M();d()?g("uninstall","NO_AGENTS",x):f(x),process.exit(1)}let l=F().installations.find(x=>x.installPath===e||x.slug===e||x.resourceId===e),a=R(s,!!r.project),c=e.split("/"),p=["skills","files"].includes(c[0])?c.slice(1):c,_=(0,pt.join)(a,...p),T=(0,z.existsSync)(_);if(T&&(0,z.rmSync)(_,{recursive:!0,force:!0}),!T&&l?.slug){let x=(0,pt.join)(a,l.slug);(0,z.existsSync)(x)&&(0,z.rmSync)(x,{recursive:!0,force:!0})}if(y()&&l){let x=await k("/api/cli/uninstall",{resourceId:l.resourceId});!x.ok&&!d()&&f(`Warning: Could not record uninstall on server: ${x.error.message}`)}l&&We(l.resourceId,s.id),d()?w("uninstall",{path:e,removed:!0}):u(`Uninstalled "${e}"`)})}E();function $i(n){n.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=P(),t=D(),i=F(),r=qe(),s={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:r.map(o=>o.id),installedCount:i.installations.length};if(d()){w("status",s);return}u("Shared Context CLI Status"),u("\u2500".repeat(30)),e?.token?u(` Auth: ${e.email} (${e.orgSlug})`):u(" Auth: Not logged in"),u(` API: ${t.apiBase}`),r.length>0?u(` Agents: ${r.map(o=>o.label).join(", ")}`):u(" Agents: None detected"),u(` Skills: ${i.installations.length} installed`)})}E();v();function Ii(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=P();e.revoke&&y()&&await Ue("/api/cli/auth"),Ve(),d()?w("logout",{email:t?.email||null}):u("Logged out.")})}var Pi={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."},ge=class extends Error{constructor(t,i){super(i||Pi[t]);this.code=t;this.name="CliError"}get recovery(){return Pi[this.code]}};var b=new kt;b.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();$t(!!e.json,!!e.human)});Rt(b);wi(b);yi(b);Ci(b);Oi(b);bi(b);Si(b);vi(b);Ti(b);$i(b);Ii(b);process.on("uncaughtException",n=>{n instanceof ge?d()?g(process.argv[2]||"unknown",n.code,n.message):(f(`Error: ${n.message}`),f(n.recovery)):d()?g(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):f(`Error: ${n.message||n}`),process.exit(1)});b.parse();
182
+ `;var Ae="resource-manager",Pr="Resource Manager",jt="collections/shared-context/essentials";function hn(n,e){let t=A(n,e),r=(0,Be.join)(t,Ae);return(0,qe.mkdirSync)(r,{recursive:!0}),(0,qe.writeFileSync)((0,Be.join)(r,"SKILL.md"),$r,"utf-8"),(0,Be.join)(r,"SKILL.md")}var fn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Tr(n){n.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").action(async(e,t)=>{let r={...e,...t.optsWithGlobals()};if(r.code){let{post:o}=await Promise.resolve().then(()=>(W(),Or)),{saveAuth:c}=await Promise.resolve().then(()=>(B(),_r)),u=await o("/api/cli/auth",{code:r.code});u.ok||(g()?S("init",u.error.code,u.error.message):w(`Auth failed: ${u.error.message}`),process.exit(1)),c({token:u.data.token,email:u.data.user.email,orgId:u.data.org.id,orgSlug:u.data.org.slug,orgName:u.data.org.name,createdAt:new Date().toISOString()}),g()||d(`Authenticated as ${u.data.user.email}`)}else $()||(g()?(S("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(w("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s=oe(r.agent);if(!s){let o=ae();g()?S("init","NO_AGENTS",o):w(o),process.exit(1)}let i=X();if(i?.token){let o=(await import("os")).hostname(),c=await I("/api/cli/register-agent",{platform:s.platform,name:`CLI (${o})`});!c.ok&&!g()&&w(`Warning: Could not register agent connection: ${c.error.message}`)}let a=!1,l=[];if(i?.token)try{let o=await j(`/api/cli/resource/${jt}`);if(o.ok){let c=o.data,p=await we(s).install(c,r.project?"project":"user",s),m={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};if(J({resourceId:c.resource.id,slug:c.resource.slug||"essentials",installPath:jt,title:c.resource.title,sha:c.resource.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString(),pluginFormat:m[s.id]||"directory",memberCount:c.memberResources?.length}),c.resource.latestSha&&await I("/api/cli/install",{resourceId:c.resource.id,agentPlatform:s.platform,installedSha:c.resource.latestSha}).catch(()=>{}),c.memberResources)for(let h of c.memberResources){let y=h.slug||h.id,b=fn[h.resourceType]||h.resourceType+"s",f=h.orgSlug||c.resource.orgSlug,O=f?`${b}/${f}/${y}`:`${b}/${y}`;J({resourceId:h.id,slug:y,installPath:O,title:h.title,sha:h.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString(),collectionId:c.resource.id}),l.push(h.title),h.latestSha&&await I("/api/cli/install",{resourceId:h.id,agentPlatform:s.platform,installedSha:h.latestSha}).catch(()=>{})}if(a=!0,!g()&&p.warnings.length>0)for(let h of p.warnings)w(`Warning: ${h}`)}}catch{}if(!a&&(hn(s,!!r.project),J({resourceId:"resource-manager",slug:Ae,installPath:`skills/${Ae}`,title:Pr,sha:"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()}),i?.token))try{let o=`skills/shared-context/${Ae}`,c=await j(`/api/cli/resource/${o}`);if(c.ok&&c.data.resource){let u=c.data.resource;u.latestSha&&await I("/api/cli/install",{resourceId:u.id,agentPlatform:s.platform,installedSha:u.latestSha}),J({resourceId:u.id,slug:u.slug||Ae,installPath:`skills/shared-context/${u.slug||Ae}`,title:u.title||Pr,sha:u.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()})}}catch{}g()?_("init",{agent:s.id,collection:a?jt:void 0,resourceManagerOnly:!a,membersInstalled:a?l.length:void 0,authenticated:$()}):(d(""),a?(d(`Shared Context Essentials installed for ${s.label} (${l.length} resources)`),d(` ${l.join(", ")}`)):(d(`Shared Context initialized for ${s.label}`),d("Resource Manager installed")),d(""),d("Quick reference:"),d(' shared-context-ai search "query" Search for resources'),d(" shared-context-ai install <installPath> Install a resource"),d(" shared-context-ai list List installed resources"),d(" shared-context-ai check Check for updates"),d(" shared-context-ai preview <installPath> Preview before installing"))})}var as=require("http"),ls=require("crypto");B();W();B();async function cs(n){let e=await I("/api/cli/auth",{code:n});return e.ok?(vt({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()}),g()?_("login",{email:e.data.user.email,org:e.data.org.slug}):d(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(g()?S("login",e.error.code,e.error.message):w(`Login failed: ${e.error.message}`),!1)}async function In(){let n=(0,ls.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,as.createServer)((r,s)=>{let i=new URL(r.url||"/","http://localhost"),a=i.searchParams.get("code"),l=i.searchParams.get("state");if(!a||l!==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(),cs(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=`${ie().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${n}`;g()||(d("Opening browser for authentication..."),d(`If the browser doesn't open, visit: ${a}`));try{let l=(await Promise.resolve().then(()=>(os(),is))).default;await l(a)}catch{g()||d(`Could not open browser. Please visit:
183
+ ${a}`)}setTimeout(()=>{t.close(),g()||w("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function us(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 cs(e.code):t=await In(),process.exit(t?0:1)})}W();var Rn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ps(n){let e=Rn[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 ms(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=$()?`/api/cli/search?${r}`:`/api/public/search?${r}`,i=await j(s);i.ok||(g()?S("search",i.error.code,i.error.message):d(`Search failed: ${i.error.message}`),process.exit(1));let a=i.data.results;if(g()){let o=a.map(c=>{let u=ps(c);return{installPath:u,installCommand:`npx shared-context-ai install ${u}`,title:c.title,description:c.description,resourceType:c.resourceType,installCount:c.installCount,topicTags:c.topicTags}});_("search",{results:o,count:o.length});return}if(a.length===0){let o=t.type?`${t.type}s`:"results";d(`No ${o} found.`);return}d(`Found ${a.length} result${a.length===1?"":"s"}:
184
+ `);let l=a.map(o=>[ps(o),o.title,`\u2193${o.installCount}`]);d(me(l)),d(`
185
+ Install a skill: npx shared-context-ai install <installPath>`)})}W();B();function ds(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 hs(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if($()){let e=await j("/api/cli/installed");e.ok||(g()?S("list",e.error.code,e.error.message):d(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(g()){let s=t.map(i=>({...i,installPath:ds(i)}));_("list",{installations:s,count:s.length});return}if(t.length===0){d("No skills installed."),d("Use 'shared-context-ai search' to find skills to install.");return}d(`${t.length} skill${t.length===1?"":"s"} installed:
186
+ `);let r=t.map(s=>[ds(s),s.title,s.hasUpdate?"(update available)":"(current)"]);d(me(r))}else{let t=Q().installations;if(g()){_("list",{installations:t,count:t.length});return}if(t.length===0){d("No skills installed locally.");return}d(`${t.length} skill${t.length===1?"":"s"} installed locally:
187
+ `);let r=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);d(me(r)),d(`
188
+ Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}W();function fs(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let r=$()?"/api/cli/resource":"/api/public/resource",s=await j(`${r}/${e}/preview`);s.ok||(g()?S("preview",s.error.code,s.error.message):w(`Preview failed: ${s.error.message}`),process.exit(1)),g()?_("preview",s.data):d(s.data.content)})}W();function gs(n){n.command("check").description("Check for skill updates").action(async()=>{$()||(g()?S("check","AUTH_MISSING","Login required to check for updates."):w("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await j("/api/cli/updates");e.ok||(g()?S("check",e.error.code,e.error.message):w(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:r}=e.data;if(g()){_("check",{updates:t,count:r});return}if(r===0){d("All skills are up to date.");return}d(`${r} update${r===1?"":"s"} available:
189
+ `);let s=t.map(i=>{let a=i.slug||i.resourceId;return[i.storageType==="github"&&i.githubOwner?`skills/external/${i.githubOwner}/${a}`:i.orgSlug?`skills/${i.orgSlug}/${a}`:`skills/${a}`,i.title,`${i.installedSha.slice(0,7)} \u2192 ${i.latestSha.slice(0,7)}`]});d(me(s)),d(`
190
+ Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var tr=require("path");W();B();var jn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ys(n){let e=n.slug||n.resourceId,t=jn[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 bs(n){n.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,r)=>{let s=r.optsWithGlobals();$()||(g()?S("update","AUTH_MISSING","Login required to update resources."):w("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let i=oe(s.agent);if(!i){let c=ae();g()?S("update","NO_AGENTS",c):w(c),process.exit(1)}let a=await j("/api/cli/updates");a.ok||(g()?S("update",a.error.code,a.error.message):w(`Failed to check updates: ${a.error.message}`),process.exit(1));let l=a.data.updates;if(e&&(l=l.filter(c=>ys(c)===e||c.slug===e||c.resourceId===e),l.length===0)){g()?S("update","SKILL_NOT_FOUND",`No update available for "${e}".`):d(`No update available for "${e}".`);return}if(l.length===0){g()?_("update",{updated:[],count:0}):d("All resources are up to date.");return}let o=[];for(let c of l){let u=ys(c),p=await j(`/api/cli/resource/${u}`);if(!p.ok){g()||w(` Failed to fetch ${u}: ${p.error.message}`);continue}let m=p.data,h=u.split("/").slice(1);if(m.resource.resourceType==="agent"){let y=F(i,!!s.project),b=(0,tr.join)(y,...h);v(b,m.files)}else if(m.resource.resourceType==="mcp")It(i,!!s.project,m);else{let y=A(i,!!s.project),b=(0,tr.join)(y,...h);v(b,m.files)}m.resource.latestSha&&await I("/api/cli/update",{resourceId:m.resource.id,installedSha:m.resource.latestSha}),J({resourceId:m.resource.id,slug:m.resource.slug||m.resource.id,installPath:u,title:m.resource.title,sha:m.resource.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString()}),o.push({installPath:u,title:m.resource.title}),g()||d(` Updated ${u}`)}g()?_("update",{updated:o,count:o.length}):o.length>0&&d(`
191
+ ${o.length} resource${o.length===1?"":"s"} updated.`)})}var T=require("fs"),Oe=require("path");W();B();function ws(n){n.command("uninstall <path>").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),i=oe(s.agent);if(!i){let h=ae();g()?S("uninstall","NO_AGENTS",h):w(h),process.exit(1)}let l=Q().installations.find(h=>h.installPath===e||h.slug===e||h.resourceId===e),o=e.split("/"),u=["skills","files","commands","hooks","collections","agents","mcps"].includes(o[0])?o[0]:null,p=u?o.slice(1):o,m=!1;if(u==="collections"){let h=we(i),y=p[p.length-1],b=s.project?"project":"user",f=await h.uninstall(y,b,i,l?.resourceId);if(m=f.removed,!g())for(let O of f.warnings)w(`Warning: ${O}`);if(l){let E=Q().installations.filter(C=>C.collectionId===l.resourceId&&C.agent===i.id);for(let C of E){let ne=C.installPath.split("/"),D=ne[0],V=ne.slice(1);if(D==="agents"){let fe=F(i,!!s.project),te=(0,Oe.join)(fe,...V);(0,T.existsSync)(te)&&(0,T.rmSync)(te,{recursive:!0,force:!0})}else if(D==="mcps"){let fe=V[V.length-1],te=M(i,!!s.project);if((0,T.existsSync)(te))try{let ge=JSON.parse((0,T.readFileSync)(te,"utf-8"));if(typeof ge.mcpServers=="object"&&ge.mcpServers&&!Array.isArray(ge.mcpServers)){let st=ge.mcpServers;fe in st&&(delete st[fe],ge.mcpServers=st,(0,T.writeFileSync)(te,JSON.stringify(ge,null,2)+`
192
+ `,"utf-8"))}}catch{}}else{let fe=A(i,!!s.project),te=(0,Oe.join)(fe,...V);(0,T.existsSync)(te)&&(0,T.rmSync)(te,{recursive:!0,force:!0})}Fe(C.resourceId,i.id)}}}else if(u==="agents"){let h=F(i,!!s.project),y=(0,Oe.join)(h,...p);m=(0,T.existsSync)(y),m&&(0,T.rmSync)(y,{recursive:!0,force:!0})}else if(u==="mcps"){let h=p[p.length-1],y=M(i,!!s.project);if((0,T.existsSync)(y))try{let b=JSON.parse((0,T.readFileSync)(y,"utf-8"));if(typeof b.mcpServers=="object"&&b.mcpServers&&!Array.isArray(b.mcpServers)){let f=b.mcpServers;h in f&&(delete f[h],b.mcpServers=f,(0,T.writeFileSync)(y,JSON.stringify(b,null,2)+`
193
+ `,"utf-8"),m=!0)}}catch{}}else{let h=A(i,!!s.project),y=(0,Oe.join)(h,...p);if(m=(0,T.existsSync)(y),m&&(0,T.rmSync)(y,{recursive:!0,force:!0}),!m&&l?.slug){let b=(0,Oe.join)(h,l.slug);(0,T.existsSync)(b)&&(0,T.rmSync)(b,{recursive:!0,force:!0})}}if($()&&l){let h=await I("/api/cli/uninstall",{resourceId:l.resourceId});!h.ok&&!g()&&w(`Warning: Could not record uninstall on server: ${h.error.message}`)}l&&Fe(l.resourceId,i.id),g()?_("uninstall",{path:e,removed:!0}):d(`Uninstalled "${e}"`)})}B();function Ss(n){n.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=X(),t=ie(),r=Q(),s=Tt(),i={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(a=>a.id),installedCount:r.installations.length};if(g()){_("status",i);return}d("Shared Context CLI Status"),d("\u2500".repeat(30)),e?.token?d(` Auth: ${e.email} (${e.orgSlug})`):d(" Auth: Not logged in"),d(` API: ${t.apiBase}`),s.length>0?d(` Agents: ${s.map(a=>a.label).join(", ")}`):d(" Agents: None detected"),d(` Skills: ${r.installations.length} installed`)})}B();W();function xs(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=X();e.revoke&&$()&&await $t("/api/cli/auth"),kt(),g()?_("logout",{email:t?.email||null}):d("Logged out.")})}var tt=require("fs"),_s=require("path");W();var P=require("fs"),k=require("path"),Cs=require("crypto"),Fn=[{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}],Dn=new Set(["py","sh","js","ts","rb","go","rs","bash","zsh"]),Nn=new Set(["json","yaml","yml","toml","xml","csv","txt","env","ini","cfg"]);function Ze(n){let e={name:"",description:"",body:n};if(!n.startsWith(`---
194
+ `)&&!n.startsWith(`---\r
195
+ `))return e;let t=n.indexOf(`
196
+ ---`,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 i={},a={},l=new Set(["requires","tools"]),o={},c=r.split(`
197
+ `),u=null,p=!1;for(let m=0;m<c.length;m++){let h=c[m];if(u&&/^\s+-\s/.test(h)){let O=h.replace(/^\s+-\s/,"").trim();if(O){let E=ve(O);p?o[u].push(E):a[u].push(E)}continue}u=null,p=!1;let y=h.indexOf(":");if(y===-1)continue;let b=h.slice(0,y).trim(),f=h.slice(y+1).trim();if(!f&&b&&m+1<c.length&&/^\s+-\s/.test(c[m+1])){u=b,l.has(b)?(p=!0,o[b]=[]):(p=!1,a[b]=[]);continue}b==="name"||b==="title"?e.name=ve(f):b==="description"?e.description=ve(f):b==="skill_class"?e.skillClass=ve(f):b==="service"?e.service=ve(f):b&&f&&(i[b]=ve(f))}return o.requires?.length&&(e.requires=o.requires),o.tools?.length&&(e.tools=o.tools),Object.keys(i).length&&(e.fields=i),Object.keys(a).length&&(e.arrayFields=a),e}function ve(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 Mn(n){let{body:e}=Ze(n);return e.replace(/\r\n/g,`
198
+ `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Xe(n){let e=Mn(n);return`sha256:${(0,Cs.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Qe(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ke(n){try{return(0,P.statSync)(n).isDirectory()}catch{return!1}}function Hn(n){try{return(0,P.readdirSync)(n).filter(e=>!e.startsWith(".")&&ke((0,k.join)(n,e)))}catch{return[]}}function et(n){try{return(0,P.readdirSync)(n).filter(e=>!e.startsWith(".")&&!ke((0,k.join)(n,e)))}catch{return[]}}function Ln(n){let e=[],t=(0,k.join)(n,"scripts");if((0,P.existsSync)(t)&&ke(t))for(let s of et(t)){let i=(0,k.extname)(s).slice(1);Dn.has(i)&&e.push({category:"script",extension:i,filename:s,content:(0,P.readFileSync)((0,k.join)(t,s),"utf-8")})}let r=(0,k.join)(n,"resources");if((0,P.existsSync)(r)&&ke(r))for(let s of et(r)){let i=(0,k.extname)(s).slice(1);Nn.has(i)&&e.push({category:"resource",extension:i,filename:s,content:(0,P.readFileSync)((0,k.join)(r,s),"utf-8")})}return e}function As(n){let e=[],t=[],r,s=(0,k.join)(n,".claude-plugin","plugin.json");if((0,P.existsSync)(s))try{r=JSON.parse((0,P.readFileSync)(s,"utf-8")).name||void 0}catch{}for(let o of Fn){let c=(0,k.join)(n,o.folder);if(!(!(0,P.existsSync)(c)||!ke(c))){if(o.folder==="files"){for(let u of et(c)){if(!u.endsWith(".md"))continue;let p=(0,k.join)(c,u),m=(0,P.readFileSync)(p,"utf-8"),h=Ze(m),y=h.name||(0,k.basename)(u,".md"),b=`files/${(0,k.basename)(u,".md")}`;e.push({importPath:b,resourceType:"file",title:y,description:h.description||null,body:h.body,bodyHash:Xe(m),metadata:{},attachments:[]})}continue}for(let u of Hn(c)){let p=o.mainFile||`${u}.md`,m=(0,k.join)(c,u,p);if(!(0,P.existsSync)(m))continue;let h=(0,P.readFileSync)(m,"utf-8"),y=`${o.folder}/${u}`,b,f,O,E={},C=null;if(o.resourceType==="hook"||o.resourceType==="mcp"){try{let D=JSON.parse(h);b=D.name||Qe(u),f=D.description||null}catch{b=Qe(u),f=null}O=h}else C=Ze(h),b=C.name||Qe(u),f=C.description||null,O=C.body,C.skillClass&&(E.skillClass=C.skillClass),C.service&&(E.service=C.service),C.requires?.length&&(E.requires=C.requires),C.tools?.length&&(E.tools=C.tools),C.fields&&Object.keys(C.fields).length&&(E.fields=C.fields);o.folder==="commands"&&(E.fields||(E.fields={}),E.fields["user-invocable"]="true");let ne=o.canHaveChildren?Ln((0,k.join)(c,u)):[];e.push({importPath:y,resourceType:o.resourceType,title:b,description:f,body:O,bodyHash:Xe(h),metadata:E,attachments:ne}),o.resourceType==="collection"&&C?.arrayFields?.resources&&t.push({collectionImportPath:y,memberImportPaths:C.arrayFields.resources.map(D=>{let V=D.split("/");return V.length>=3?`${V[0]}/${V[V.length-1]}`:D})})}}}let i=(0,k.join)(n,".mcp.json");if((0,P.existsSync)(i))try{let o=JSON.parse((0,P.readFileSync)(i,"utf-8"));if(o.mcpServers&&typeof o.mcpServers=="object")for(let[c,u]of Object.entries(o.mcpServers)){let p=`mcps/${c}`;if(e.some(y=>y.importPath===p))continue;let m=Qe(c),h=JSON.stringify({name:m,description:`MCP server: ${c}`,mcpServers:{[c]:u}},null,2);e.push({importPath:p,resourceType:"mcp",title:m,description:`MCP server: ${c}`,body:h,bodyHash:Xe(h),metadata:{},attachments:[]})}}catch{}let a=(0,k.join)(n,"files");if((0,P.existsSync)(a)&&ke(a)&&!e.some(o=>o.resourceType==="file"))for(let o of et(a)){if(!o.endsWith(".md"))continue;let c=(0,k.join)(a,o),u=(0,P.readFileSync)(c,"utf-8"),p=Ze(u),m=p.name||(0,k.basename)(o,".md"),h=`files/${(0,k.basename)(o,".md")}`;e.some(y=>y.importPath===h)||e.push({importPath:h,resourceType:"file",title:m,description:p.description||null,body:p.body,bodyHash:Xe(u),metadata:{},attachments:[]})}return{resources:[...e.filter(o=>o.resourceType!=="collection"),...e.filter(o=>o.resourceType==="collection")],collectionMemberships:t,pluginName:r}}function Os(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(),i=t.github;if(i&&e&&(g()?S("import","INVALID_ARGS","Cannot use --github with a local path"):w("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!i&&!e&&(g()?S("import","INVALID_ARGS","Provide a local path or --github <url>"):w("Error: Provide a local path or --github <url>"),process.exit(1)),$()||(g()?S("import","AUTH_MISSING","Authentication required for import"):w("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),i){t.onConflict&&t.onConflict!=="auto"&&(g()?S("import","INVALID_ARGS","--on-conflict is not supported with --github"):w("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(g()?S("import","INVALID_ARGS","--dry-run is not supported with --github"):w("Error: --dry-run is not supported with --github"),process.exit(1));let y={url:i};t.resourceType&&(y.resourceType=t.resourceType),g()||d(`
199
+ Importing from GitHub: ${i}`);let b=await I("/api/cli/github-import",y);b.ok||(g()?S("import",b.error.code,b.error.message):w(`
200
+ Import failed: ${b.error.message}`),process.exit(1));let f=b.data;if(g()){_("import",f);return}d(""),d(` Source: ${f.source.owner}/${f.source.repo}`),d(` Type: ${f.resourceType}`),d(` Title: ${f.title}`),f.slug&&d(` Slug: ${f.slug}`),d(` URL: ${f.url}`),d(""),d("Import complete: 1 created");return}let a=(0,_s.resolve)(e);(!(0,tt.existsSync)(a)||!(0,tt.statSync)(a).isDirectory())&&(g()?S("import","INVALID_PATH",`Not a directory: ${a}`):w(`Error: Not a directory: ${a}`),process.exit(1));let l=As(a);if(l.resources.length===0){g()?_("import",{resources:[],message:"No resources found"}):d("No resources found in the specified directory.");return}if(!g()){let y=new Map;for(let f of l.resources)y.set(f.resourceType,(y.get(f.resourceType)||0)+1);let b=[...y.entries()].map(([f,O])=>`${O} ${f}${O===1?"":"s"}`).join(", ");d(`
201
+ Discovered ${l.resources.length} resources in ${e}:`),d(` ${b}`),l.pluginName&&d(` Plugin: ${l.pluginName}`)}let o=t.tags?t.tags.split(",").map(y=>y.trim()).filter(Boolean):void 0,c={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:o,resources:l.resources,collectionMemberships:l.collectionMemberships.length>0?l.collectionMemberships:void 0};!g()&&!t.dryRun?d(`
202
+ Executing import...`):g()||d(`
203
+ Dry run \u2014 previewing changes...`);let u=await I("/api/cli/import",c,12e4);u.ok||(g()?S("import",u.error.code,u.error.message):w(`
204
+ Import failed: ${u.error.message}`),process.exit(1));let p=u.data;if(g()){_("import",p);return}let m=[...p.created.map(y=>({...y,action:"created"})),...p.updated.map(y=>({...y,action:"updated"})),...p.installed.map(y=>({...y,action:"installed"})),...p.cloned.map(y=>({...y,action:"cloned"})),...p.skipped.map(y=>({...y,action:"skipped"})),...p.errors.map(y=>({...y,action:"error"}))];if(m.length>0){d("");let y=m.length,b=m.map((f,O)=>{let E=`[${String(O+1).padStart(String(y).length)}/${y}]`,C=(f.resourceType||"").padEnd(10),ne=(f.importPath.split("/").pop()||"").padEnd(24),D="";switch(f.action){case"created":D=`\u2713 created${f.slug?` (slug: ${f.slug})`:""}`;break;case"updated":D="\u2713 updated";break;case"installed":{let V=f.versionsBehind;D=`\u2713 installed${V?` (${V} versions behind)`:""}`;break}case"cloned":D=`\u2713 cloned${f.slug?` (slug: ${f.slug})`:""}`;break;case"skipped":D=`\u2713 skipped (${f.reason||"up to date"})`;break;case"error":D=`\u2717 error: ${f.error||"unknown"}`;break}return` ${E} ${C} ${ne} ${D}`});for(let f of b)d(f)}if(p.collections.length>0)for(let y of p.collections){let b=y.importPath.split("/").pop()||y.importPath;d(` collection ${b.padEnd(20)} \u2713 ${y.membersLinked} members linked${y.membersFailed>0?`, ${y.membersFailed} failed`:""}`)}d("");let h=[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?d(`Dry run complete: ${h.join(", ")}`):d(`Import complete: ${h.join(", ")}`),p.errors.length>0&&process.exit(1)})}var vs={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."},rt=class extends Error{constructor(t,r){super(r||vs[t]);this.code=t;this.name="CliError"}get recovery(){return vs[this.code]}};var H=new fr;H.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();br(!!e.json,!!e.human)});Tr(H);us(H);ms(H);Er(H);hs(H);fs(H);gs(H);bs(H);ws(H);Ss(H);xs(H);Os(H);process.on("uncaughtException",n=>{n instanceof rt?g()?S(process.argv[2]||"unknown",n.code,n.message):(w(`Error: ${n.message}`),w(n.recovery)):g()?S(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):w(`Error: ${n.message||n}`),process.exit(1)});H.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shared-context-ai",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "CLI for Shared Context - search, install, and manage AI skills",
5
5
  "bin": {
6
6
  "shared-context-ai": "dist/index.js"