shared-context-ai 0.1.11 → 0.1.13

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 +63 -55
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,41 +1,46 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Qs=Object.create;var bt=Object.defineProperty;var Zs=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.getPrototypeOf,rn=Object.prototype.hasOwnProperty;var X=(n,e)=>()=>(n&&(e=n(n=0)),e);var xe=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),St=(n,e)=>{for(var t in e)bt(n,t,{get:e[t],enumerable:!0})},sn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of en(e))!rn.call(n,s)&&s!==t&&bt(n,s,{get:()=>e[s],enumerable:!(r=Zs(e,s))||r.enumerable});return n};var q=(n,e,t)=>(t=n!=null?Qs(tn(n)):{},sn(e||!n||!n.__esModule?bt(t,"default",{value:n,enumerable:!0}):t,n));var Ne=xe(At=>{"use strict";var Ge=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}},wt=class extends Ge{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};At.CommanderError=Ge;At.InvalidArgumentError=wt});var Je=xe(Ct=>{"use strict";var{InvalidArgumentError:nn}=Ne(),xt=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new nn(`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 on(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Ct.Argument=xt;Ct.humanReadableArgName=on});var _t=xe(Ot=>{"use strict";var{humanReadableArgName:an}=Je(),kt=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=>an(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(u,d){return t.formatItem(u,r,d,t)}let a=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),s),""]));let l=t.visibleArguments(e).map(u=>i(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));l.length>0&&(a=a.concat([t.styleTitle("Arguments:"),...l,""]));let c=t.visibleOptions(e).map(u=>i(t.styleOptionTerm(t.optionTerm(u)),t.styleOptionDescription(t.optionDescription(u))));if(c.length>0&&(a=a.concat([t.styleTitle("Options:"),...c,""])),t.showGlobalOptions){let u=t.visibleGlobalOptions(e).map(d=>i(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));u.length>0&&(a=a.concat([t.styleTitle("Global Options:"),...u,""]))}let p=t.visibleCommands(e).map(u=>i(t.styleSubcommandTerm(t.subcommandTerm(u)),t.styleSubcommandDescription(t.subcommandDescription(u))));return p.length>0&&(a=a.concat([t.styleTitle("Commands:"),...p,""])),a.join(`
3
- `)}displayWidth(e){return yr(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 o=e.padEnd(t+e.length-s.displayWidth(e)),l=2,p=(this.helpWidth??80)-t-l-2,u;return p<this.minWidthToWrap||s.preformatted(r)?u=r:u=s.boxWrap(r,p).replace(/\n/g,`
4
- `+" ".repeat(t+l)),a+o+" ".repeat(l)+u.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 o=a.match(s);if(o===null){i.push("");return}let l=[o.shift()],c=this.displayWidth(l[0]);o.forEach(p=>{let u=this.displayWidth(p);if(c+u<=t){l.push(p),c+=u;return}i.push(l.join(""));let d=p.trimStart();l=[d],c=this.displayWidth(d)}),i.push(l.join(""))}),i.join(`
6
- `)}};function yr(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}Ot.Help=kt;Ot.stripColor=yr});var $t=xe(Pt=>{"use strict";var{InvalidArgumentError:cn}=Ne(),vt=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=ln(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 cn(`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?br(this.name().replace(/^no-/,"")):br(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Et=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 br(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ln(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],o=`option creation failed due to '${a}' in option flags '${n}'`;throw/^-[^-][^-]/.test(a)?new Error(`${o}
2
+ "use strict";var an=Object.create;var xt=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var ln=Object.getOwnPropertyNames;var un=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty;var re=(n,e)=>()=>(n&&(e=n(n=0)),e);var ve=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ot=(n,e)=>{for(var t in e)xt(n,t,{get:e[t],enumerable:!0})},dn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ln(e))!pn.call(n,s)&&s!==t&&xt(n,s,{get:()=>e[s],enumerable:!(r=cn(e,s))||r.enumerable});return n};var K=(n,e,t)=>(t=n!=null?an(un(n)):{},dn(e||!n||!n.__esModule?xt(t,"default",{value:n,enumerable:!0}):t,n));var Be=ve(vt=>{"use strict";var Xe=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}},_t=class extends Xe{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};vt.CommanderError=Xe;vt.InvalidArgumentError=_t});var Qe=ve(Et=>{"use strict";var{InvalidArgumentError:mn}=Be(),Pt=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 mn(`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 fn(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Et.Argument=Pt;Et.humanReadableArgName=fn});var jt=ve($t=>{"use strict";var{humanReadableArgName:hn}=Qe(),Rt=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),o=r.long&&e._findOption(r.long);!s&&!o?t.push(r):r.long&&!o?t.push(e.createOption(r.long,r.description)):r.short&&!s&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(o=>!o.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>hn(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),s=t.helpWidth??80;function o(p,d){return t.formatItem(p,r,d,t)}let a=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],i=t.commandDescription(e);i.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(i),s),""]));let c=t.visibleArguments(e).map(p=>o(t.styleArgumentTerm(t.argumentTerm(p)),t.styleArgumentDescription(t.argumentDescription(p))));c.length>0&&(a=a.concat([t.styleTitle("Arguments:"),...c,""]));let l=t.visibleOptions(e).map(p=>o(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));if(l.length>0&&(a=a.concat([t.styleTitle("Options:"),...l,""])),t.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(d=>o(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));p.length>0&&(a=a.concat([t.styleTitle("Global Options:"),...p,""]))}let u=t.visibleCommands(e).map(p=>o(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));return u.length>0&&(a=a.concat([t.styleTitle("Commands:"),...u,""])),a.join(`
3
+ `)}displayWidth(e){return kr(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,r,s){let a=" ".repeat(2);if(!r)return a+e;let i=e.padEnd(t+e.length-s.displayWidth(e)),c=2,u=(this.helpWidth??80)-t-c-2,p;return u<this.minWidthToWrap||s.preformatted(r)?p=r:p=s.boxWrap(r,u).replace(/\n/g,`
4
+ `+" ".repeat(t+c)),a+i+" ".repeat(c)+p.replace(/\n/g,`
5
+ ${a}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return r.forEach(a=>{let i=a.match(s);if(i===null){o.push("");return}let c=[i.shift()],l=this.displayWidth(c[0]);i.forEach(u=>{let p=this.displayWidth(u);if(l+p<=t){c.push(u),l+=p;return}o.push(c.join(""));let d=u.trimStart();c=[d],l=this.displayWidth(d)}),o.push(c.join(""))}),o.join(`
6
+ `)}};function kr(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}$t.Help=Rt;$t.stripColor=kr});var Dt=ve(Ft=>{"use strict";var{InvalidArgumentError:gn}=Be(),It=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=yn(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 gn(`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?xr(this.name().replace(/^no-/,"")):xr(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Tt=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function xr(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function yn(n){let e,t,r=/^-[^-]$/,s=/^--[^-]/,o=n.split(/[ |,]+/).concat("guard");if(r.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&r.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let a=o[0],i=`option creation failed due to '${a}' in option flags '${n}'`;throw/^-[^-][^-]/.test(a)?new Error(`${i}
7
7
  - a short flag is a single dash and a single character
8
8
  - either use a single dash and a single character (for a short flag)
9
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(a)?new Error(`${o}
10
- - too many short flags`):s.test(a)?new Error(`${o}
11
- - too many long flags`):new Error(`${o}
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}}Pt.Option=vt;Pt.DualOptions=Et});var wr=xe(Sr=>{"use strict";function un(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 pn(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 o=un(n,a),l=Math.max(n.length,a.length);(l-o)/l>i&&(o<s?(s=o,r=[a]):o===s&&r.push(a))}),r.sort((a,o)=>a.localeCompare(o)),t&&(r=r.map(a=>`--${a}`)),r.length>1?`
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(a)?new Error(`${i}
10
+ - too many short flags`):s.test(a)?new Error(`${i}
11
+ - too many long flags`):new Error(`${i}
12
+ - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${n}'.`);return{shortFlag:e,longFlag:t}}Ft.Option=It;Ft.DualOptions=Tt});var _r=ve(Or=>{"use strict";function bn(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let o=1;n[s-1]===e[r-1]?o=0:o=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+o),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function Sn(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(a=>a.slice(2)));let r=[],s=3,o=.4;return e.forEach(a=>{if(a.length<=1)return;let i=bn(n,a),c=Math.max(n.length,a.length);(c-i)/c>o&&(i<s?(s=i,r=[a]):i===s&&r.push(a))}),r.sort((a,i)=>a.localeCompare(i)),t&&(r=r.map(a=>`--${a}`)),r.length>1?`
13
13
  (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
14
- (Did you mean ${r[0]}?)`:""}Sr.suggestSimilar=pn});var kr=xe(Ft=>{"use strict";var mn=require("events").EventEmitter,Rt=require("child_process"),me=require("path"),Ye=require("fs"),k=require("process"),{Argument:dn,humanReadableArgName:hn}=Je(),{CommanderError:Tt}=Ne(),{Help:fn,stripColor:gn}=_t(),{Option:Ar,DualOptions:yn}=$t(),{suggestSimilar:xr}=wr(),It=class n extends mn{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=>k.stdout.write(t),writeErr:t=>k.stderr.write(t),outputError:(t,r)=>r(t),getOutHelpWidth:()=>k.stdout.isTTY?k.stdout.columns:void 0,getErrHelpWidth:()=>k.stderr.isTTY?k.stderr.columns:void 0,getOutHasColors:()=>jt()??(k.stdout.isTTY&&k.stdout.hasColors?.()),getErrHasColors:()=>jt()??(k.stderr.isTTY&&k.stderr.hasColors?.()),stripColor:t=>gn(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,o]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(a);return s&&(l.description(s),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,o&&l.arguments(o),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new n(e)}createHelp(){return Object.assign(new fn,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 dn(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 Tt(e,t,r)),k.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 Ar(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,o)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,a):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,o)};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 Ar)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 o=s;s=(l,c)=>{let p=o.exec(l);return p?p[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){k.versions?.electron&&(t.from="electron");let s=k.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=k.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":k.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(Ye.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
14
+ (Did you mean ${r[0]}?)`:""}Or.suggestSimilar=Sn});var Rr=ve(Wt=>{"use strict";var wn=require("events").EventEmitter,Nt=require("child_process"),he=require("path"),Ze=require("fs"),$=require("process"),{Argument:An,humanReadableArgName:Cn}=Qe(),{CommanderError:Mt}=Be(),{Help:kn,stripColor:xn}=jt(),{Option:vr,DualOptions:On}=Dt(),{suggestSimilar:Pr}=_r(),Lt=class n extends wn{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>$.stdout.write(t),writeErr:t=>$.stderr.write(t),outputError:(t,r)=>r(t),getOutHelpWidth:()=>$.stdout.isTTY?$.stdout.columns:void 0,getErrHelpWidth:()=>$.stderr.isTTY?$.stderr.columns:void 0,getOutHasColors:()=>Ht()??($.stdout.isTTY&&$.stdout.hasColors?.()),getErrHasColors:()=>Ht()??($.stderr.isTTY&&$.stderr.hasColors?.()),stripColor:t=>xn(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let s=t,o=r;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,a,i]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(a);return s&&(c.description(s),c._executableHandler=!0),o.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(o.noHelp||o.hidden),c._executableFile=o.executableFile||null,i&&c.arguments(i),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new n(e)}createHelp(){return Object.assign(new kn,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 An(e,t)}argument(e,t,r,s){let o=this.createArgument(e,t);return typeof r=="function"?o.default(s).argParser(r):o.default(r),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",a=this.createCommand(r);return a.helpOption(!1),s&&a.arguments(s),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
+ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new Mt(e,t,r)),$.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,o=r.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new vr(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(o){if(o.code==="commander.invalidArgument"){let a=`${s} ${o.message}`;this.error(a,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
17
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(o,a,i)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let c=this.getOptionValue(r);o!==null&&e.parseArg?o=this._callParseArg(e,o,c,a):o!==null&&e.variadic&&(o=e._concatValue(o,c)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(r,o,i)};return this.on("option:"+t,o=>{let a=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let a=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,a,"env")}),this}_optionEx(e,t,r,s,o){if(typeof t=="object"&&t instanceof vr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,r);if(a.makeOptionMandatory(!!e.mandatory),typeof s=="function")a.default(o).argParser(s);else if(s instanceof RegExp){let i=s;s=(c,l)=>{let u=i.exec(c);return u?u[0]:l},a.default(o).argParser(s)}else a.default(s);return this.addOption(a)}option(e,t,r,s){return this._optionEx({},e,t,r,s)}requiredOption(e,t,r,s){return this._optionEx({mandatory:!0},e,t,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){$.versions?.electron&&(t.from="electron");let s=$.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=$.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":$.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(Ze.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
19
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
- - ${s}`;throw new Error(i)}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(p,u){let d=me.resolve(p,u);if(Ye.existsSync(d))return d;if(s.includes(me.extname(u)))return;let b=s.find(g=>Ye.existsSync(`${d}${g}`));if(b)return`${d}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let p;try{p=Ye.realpathSync(this._scriptPath)}catch{p=this._scriptPath}o=me.resolve(me.dirname(p),o)}if(o){let p=i(o,a);if(!p&&!e._executableFile&&this._scriptPath){let u=me.basename(this._scriptPath,me.extname(this._scriptPath));u!==this._name&&(p=i(o,`${u}-${e._name}`))}a=p||a}r=s.includes(me.extname(a));let l;k.platform!=="win32"?r?(t.unshift(a),t=Cr(k.execArgv).concat(t),l=Rt.spawn(k.argv[0],t,{stdio:"inherit"})):l=Rt.spawn(a,t,{stdio:"inherit"}):(this._checkForMissingExecutable(a,o,e._name),t.unshift(a),t=Cr(k.execArgv).concat(t),l=Rt.spawn(k.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{k.on(u,()=>{l.killed===!1&&l.exitCode===null&&l.kill(u)})});let c=this._exitCallback;l.on("close",p=>{p=p??1,c?c(new Tt(p,"commander.executeSubCommandAsync","(close)")):k.exit(p)}),l.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(a,o,e._name);else if(p.code==="EACCES")throw new Error(`'${a}' not executable`);if(!c)k.exit(1);else{let u=new Tt(1,"commander.executeSubCommandAsync","(error)");u.nestedError=p,c(u)}}),this.runningCommand=l}_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 o=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;a=this._callParseArg(r,s,i,o)}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,o)=>e(r,o,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(l){return l.length>1&&l[0]==="-"}let o=null;for(;i.length;){let l=i.shift();if(l==="--"){s===r&&s.push(l),s.push(...i);break}if(o&&!a(l)){this.emit(`option:${o.name()}`,l);continue}if(o=null,a(l)){let c=this._findOption(l);if(c){if(c.required){let p=i.shift();p===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,p)}else if(c.optional){let p=null;i.length>0&&!a(i[0])&&(p=i.shift()),this.emit(`option:${c.name()}`,p)}else this.emit(`option:${c.name()}`);o=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),p=this._findOption(l.slice(0,c));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,l.slice(c+1));continue}}if(a(l)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(l)){t.push(l),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){r.push(l),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
21
+ - ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(u,p){let d=he.resolve(u,p);if(Ze.existsSync(d))return d;if(s.includes(he.extname(p)))return;let f=s.find(g=>Ze.existsSync(`${d}${g}`));if(f)return`${d}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,i=this._executableDir||"";if(this._scriptPath){let u;try{u=Ze.realpathSync(this._scriptPath)}catch{u=this._scriptPath}i=he.resolve(he.dirname(u),i)}if(i){let u=o(i,a);if(!u&&!e._executableFile&&this._scriptPath){let p=he.basename(this._scriptPath,he.extname(this._scriptPath));p!==this._name&&(u=o(i,`${p}-${e._name}`))}a=u||a}r=s.includes(he.extname(a));let c;$.platform!=="win32"?r?(t.unshift(a),t=Er($.execArgv).concat(t),c=Nt.spawn($.argv[0],t,{stdio:"inherit"})):c=Nt.spawn(a,t,{stdio:"inherit"}):(this._checkForMissingExecutable(a,i,e._name),t.unshift(a),t=Er($.execArgv).concat(t),c=Nt.spawn($.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{$.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new Mt(u,"commander.executeSubCommandAsync","(close)")):$.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(a,i,e._name);else if(u.code==="EACCES")throw new Error(`'${a}' not executable`);if(!l)$.exit(1);else{let p=new Mt(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),this.runningCommand=c}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,o)=>{let a=s;if(s!==null&&r.parseArg){let i=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;a=this._callParseArg(r,s,o,i)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let o=r.defaultValue;r.variadic?s<this.args.length?(o=this.args.slice(s),r.parseArg&&(o=o.reduce((a,i)=>e(r,i,a),r.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],r.parseArg&&(o=e(r,o,r.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(a=>{s.push({hookedCommand:o,callback:a})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{r=this._chainOrCall(r,()=>o.callback(o.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(o,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(o=>r.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],s=t,o=e.slice();function a(c){return c.length>1&&c[0]==="-"}let i=null;for(;o.length;){let c=o.shift();if(c==="--"){s===r&&s.push(c),s.push(...o);break}if(i&&!a(c)){this.emit(`option:${i.name()}`,c);continue}if(i=null,a(c)){let l=this._findOption(c);if(l){if(l.required){let u=o.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;o.length>0&&!a(o[0])&&(u=o.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);i=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),o.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(a(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(c)){t.push(c),o.length>0&&r.push(...o);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){r.push(c),o.length>0&&r.push(...o);break}}if(this._passThroughOptions){s.push(c),o.length>0&&s.push(...o);break}s.push(c)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
- `),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in k.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()}`,k.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new yn(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 o=a.attributeName(),l=this.getOptionValue(o),c=this.options.find(u=>u.negate&&o===u.attributeName()),p=this.options.find(u=>!u.negate&&o===u.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:p||a},s=a=>{let o=r(a),l=o.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${o.envVar}'`:`option '${o.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(o=>o.long).map(o=>o.long);s=s.concat(a),i=i.parent}while(i&&!i._enablePositionalOptions);t=xr(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=xr(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=>hn(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=me.basename(e,me.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=o=>this._outputConfiguration.writeErr(o),s=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(r=o=>this._outputConfiguration.writeOut(o),s=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:o=>(s||(o=this._outputConfiguration.stripColor(o)),r(o)),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(k.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 Cr(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 jt(){if(k.env.NO_COLOR||k.env.FORCE_COLOR==="0"||k.env.FORCE_COLOR==="false")return!1;if(k.env.FORCE_COLOR||k.env.CLICOLOR_FORCE!==void 0)return!0}Ft.Command=It;Ft.useColor=jt});var Er=xe(ee=>{"use strict";var{Argument:Or}=Je(),{Command:Dt}=kr(),{CommanderError:bn,InvalidArgumentError:_r}=Ne(),{Help:Sn}=_t(),{Option:vr}=$t();ee.program=new Dt;ee.createCommand=n=>new Dt(n);ee.createOption=(n,e)=>new vr(n,e);ee.createArgument=(n,e)=>new Or(n,e);ee.Command=Dt;ee.Option=vr;ee.Argument=Or;ee.Help=Sn;ee.CommanderError=bn;ee.InvalidArgumentError=_r;ee.InvalidOptionArgumentError=_r});var Lr={};St(Lr,{addToManifest:()=>ne,clearAuth:()=>Ht,getAuth:()=>ae,getConfig:()=>ge,getManifest:()=>K,getSyncState:()=>Qe,removeFromManifest:()=>Xe,saveAuth:()=>Mt,saveConfig:()=>Mr,saveManifest:()=>Lt,saveSyncState:()=>He,shouldSync:()=>Wt,updateConfig:()=>xn});function Me(){let n=process.env.SC_PROFILE;return n?(0,Ce.join)(jr,"profiles",n):jr}function Nt(){return(0,Ce.join)(Me(),"auth.json")}function Dr(){return(0,Ce.join)(Me(),"config.json")}function Nr(){return(0,Ce.join)(Me(),"manifest.json")}function wn(){(0,se.mkdirSync)(Me(),{recursive:!0})}function Ke(n,e){try{return(0,se.existsSync)(n)?JSON.parse((0,se.readFileSync)(n,"utf-8")):e}catch{return e}}function ze(n,e,t=!1){if(wn(),(0,se.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
- `,"utf-8"),t)try{(0,se.chmodSync)(n,384)}catch{}}function ae(){return Ke(Nt(),null)}function Mt(n){ze(Nt(),n,!0)}function Ht(){try{(0,se.writeFileSync)(Nt(),"{}","utf-8")}catch{}}function ge(){return Ke(Dr(),An)}function Mr(n){ze(Dr(),n)}function xn(n){let e=ge();Mr({...e,...n})}function K(){return Ke(Nr(),Cn)}function Lt(n){ze(Nr(),n)}function ne(n){let e=K(),t=e.installations.findIndex(r=>r.resourceId===n.resourceId&&r.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),Lt(e)}function Xe(n,e){let t=K();t.installations=t.installations.filter(r=>!(r.resourceId===n&&(!e||r.agent===e))),Lt(t)}function Hr(){return(0,Ce.join)(Me(),"last-sync.json")}function Qe(){return Ke(Hr(),null)}function He(n){ze(Hr(),n)}function Wt(n=kn){let e=Qe();return e?.lastSyncAt?Date.now()-new Date(e.lastSyncAt).getTime()>=n:!0}var se,Ce,Fr,jr,An,Cn,kn,Q=X(()=>{"use strict";se=require("fs"),Ce=require("path"),Fr=require("os"),jr=(0,Ce.join)((0,Fr.homedir)(),".config","shared-context");An={apiBase:"https://sharedcontext.ai"};Cn={installations:[]};kn=720*60*1e3});var Wr={};St(Wr,{del:()=>Ut,get:()=>H,isAuthenticated:()=>T,patch:()=>vn,post:()=>F});function On(){return ge().apiBase||"https://sharedcontext.ai"}function _n(){let n={"Content-Type":"application/json"},e=ae();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function T(){return!!ae()?.token}async function Ze(n,e,t,r){let s=`${On()}${e}`;try{let i={method:n,headers:_n(),body:t?JSON.stringify(t):void 0};r&&(i.signal=AbortSignal.timeout(r));let a=await fetch(s,i),o=a.headers.get("content-type")||"";if(!o.includes("application/json"))return a.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${o||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${a.status}`,message:a.statusText}};let l=await a.json();return a.ok?{ok:!0,data:l.data??l}:{ok:!1,error:{code:l?.error?.code||`HTTP_${a.status}`,message:l?.error?.message||l?.message||a.statusText}}}catch(i){return{ok:!1,error:{code:"NETWORK_ERROR",message:i instanceof Error?i.message:"Network request failed"}}}}function H(n){return Ze("GET",n)}function F(n,e,t){return Ze("POST",n,e,t)}function vn(n,e){return Ze("PATCH",n,e)}function Ut(n,e){return Ze("DELETE",n,e)}var z=X(()=>{"use strict";Q()});function Xn(){try{return Xt.default.statSync("/.dockerenv"),!0}catch{return!1}}function Qn(){try{return Xt.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Qt(){return zt===void 0&&(zt=Xn()||Qn()),zt}var Xt,zt,es=X(()=>{"use strict";Xt=q(require("fs"),1)});function _e(){return Zt===void 0&&(Zt=Zn()||Qt()),Zt}var ts,Zt,Zn,er=X(()=>{"use strict";ts=q(require("fs"),1);es();Zn=()=>{try{return ts.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var tr,ss,pt,rs,be,rr=X(()=>{"use strict";tr=q(require("process"),1),ss=q(require("os"),1),pt=q(require("fs"),1);er();rs=()=>{if(tr.default.platform!=="linux")return!1;if(ss.default.release().toLowerCase().includes("microsoft"))return!_e();try{if(pt.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!_e()}catch{}return pt.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||pt.default.existsSync("/run/WSL")?!_e():!1},be=tr.default.env.__IS_WSL_TEST__?rs:rs()});var sr,Ue,ei,ti,nr,ns=X(()=>{"use strict";sr=q(require("process"),1),Ue=q(require("fs/promises"),1);rr();rr();ei=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",r=!1;try{await Ue.default.access(t,Ue.constants.F_OK),r=!0}catch{}if(!r)return n;let s=await Ue.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}})(),ti=async()=>`${await ei()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,nr=async()=>be?ti():`${sr.default.env.SYSTEMROOT||sr.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Se(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 is=X(()=>{"use strict"});async function ir(){if(as.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await ri("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 os,as,cs,ri,ls=X(()=>{"use strict";os=require("util"),as=q(require("process"),1),cs=require("child_process"),ri=(0,os.promisify)(cs.execFile)});async function ms(n,{humanReadableOutput:e=!0,signal:t}={}){if(us.default.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await si("osascript",["-e",n,r],s);return i.trim()}var us,ps,or,si,ds=X(()=>{"use strict";us=q(require("process"),1),ps=require("util"),or=require("child_process"),si=(0,ps.promisify)(or.execFile)});async function ar(n){return ms(`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 hs=X(()=>{"use strict";ds()});async function lr(n=ni){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 cr(`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),o=i===-1?void 0:r.slice(0,i);return mt[r]??mt[a]??mt[o]??{name:r,id:r}}var fs,gs,ni,mt,Lo,cr,ys=X(()=>{"use strict";fs=require("util"),gs=require("child_process"),ni=(0,fs.promisify)(gs.execFile),mt={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"}},Lo=new Map(Object.entries(mt)),cr=class extends Error{}});async function ur(){if(dt.default.platform==="darwin"){let n=await ir();return{name:await ar(n),id:n}}if(dt.default.platform==="linux"){let{stdout:n}=await ii("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:oi(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(dt.default.platform==="win32")return lr();throw new Error("Only macOS, Linux, and Windows are supported")}var bs,dt,Ss,ii,oi,ws=X(()=>{"use strict";bs=require("util"),dt=q(require("process"),1),Ss=require("child_process");ls();hs();ys();ii=(0,bs.promisify)(Ss.execFile),oi=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var vs={};St(vs,{apps:()=>we,default:()=>pi,openApp:()=>ui});async function ci(){let n=await nr(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=dr.Buffer.from(e,"utf16le").toString("base64"),{stdout:r}=await ai(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 ks(n){if(typeof n=="string"||Array.isArray(n))return n;let{[xs]:e}=n;if(!e)throw new Error(`${xs} is not supported`);return e}function ft({[Fe]:n},{wsl:e}){if(e&&be)return ks(e);if(!n)throw new Error(`${Fe} is not supported`);return ks(n)}var mr,dr,hr,Os,_s,fr,ht,mi,ai,pr,As,Fe,xs,Cs,Ve,li,ui,we,pi,Es=X(()=>{"use strict";mr=q(require("process"),1),dr=require("buffer"),hr=q(require("path"),1),Os=require("url"),_s=require("util"),fr=q(require("child_process"),1),ht=q(require("fs/promises"),1);ns();is();ws();er();mi={},ai=(0,_s.promisify)(fr.default.execFile),pr=hr.default.dirname((0,Os.fileURLToPath)(mi.url)),As=hr.default.join(pr,"xdg-open"),{platform:Fe,arch:xs}=mr.default;Cs=async(n,e)=>{let t;for(let r of n)try{return await e(r)}catch(s){t=s}throw t},Ve=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return Cs(n.app,o=>Ve({...n,app:o}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return Cs(e,o=>Ve({...n,app:{name:o,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let o={"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"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},c=be?await ci():await ur();if(c.id in o){let p=o[c.id];return e==="browserPrivate"&&t.push(l[p]),Ve({...n,app:{name:we[p],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let r,s=[],i={};if(Fe==="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(Fe==="win32"||be&&!_e()&&!e){r=await nr(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),be||(i.windowsVerbatimArguments=!0);let o=["Start"];n.wait&&o.push("-Wait"),e?(o.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&o.push(`"${n.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),o.push("-ArgumentList",t.join(","))),n.target=dr.Buffer.from(o.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let o=!pr||pr==="/",l=!1;try{await ht.default.access(As,ht.constants.X_OK),l=!0}catch{}r=mr.default.versions.electron??(Fe==="android"||o||!l)?"xdg-open":As}t.length>0&&s.push(...t),n.wait||(i.stdio="ignore",i.detached=!0)}Fe==="darwin"&&t.length>0&&s.push("--args",...t),n.target&&s.push(n.target);let a=fr.default.spawn(r,s,i);return n.wait?new Promise((o,l)=>{a.once("error",l),a.once("close",c=>{if(!n.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}o(a)})}):(a.unref(),a)},li=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return Ve({...e,target:n})},ui=(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 Ve({...e,app:{name:n,arguments:t}})};we={};Se(we,"chrome",()=>ft({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"]}}));Se(we,"brave",()=>ft({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"]}}));Se(we,"firefox",()=>ft({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Se(we,"edge",()=>ft({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Se(we,"browser",()=>"browser");Se(we,"browserPrivate",()=>"browserPrivate");pi=li});var Pr=q(Er(),1),{program:ki,createCommand:Oi,createArgument:_i,createOption:vi,CommanderError:Ei,InvalidArgumentError:Pi,InvalidOptionArgumentError:$i,Command:$r,Argument:Ri,Option:Ti,Help:Ii}=Pr.default;var Rr=!1,Tr=!1;function Ir(n,e){Rr=n,Tr=e}function y(){return Rr?!0:Tr?!1:!process.stdout.isTTY}function O(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function x(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function h(n){console.log(n)}function w(n){console.error(n)}function re(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 ut=require("fs"),We=require("path"),Qr=require("os");Q();z();var Vt=require("fs"),Z=require("path"),ye=require("os"),ve=[{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 ce(n){if(n){let r=ve.find(i=>i.id===n);if(r)return r;let s=ve.find(i=>i.dir===`.${n}`||i.dir===n);return s||null}for(let r of ve)if(r.envVars.some(s=>process.env[s]))return r;let e=(0,ye.homedir)(),t=[];for(let r of ve)(0,Vt.existsSync)((0,Z.join)(e,r.dir))&&t.push(r);return t.length===1?t[0]:null}function Bt(){let n=[],e=(0,ye.homedir)();for(let t of ve)(t.envVars.some(r=>process.env[r])||(0,Vt.existsSync)((0,Z.join)(e,t.dir)))&&n.push(t);return n}function le(){let n=Bt();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 (${ve.map(e=>e.id).join(", ")})`}function _(n,e){return e?(0,Z.join)(process.cwd(),n.dir,n.skillsSubdir):(0,Z.join)((0,ye.homedir)(),n.dir,n.skillsSubdir)}function U(n,e){return e?(0,Z.join)(process.cwd(),n.dir,"agents"):(0,Z.join)((0,ye.homedir)(),n.dir,"agents")}function G(n,e){return e?(0,Z.join)(process.cwd(),".mcp.json"):n.id==="claude-code"?(0,Z.join)((0,ye.homedir)(),".claude.json"):n.id==="cursor"?(0,Z.join)((0,ye.homedir)(),".cursor","mcp.json"):(0,Z.join)(process.cwd(),".mcp.json")}function ie(n,e){return e?(0,Z.join)(process.cwd(),n.dir,"settings.json"):(0,Z.join)((0,ye.homedir)(),n.dir,"settings.json")}var L=require("fs"),ke=require("path");var pe=require("fs"),ue=require("path");z();Q();var Vr={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function $(n,e){let t=(0,ue.resolve)(n);for(let r of e){let s=(0,ue.resolve)((0,ue.join)(n,r.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${r.path}`);(0,pe.mkdirSync)((0,ue.dirname)(s),{recursive:!0}),(0,pe.writeFileSync)(s,r.content,"utf-8")}}function En(n){let e=n.resource.slug||n.resource.id,t=Vr[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 Ur(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 qt(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=G(n,e),a=t.resource.slug||t.resource.id,o={};if((0,pe.existsSync)(i))try{o=JSON.parse((0,pe.readFileSync)(i,"utf-8"))}catch{o={}}let l=typeof o.mcpServers=="object"&&o.mcpServers&&!Array.isArray(o.mcpServers)?o.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(l,s.mcpServers):l[a]=s,o.mcpServers=l,(0,pe.mkdirSync)((0,ue.dirname)(i),{recursive:!0}),(0,pe.writeFileSync)(i,JSON.stringify(o,null,2)+`
31
- `,"utf-8")}function Pn(n,e,t,r){let s=t.files.find(c=>c.path.endsWith(".json")&&!c.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let i=JSON.parse(s.content),a=ie(n,e),o={},l=i.hooks&&typeof i.hooks=="object"&&!Array.isArray(i.hooks)?i.hooks:i;for(let[c,p]of Object.entries(l))if(!(c==="name"||c==="description")&&Array.isArray(p)){o[c]||(o[c]=[]);for(let u of p)o[c].push(u)}if(Object.keys(o).length===0)throw new Error("Hook package does not contain any hook event handlers");return Gt(a,o,r),a}function Br(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=ce(s.agent);if(!i){let m=le();y()?x("install","NO_AGENTS",m):w(m),process.exit(1)}let a=T(),l=await H(`${a?"/api/cli/resource":"/api/public/resource"}/${e}`);l.ok||(y()?x("install",l.error.code,l.error.message):w(`Install failed: ${l.error.message}`),process.exit(1));let c=l.data,p=c.resource.slug||c.resource.id,u=En(c),d;if(c.resource.resourceType==="agent"){let m=U(i,!!s.project);d=(0,ue.join)(m,...Ur(c));try{$(d,c.files)}catch(A){y()?x("install","WRITE_FAILED",`Failed to write files: ${A}`):w(`Failed to write files: ${A}`),process.exit(1)}}else if(c.resource.resourceType==="mcp"){d="";try{qt(i,!!s.project,c)}catch(m){y()?x("install","WRITE_FAILED",`Failed to install MCP config: ${m}`):w(`Failed to install MCP config: ${m}`),process.exit(1)}}else if(c.resource.resourceType==="hook"){d="";try{Pn(i,!!s.project,c,u)}catch(m){y()?x("install","WRITE_FAILED",`Failed to install hook config: ${m}`):w(`Failed to install hook config: ${m}`),process.exit(1)}}else{let m=_(i,!!s.project);d=(0,ue.join)(m,...Ur(c));try{if(c.resource.resourceType==="collection"){let S=await Ee(i).install(c,s.project?"project":"user",i);if(d=S.installDir,!y())for(let C of S.warnings)w(`Warning: ${C}`)}else $(d,c.files)}catch(A){y()?x("install","WRITE_FAILED",`Failed to write files: ${A}`):w(`Failed to write files: ${A}`),process.exit(1)}}let b;if(a&&c.resource.latestSha){let m=await F("/api/cli/install",{resourceId:c.resource.id,agentPlatform:i.platform,installedSha:c.resource.latestSha});m.ok||(b=`Could not record install on server: ${m.error.message}`,y()||w(`Warning: ${b}`))}let g={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},f=c.resource.resourceType==="collection";if(ne({resourceId:c.resource.id,slug:p,installPath:u,title:c.resource.title,sha:c.resource.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString(),...f?{pluginFormat:g[i.id]||"directory",memberCount:c.memberResources?.length}:{}}),c.memberResources&&c.resource.resourceType==="collection")for(let m of c.memberResources){let A=m.slug||m.id,S=Vr[m.resourceType]||m.resourceType+"s",C=m.orgSlug||c.resource.orgSlug,N=C?`${S}/${C}/${A}`:`${S}/${A}`;ne({resourceId:m.id,slug:A,installPath:N,title:m.title,sha:m.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString(),collectionId:c.resource.id}),a&&m.latestSha&&await F("/api/cli/install",{resourceId:m.id,agentPlatform:i.platform,installedSha:m.latestSha}).catch(()=>{})}if(y())O("install",{installPath:u,title:c.resource.title,path:d||void 0,files:c.files.length,...c.resource.resourceType==="mcp"?{mcpConfigPath:G(i,!!s.project)}:{},...c.resource.resourceType==="hook"?{settingsPath:ie(i,!!s.project)}:{},...c.memberResources?{memberResources:c.memberResources.map(m=>({title:m.title,resourceType:m.resourceType,slug:m.slug}))}:{},...b&&{warning:b}});else{if(c.resource.resourceType==="mcp"?h(`Installed MCP "${c.resource.title}" to ${G(i,!!s.project)}`):c.resource.resourceType==="hook"?h(`Installed hook "${c.resource.title}" to ${ie(i,!!s.project)}`):c.memberResources&&c.memberResources.length>0?h(`Installed "${c.resource.title}" (${c.memberResources.length} resources)`):h(`Installed "${c.resource.title}" to ${d}`),c.resource.resourceType!=="mcp"&&c.resource.resourceType!=="hook"&&!(c.memberResources&&c.memberResources.length>0)&&h(` ${c.files.length} file${c.files.length===1?"":"s"} written`),c.memberResources&&c.memberResources.length>0){let m={};for(let S of c.memberResources){let C=S.resourceType||"other";m[C]||(m[C]=[]),m[C].push(S.title)}let A={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};h("");for(let[S,C]of Object.entries(m)){let N=A[S]||S;h(` ${N}: ${C.join(", ")}`)}}a||(h(""),h("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var et=class{buildFiles(e){let t=[],r=[],s=[],i={},a={};for(let o of e.files){let l=o.path.split("/"),c=l[0];if(c==="agents")s.push({path:o.path.slice(7),content:o.content});else if(c==="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 u=l.indexOf("resources"),d=u>0?l[u-1]:l[1];i[d]=p}}catch{t.push(`Failed to parse MCP config: ${o.path}`)}}else if(c==="hooks"){if(o.path.endsWith(".json"))try{let p=JSON.parse(o.content),u=o.path.replace(/\/[^/]+$/,"");$n(p,a,u)}catch{t.push(`Failed to parse hook config: ${o.path}`)}}else c==="skills"||c==="commands"||c==="files"?r.push({path:o.path.slice(c.length+1),content:o.content}):r.push(o)}return{mainFiles:r,agentFiles:s,mcpEntries:i,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,o=_(r,i),l=Tn(e),c=(0,ke.join)(o,...l),p=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(b=>!b.path.includes("/")),d=s.mainFiles.filter(b=>b.path.includes("/"));u.length>0&&($(c,u),p+=u.length),d.length>0&&($(o,d),p+=d.length)}if(s.agentFiles.length>0){let u=U(r,i);$(u,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Rn(G(r,i),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Gt(ie(r,i),s.hookEntries),{installDir:c,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,r,s){let i=[],o=_(r,t==="project"),l=(0,ke.join)(o,e),c=!1;return(0,L.existsSync)(l)&&((0,L.rmSync)(l,{recursive:!0,force:!0}),c=!0),c||i.push(`Collection directory not found at ${l}`),{removed:c,warnings:i}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,ke.join)(s,e)}};function $n(n,e,t){if(!n||typeof n!="object")return;let r=n,s=r.hooks&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)?r.hooks:r;for(let[i,a]of Object.entries(s))if(!(i==="name"||i==="description")&&Array.isArray(a)){e[i]||(e[i]=[]);for(let o of a){let l=t&&typeof o=="object"&&o!==null?{...o,_sc:t}:o;e[i].push(l)}}}function Gt(n,e,t){let r={};if((0,L.existsSync)(n))try{r=JSON.parse((0,L.readFileSync)(n,"utf-8"))}catch{r={}}let s=typeof r.hooks=="object"&&r.hooks&&!Array.isArray(r.hooks)?r.hooks:{};if(t)for(let[i,a]of Object.entries(s))Array.isArray(a)&&(s[i]=a.filter(o=>!o||typeof o!="object"||o._sc!==t),s[i].length===0&&delete s[i]);for(let[i,a]of Object.entries(e)){Array.isArray(s[i])||(s[i]=[]);for(let o of a){let l=t&&typeof o=="object"&&o!==null?{...o,_sc:t}:o,c=JSON.stringify(l);s[i].some(u=>JSON.stringify(u)===c)||s[i].push(l)}}r.hooks=s,(0,L.mkdirSync)((0,ke.dirname)(n),{recursive:!0}),(0,L.writeFileSync)(n,JSON.stringify(r,null,2)+`
32
- `,"utf-8")}function Jt(n,e){if(!(0,L.existsSync)(n))return!1;let t;try{t=JSON.parse((0,L.readFileSync)(n,"utf-8"))}catch{return!1}let r=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!r)return!1;let s=!1;for(let[i,a]of Object.entries(r)){if(!Array.isArray(a))continue;let o=a.filter(l=>!l||typeof l!="object"||l._sc!==e);o.length!==a.length&&(s=!0,o.length===0?delete r[i]:r[i]=o)}return s&&(t.hooks=r,(0,L.writeFileSync)(n,JSON.stringify(t,null,2)+`
33
- `,"utf-8")),s}function Rn(n,e){let t={};if((0,L.existsSync)(n))try{t=JSON.parse((0,L.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,L.mkdirSync)((0,ke.dirname)(n),{recursive:!0}),(0,L.writeFileSync)(n,JSON.stringify(t,null,2)+`
34
- `,"utf-8")}function Tn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var J=require("fs"),Oe=require("path");var In={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},tt=class{buildFiles(e){let t=[],r=[],s=[],i={},a={};for(let o of e.files){let l=o.path.split("/"),c=l[0];if(c==="agents")s.push({path:o.path.slice(7),content:o.content});else if(c==="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 u=l.indexOf("resources"),d=u>0?l[u-1]:l[1];i[d]=p}}catch{t.push(`Failed to parse MCP config: ${o.path}`)}}else if(c==="hooks"){if(o.path.endsWith(".json"))try{let p=JSON.parse(o.content);jn(p,a)}catch{t.push(`Failed to parse hook config: ${o.path}`)}}else c==="skills"||c==="commands"||c==="files"?r.push({path:o.path.slice(c.length+1),content:o.content}):r.push(o)}return{mainFiles:r,agentFiles:s,mcpEntries:i,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,o=_(r,i),l=Nn(e),c=(0,Oe.join)(o,...l),p=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(b=>!b.path.includes("/")),d=s.mainFiles.filter(b=>b.path.includes("/"));u.length>0&&($(c,u),p+=u.length),d.length>0&&($(o,d),p+=d.length)}if(s.agentFiles.length>0){let u=U(r,i);$(u,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Dn(G(r,i),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Fn(ie(r,i),s.hookEntries),{installDir:c,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=_(r,t==="project"),o=(0,Oe.join)(a,e),l=!1;return(0,J.existsSync)(o)&&((0,J.rmSync)(o,{recursive:!0,force:!0}),l=!0),l||s.push(`Collection directory not found at ${o}`),{removed:l,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,Oe.join)(s,e)}};function jn(n,e){if(!n||typeof n!="object")return;let t=n,r=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,i]of Object.entries(r)){if(s==="name"||s==="description"||!Array.isArray(i))continue;let a=In[s]||s;e[a]||(e[a]=[]);for(let o of i)e[a].push(o)}}function Fn(n,e){let t={};if((0,J.existsSync)(n))try{t=JSON.parse((0,J.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,i]of Object.entries(e)){Array.isArray(r[s])||(r[s]=[]);for(let a of i){let o=JSON.stringify(a);r[s].some(c=>JSON.stringify(c)===o)||r[s].push(a)}}t.hooks=r,(0,J.mkdirSync)((0,Oe.dirname)(n),{recursive:!0}),(0,J.writeFileSync)(n,JSON.stringify(t,null,2)+`
35
- `,"utf-8")}function Dn(n,e){let t={};if((0,J.existsSync)(n))try{t=JSON.parse((0,J.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,J.mkdirSync)((0,Oe.dirname)(n),{recursive:!0}),(0,J.writeFileSync)(n,JSON.stringify(t,null,2)+`
36
- `,"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 W=require("fs"),de=require("path");var rt=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[],o=e.resource.slug||e.resource.id;for(let l of e.files){let c=l.path.split("/"),p=c[0];if(p==="agents")s.push({path:l.path.slice(7),content:l.content});else if(p==="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 d=c.indexOf("resources"),b=d>0?c[d-1]:c[1];i[b]=u}}catch{t.push(`Failed to parse MCP config: ${l.path}`)}}else p==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${l.path})`):p==="skills"||p==="commands"||p==="files"?r.push({path:l.path.slice(p.length+1),content:l.content}):r.push(l)}return{mainFiles:r,agentFiles:s,mcpEntries:i,hookEntries:{},customFiles:a,warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=_(r,i),o=Hn(e),l=(0,de.join)(a,...o),c=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(d=>!d.path.includes("/")),u=s.mainFiles.filter(d=>d.path.includes("/"));p.length>0&&($(l,p),c+=p.length),u.length>0&&($(a,u),c+=u.length)}if(s.agentFiles.length>0){let p=U(r,i);$(p,s.agentFiles),c+=s.agentFiles.length}for(let p of s.customFiles)(0,W.mkdirSync)((0,de.dirname)(p.absolutePath),{recursive:!0}),(0,W.writeFileSync)(p.absolutePath,p.content,"utf-8"),c++;return Object.keys(s.mcpEntries).length>0&&Mn(G(r,i),s.mcpEntries),{installDir:l,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=_(r,t==="project"),o=(0,de.join)(a,e),l=!1;(0,W.existsSync)(o)&&((0,W.rmSync)(o,{recursive:!0,force:!0}),l=!0);let c=(0,de.join)(homedir(),".cursor","rules");if((0,W.existsSync)(c))try{let p=(0,W.readdirSync)(c);for(let u of p)u.startsWith(`${e}-`)&&u.endsWith(".mdc")&&((0,W.unlinkSync)((0,de.join)(c,u)),l=!0)}catch{s.push("Could not clean up Cursor rules")}return l||s.push(`Collection not found for Cursor at ${o}`),{removed:l,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,de.join)(s,e)}};function Mn(n,e){let t={};if((0,W.existsSync)(n))try{t=JSON.parse((0,W.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,W.mkdirSync)((0,de.dirname)(n),{recursive:!0}),(0,W.writeFileSync)(n,JSON.stringify(t,null,2)+`
37
- `,"utf-8")}function Hn(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 it=require("fs"),st=require("path");var nt=class{buildFiles(e){let t=[],r=[],s=[];for(let i of e.files){let o=i.path.split("/")[0];o==="agents"?s.push({path:i.path.slice(7),content:i.content}):o==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${i.path})`):o==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${i.path})`):o==="commands"?t.push(`Commands are not supported by Codex (skipped: ${i.path})`):o==="skills"||o==="files"?r.push({path:i.path.slice(o.length+1),content:i.content}):r.push(i)}return{mainFiles:r,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=_(r,i),o=Ln(e),l=(0,st.join)(a,...o),c=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(d=>!d.path.includes("/")),u=s.mainFiles.filter(d=>d.path.includes("/"));p.length>0&&($(l,p),c+=p.length),u.length>0&&($(a,u),c+=u.length)}if(s.agentFiles.length>0){let p=U(r,i);$(p,s.agentFiles),c+=s.agentFiles.length}return{installDir:l,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=_(r,t==="project"),o=(0,st.join)(a,e),l=!1;return(0,it.existsSync)(o)&&((0,it.rmSync)(o,{recursive:!0,force:!0}),l=!0),l||s.push(`Collection directory not found at ${o}`),{removed:l,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,st.join)(s,e)}};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 oe=require("fs"),Pe=require("path");var ot=class{buildFiles(e){let t=[],r=[],s={};for(let i of e.files){let a=i.path.split("/"),o=a[0];if(o==="agents")r.push({path:i.path.slice(7),content:i.content});else if(o==="mcps"){if(i.path.endsWith(".json"))try{let l=JSON.parse(i.content);if(l.mcpServers&&typeof l.mcpServers=="object")Object.assign(s,l.mcpServers);else if(i.path.includes("resources/")){let c=a.indexOf("resources"),p=c>0?a[c-1]:a[1];s[p]=l}}catch{}}else o==="skills"||o==="commands"||o==="hooks"||o==="files"?t.push({path:i.path.slice(o.length+1),content:i.content}):t.push(i)}return{mainFiles:t,agentFiles:r,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=_(r,i),o=Un(e),l=(0,Pe.join)(a,...o),c=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(d=>!d.path.includes("/")),u=s.mainFiles.filter(d=>d.path.includes("/"));p.length>0&&($(l,p),c+=p.length),u.length>0&&($(a,u),c+=u.length)}if(s.agentFiles.length>0){let p=U(r,i);$(p,s.agentFiles),c+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Wn(G(r,i),s.mcpEntries),{installDir:l,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let i=_(r,t==="project"),a=(0,Pe.join)(i,e),o=!1;return(0,oe.existsSync)(a)&&((0,oe.rmSync)(a,{recursive:!0,force:!0}),o=!0),{removed:o,warnings:[]}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,Pe.join)(s,e)}};function Wn(n,e){let t={};if((0,oe.existsSync)(n))try{t=JSON.parse((0,oe.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,oe.mkdirSync)((0,Pe.dirname)(n),{recursive:!0}),(0,oe.writeFileSync)(n,JSON.stringify(t,null,2)+`
38
- `,"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]}function Ee(n){switch(n.id){case"claude-code":return new et;case"gemini-cli":case"antigravity":return new tt;case"cursor":return new rt;case"codex":return new nt;default:return new ot}}var qr=`---
24
+ `),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,o=r.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in $.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,$.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new On(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=a=>{let i=a.attributeName(),c=this.getOptionValue(i),l=this.options.find(p=>p.negate&&i===p.attributeName()),u=this.options.find(p=>!p.negate&&i===p.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||a},s=a=>{let i=r(a),c=i.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${i.envVar}'`:`option '${i.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let a=o.createHelp().visibleOptions(o).filter(i=>i.long).map(i=>i.long);s=s.concat(a),o=o.parent}while(o&&!o._enablePositionalOptions);t=Pr(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=Pr(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>Cn(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=he.basename(e,he.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),r=this._getOutputContext(e);t.prepareContext({error:r.error,helpWidth:r.helpWidth,outputHasColors:r.hasColors});let s=t.formatHelp(this,t);return r.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,r,s,o;return t?(r=i=>this._outputConfiguration.writeErr(i),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(r=i=>this._outputConfiguration.writeOut(i),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:i=>(s||(i=this._outputConfiguration.stripColor(i)),r(i)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getOutputContext(e),s={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach(a=>a.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:r.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(a=>a.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number($.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let a;typeof t=="function"?a=t({error:o.error,command:o.command}):a=t,a&&o.write(`${a}
27
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Er(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:r=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],r=o[3],s=o[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}function Ht(){if($.env.NO_COLOR||$.env.FORCE_COLOR==="0"||$.env.FORCE_COLOR==="false")return!1;if($.env.FORCE_COLOR||$.env.CLICOLOR_FORCE!==void 0)return!0}Wt.Command=Lt;Wt.useColor=Ht});var Tr=ve(oe=>{"use strict";var{Argument:$r}=Qe(),{Command:Ut}=Rr(),{CommanderError:_n,InvalidArgumentError:jr}=Be(),{Help:vn}=jt(),{Option:Ir}=Dt();oe.program=new Ut;oe.createCommand=n=>new Ut(n);oe.createOption=(n,e)=>new Ir(n,e);oe.createArgument=(n,e)=>new $r(n,e);oe.Command=Ut;oe.Option=Ir;oe.Argument=$r;oe.Help=vn;oe.CommanderError=_n;oe.InvalidArgumentError=jr;oe.InvalidOptionArgumentError=jr});var Yt={};Ot(Yt,{addToManifest:()=>ee,clearAuth:()=>qt,getAuth:()=>ie,getConfig:()=>Se,getManifest:()=>Y,getSyncState:()=>st,removeFromManifest:()=>rt,saveAuth:()=>Bt,saveConfig:()=>Br,saveManifest:()=>Gt,saveSyncState:()=>Ie,shouldSync:()=>Jt,updateConfig:()=>Rn});function qe(){let n=process.env.SC_PROFILE;return n?(0,Pe.join)(Hr,"profiles",n):Hr}function Vt(){return(0,Pe.join)(qe(),"auth.json")}function Ur(){return(0,Pe.join)(qe(),"config.json")}function Vr(){return(0,Pe.join)(qe(),"manifest.json")}function Pn(){(0,ce.mkdirSync)(qe(),{recursive:!0})}function et(n,e){try{return(0,ce.existsSync)(n)?JSON.parse((0,ce.readFileSync)(n,"utf-8")):e}catch{return e}}function tt(n,e,t=!1){if(Pn(),(0,ce.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
+ `,"utf-8"),t)try{(0,ce.chmodSync)(n,384)}catch{}}function ie(){return et(Vt(),null)}function Bt(n){tt(Vt(),n,!0)}function qt(){try{(0,ce.writeFileSync)(Vt(),"{}","utf-8")}catch{}}function Se(){return et(Ur(),En)}function Br(n){tt(Ur(),n)}function Rn(n){let e=Se();Br({...e,...n})}function Y(){return et(Vr(),$n)}function Gt(n){tt(Vr(),n)}function ee(n){let e=Y(),t=e.installations.findIndex(r=>r.resourceId===n.resourceId&&r.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),Gt(e)}function rt(n,e){let t=Y();t.installations=t.installations.filter(r=>!(r.resourceId===n&&(!e||r.agent===e))),Gt(t)}function qr(){return(0,Pe.join)(qe(),"last-sync.json")}function st(){return et(qr(),null)}function Ie(n){tt(qr(),n)}function Jt(n=jn){let e=st();return e?.lastSyncAt?Date.now()-new Date(e.lastSyncAt).getTime()>=n:!0}var ce,Pe,Wr,Hr,En,$n,jn,te=re(()=>{"use strict";ce=require("fs"),Pe=require("path"),Wr=require("os"),Hr=(0,Pe.join)((0,Wr.homedir)(),".config","shared-context");En={apiBase:"https://sharedcontext.ai"};$n={installations:[]};jn=720*60*1e3});var Gr={};Ot(Gr,{del:()=>Kt,get:()=>L,isAuthenticated:()=>N,patch:()=>Fn,post:()=>j});function In(){return Se().apiBase||"https://sharedcontext.ai"}function Tn(){let n={"Content-Type":"application/json"},e=ie();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function N(){return!!ie()?.token}async function nt(n,e,t,r){let s=`${In()}${e}`;try{let o={method:n,headers:Tn(),body:t?JSON.stringify(t):void 0};r&&(o.signal=AbortSignal.timeout(r));let a=await fetch(s,o),i=a.headers.get("content-type")||"";if(!i.includes("application/json"))return a.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${i||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${a.status}`,message:a.statusText}};let c=await a.json();return a.ok?{ok:!0,data:c.data??c}:{ok:!1,error:{code:c?.error?.code||`HTTP_${a.status}`,message:c?.error?.message||c?.message||a.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function L(n){return nt("GET",n)}function j(n,e,t){return nt("POST",n,e,t)}function Fn(n,e){return nt("PATCH",n,e)}function Kt(n,e){return nt("DELETE",n,e)}var z=re(()=>{"use strict";te()});function uo(){try{return sr.default.statSync("/.dockerenv"),!0}catch{return!1}}function po(){try{return sr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function nr(){return rr===void 0&&(rr=uo()||po()),rr}var sr,rr,cs=re(()=>{"use strict";sr=K(require("fs"),1)});function je(){return or===void 0&&(or=mo()||nr()),or}var ls,or,mo,ir=re(()=>{"use strict";ls=K(require("fs"),1);cs();mo=()=>{try{return ls.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var ar,ps,yt,us,Ce,cr=re(()=>{"use strict";ar=K(require("process"),1),ps=K(require("os"),1),yt=K(require("fs"),1);ir();us=()=>{if(ar.default.platform!=="linux")return!1;if(ps.default.release().toLowerCase().includes("microsoft"))return!je();try{if(yt.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!je()}catch{}return yt.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||yt.default.existsSync("/run/WSL")?!je():!1},Ce=ar.default.env.__IS_WSL_TEST__?us:us()});var lr,Ye,fo,ho,ur,ds=re(()=>{"use strict";lr=K(require("process"),1),Ye=K(require("fs/promises"),1);cr();cr();fo=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",r=!1;try{await Ye.default.access(t,Ye.constants.F_OK),r=!0}catch{}if(!r)return n;let s=await Ye.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):n}})(),ho=async()=>`${await fo()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,ur=async()=>Ce?ho():`${lr.default.env.SYSTEMROOT||lr.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function ke(n,e,t){let r=s=>Object.defineProperty(n,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get(){let s=t();return r(s),s},set(s){r(s)}}),n}var ms=re(()=>{"use strict"});async function pr(){if(hs.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await go("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(n)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var fs,hs,gs,go,ys=re(()=>{"use strict";fs=require("util"),hs=K(require("process"),1),gs=require("child_process"),go=(0,fs.promisify)(gs.execFile)});async function ws(n,{humanReadableOutput:e=!0,signal:t}={}){if(bs.default.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await yo("osascript",["-e",n,r],s);return o.trim()}var bs,Ss,dr,yo,As=re(()=>{"use strict";bs=K(require("process"),1),Ss=require("util"),dr=require("child_process"),yo=(0,Ss.promisify)(dr.execFile)});async function mr(n){return ws(`tell application "Finder" to set app_path to application file id "${n}" as string
29
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Cs=re(()=>{"use strict";As()});async function hr(n=bo){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 fr(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,s=r.lastIndexOf("."),o=r.lastIndexOf("-"),a=s===-1?void 0:r.slice(0,s),i=o===-1?void 0:r.slice(0,o);return bt[r]??bt[a]??bt[i]??{name:r,id:r}}var ks,xs,bo,bt,ra,fr,Os=re(()=>{"use strict";ks=require("util"),xs=require("child_process"),bo=(0,ks.promisify)(xs.execFile),bt={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"}},ra=new Map(Object.entries(bt)),fr=class extends Error{}});async function gr(){if(St.default.platform==="darwin"){let n=await pr();return{name:await mr(n),id:n}}if(St.default.platform==="linux"){let{stdout:n}=await So("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:wo(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(St.default.platform==="win32")return hr();throw new Error("Only macOS, Linux, and Windows are supported")}var _s,St,vs,So,wo,Ps=re(()=>{"use strict";_s=require("util"),St=K(require("process"),1),vs=require("child_process");ys();Cs();Os();So=(0,_s.promisify)(vs.execFile),wo=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Fs={};Ot(Fs,{apps:()=>xe,default:()=>Oo,openApp:()=>xo});async function Co(){let n=await ur(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Sr.Buffer.from(e,"utf16le").toString("base64"),{stdout:r}=await Ao(n,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=r.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function js(n){if(typeof n=="string"||Array.isArray(n))return n;let{[Rs]:e}=n;if(!e)throw new Error(`${Rs} is not supported`);return e}function At({[Ue]:n},{wsl:e}){if(e&&Ce)return js(e);if(!n)throw new Error(`${Ue} is not supported`);return js(n)}var br,Sr,wr,Is,Ts,Ar,wt,_o,Ao,yr,Es,Ue,Rs,$s,Ke,ko,xo,xe,Oo,Ds=re(()=>{"use strict";br=K(require("process"),1),Sr=require("buffer"),wr=K(require("path"),1),Is=require("url"),Ts=require("util"),Ar=K(require("child_process"),1),wt=K(require("fs/promises"),1);ds();ms();Ps();ir();_o={},Ao=(0,Ts.promisify)(Ar.default.execFile),yr=wr.default.dirname((0,Is.fileURLToPath)(_o.url)),Es=wr.default.join(yr,"xdg-open"),{platform:Ue,arch:Rs}=br.default;$s=async(n,e)=>{let t;for(let r of n)try{return await e(r)}catch(s){t=s}throw t},Ke=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return $s(n.app,i=>Ke({...n,app:i}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return $s(e,i=>Ke({...n,app:{name:i,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let i={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},c={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=Ce?await Co():await gr();if(l.id in i){let u=i[l.id];return e==="browserPrivate"&&t.push(c[u]),Ke({...n,app:{name:xe[u],arguments:t}})}throw new Error(`${l.name} is not supported as a default browser`)}let r,s=[],o={};if(Ue==="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(Ue==="win32"||Ce&&!je()&&!e){r=await ur(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Ce||(o.windowsVerbatimArguments=!0);let i=["Start"];n.wait&&i.push("-Wait"),e?(i.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&i.push(`"${n.target}"`),t.length>0&&(t=t.map(c=>`"\`"${c}\`""`),i.push("-ArgumentList",t.join(","))),n.target=Sr.Buffer.from(i.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let i=!yr||yr==="/",c=!1;try{await wt.default.access(Es,wt.constants.X_OK),c=!0}catch{}r=br.default.versions.electron??(Ue==="android"||i||!c)?"xdg-open":Es}t.length>0&&s.push(...t),n.wait||(o.stdio="ignore",o.detached=!0)}Ue==="darwin"&&t.length>0&&s.push("--args",...t),n.target&&s.push(n.target);let a=Ar.default.spawn(r,s,o);return n.wait?new Promise((i,c)=>{a.once("error",c),a.once("close",l=>{if(!n.allowNonzeroExitCode&&l>0){c(new Error(`Exited with code ${l}`));return}i(a)})}):(a.unref(),a)},ko=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return Ke({...e,target:n})},xo=(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 Ke({...e,app:{name:n,arguments:t}})};xe={};ke(xe,"chrome",()=>At({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"]}}));ke(xe,"brave",()=>At({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"]}}));ke(xe,"firefox",()=>At({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));ke(xe,"edge",()=>At({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));ke(xe,"browser",()=>"browser");ke(xe,"browserPrivate",()=>"browserPrivate");Oo=ko});var Fr=K(Tr(),1),{program:Mo,createCommand:Lo,createArgument:Ho,createOption:Wo,CommanderError:Uo,InvalidArgumentError:Vo,InvalidOptionArgumentError:Bo,Command:Dr,Argument:qo,Option:Go,Help:Jo}=Fr.default;var Nr=!1,Mr=!1;function Lr(n,e){Nr=n,Mr=e}function w(){return Nr?!0:Mr?!1:!process.stdout.isTTY}function E(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function _(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function m(n){console.log(n)}function x(n){console.error(n)}function se(n,e=2){if(n.length===0)return"";let t=[];for(let r of n)for(let s=0;s<r.length;s++)t[s]=Math.max(t[s]||0,r[s].length);return n.map(r=>r.map((s,o)=>o<r.length-1?s.padEnd(t[o]+e):s).join("")).join(`
30
+ `)}var gt=require("fs"),Je=require("path"),is=require("os");te();z();var zt=require("fs"),ne=require("path"),we=require("os"),Te=[{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 ue(n){if(n){let r=Te.find(o=>o.id===n);if(r)return r;let s=Te.find(o=>o.dir===`.${n}`||o.dir===n);return s||null}for(let r of Te)if(r.envVars.some(s=>process.env[s]))return r;let e=(0,we.homedir)(),t=[];for(let r of Te)(0,zt.existsSync)((0,ne.join)(e,r.dir))&&t.push(r);return t.length===1?t[0]:null}function Fe(){let n=[],e=(0,we.homedir)();for(let t of Te)(t.envVars.some(r=>process.env[r])||(0,zt.existsSync)((0,ne.join)(e,t.dir)))&&n.push(t);return n}function pe(){let n=Fe();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 (${Te.map(e=>e.id).join(", ")})`}function T(n,e){return e?(0,ne.join)(process.cwd(),n.dir,n.skillsSubdir):(0,ne.join)((0,we.homedir)(),n.dir,n.skillsSubdir)}function G(n,e){return e?(0,ne.join)(process.cwd(),n.dir,"agents"):(0,ne.join)((0,we.homedir)(),n.dir,"agents")}function V(n,e){return e?(0,ne.join)(process.cwd(),".mcp.json"):n.id==="claude-code"?(0,ne.join)((0,we.homedir)(),".claude.json"):n.id==="cursor"?(0,ne.join)((0,we.homedir)(),".cursor","mcp.json"):(0,ne.join)(process.cwd(),".mcp.json")}function X(n,e){return e?(0,ne.join)(process.cwd(),n.dir,"settings.json"):(0,ne.join)((0,we.homedir)(),n.dir,"settings.json")}var B=require("fs"),Ee=require("path");var me=require("fs"),de=require("path");z();te();var Ae=require("fs"),ot=require("path"),Jr=".shared-context",Yr="project.json";function De(){let n=(0,ot.join)(process.cwd(),Jr,Yr);if(!(0,Ae.existsSync)(n))return null;try{let e=JSON.parse((0,Ae.readFileSync)(n,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function Kr(n){let e=(0,ot.join)(process.cwd(),Jr);(0,Ae.mkdirSync)(e,{recursive:!0}),(0,Ae.writeFileSync)((0,ot.join)(e,Yr),JSON.stringify(n,null,2)+`
31
+ `,"utf-8")}var Xr={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function M(n,e){let t=(0,de.resolve)(n);for(let r of e){let s=(0,de.resolve)((0,de.join)(n,r.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${r.path}`);(0,me.mkdirSync)((0,de.dirname)(s),{recursive:!0}),(0,me.writeFileSync)(s,r.content,"utf-8")}}function Dn(n){let e=n.resource.slug||n.resource.id,t=Xr[n.resource.resourceType]||n.resource.resourceType+"s";return n.resource.storageType==="github"&&n.resource.githubOwner?`${t}/external/${n.resource.githubOwner}/${e}`:n.resource.orgSlug?`${t}/${n.resource.orgSlug}/${e}`:`${t}/${e}`}function zr(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function Xt(n,e,t){let r=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"))||t.files.find(l=>l.path.endsWith(".json")&&l.path.includes("resources/"));if(!r)throw new Error("MCP package does not contain a config file");let s=JSON.parse(r.content),o=V(n,e),a=t.resource.slug||t.resource.id,i={};if((0,me.existsSync)(o))try{i=JSON.parse((0,me.readFileSync)(o,"utf-8"))}catch{i={}}let c=typeof i.mcpServers=="object"&&i.mcpServers&&!Array.isArray(i.mcpServers)?i.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(c,s.mcpServers):c[a]=s,i.mcpServers=c,(0,me.mkdirSync)((0,de.dirname)(o),{recursive:!0}),(0,me.writeFileSync)(o,JSON.stringify(i,null,2)+`
32
+ `,"utf-8")}function Nn(n,e,t,r){let s=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),a=X(n,e),i={},c=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:o;for(let[l,u]of Object.entries(c))if(!(l==="name"||l==="description")&&Array.isArray(u)){i[l]||(i[l]=[]);for(let p of u)i[l].push(p)}if(Object.keys(i).length===0)throw new Error("Hook package does not contain any hook event handlers");return Qt(a,i,r),a}function Qr(n){n.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),o=ue(s.agent);if(!o){let y=pe();w()?_("install","NO_AGENTS",y):x(y),process.exit(1)}let a=N(),c=await L(`${a?"/api/cli/resource":"/api/public/resource"}/${e}`);c.ok||(w()?_("install",c.error.code,c.error.message):x(`Install failed: ${c.error.message}`),process.exit(1));let l=c.data,u=l.resource.slug||l.resource.id,p=Dn(l),d;if(l.resource.resourceType==="agent"){let y=G(o,!!s.project);d=(0,de.join)(y,...zr(l));try{M(d,l.files)}catch(S){w()?_("install","WRITE_FAILED",`Failed to write files: ${S}`):x(`Failed to write files: ${S}`),process.exit(1)}}else if(l.resource.resourceType==="mcp"){d="";try{Xt(o,!!s.project,l)}catch(y){w()?_("install","WRITE_FAILED",`Failed to install MCP config: ${y}`):x(`Failed to install MCP config: ${y}`),process.exit(1)}}else if(l.resource.resourceType==="hook"){d="";try{Nn(o,!!s.project,l,p)}catch(y){w()?_("install","WRITE_FAILED",`Failed to install hook config: ${y}`):x(`Failed to install hook config: ${y}`),process.exit(1)}}else{let y=T(o,!!s.project);d=(0,de.join)(y,...zr(l));try{if(l.resource.resourceType==="collection"){let k=await ge(o).install(l,s.project?"project":"user",o);if(d=k.installDir,!w())for(let C of k.warnings)x(`Warning: ${C}`)}else M(d,l.files)}catch(S){w()?_("install","WRITE_FAILED",`Failed to write files: ${S}`):x(`Failed to write files: ${S}`),process.exit(1)}}let f;if(a&&l.resource.latestSha){let y=await j("/api/cli/install",{resourceId:l.resource.id,agentPlatform:o.platform,installedSha:l.resource.latestSha});y.ok||(f=`Could not record install on server: ${y.error.message}`,w()||x(`Warning: ${f}`))}let g=s.project?De():null;g&&a&&await j(`/api/cli/projects/${g.projectId}/resources`,{resourceId:l.resource.id}).catch(()=>{});let h={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},b=l.resource.resourceType==="collection";if(ee({resourceId:l.resource.id,slug:u,installPath:p,title:l.resource.title,sha:l.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),...b?{pluginFormat:h[o.id]||"directory",memberCount:l.memberResources?.length}:{},...g?{projectId:g.projectId}:{}}),l.memberResources&&l.resource.resourceType==="collection")for(let y of l.memberResources){let S=y.slug||y.id,k=Xr[y.resourceType]||y.resourceType+"s",C=y.orgSlug||l.resource.orgSlug,A=C?`${k}/${C}/${S}`:`${k}/${S}`;ee({resourceId:y.id,slug:S,installPath:A,title:y.title,sha:y.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:l.resource.id}),a&&y.latestSha&&await j("/api/cli/install",{resourceId:y.id,agentPlatform:o.platform,installedSha:y.latestSha}).catch(()=>{})}if(w())E("install",{installPath:p,title:l.resource.title,path:d||void 0,files:l.files.length,...l.resource.resourceType==="mcp"?{mcpConfigPath:V(o,!!s.project)}:{},...l.resource.resourceType==="hook"?{settingsPath:X(o,!!s.project)}:{},...l.memberResources?{memberResources:l.memberResources.map(y=>({title:y.title,resourceType:y.resourceType,slug:y.slug}))}:{},...f&&{warning:f}});else{if(l.resource.resourceType==="mcp"?m(`Installed MCP "${l.resource.title}" to ${V(o,!!s.project)}`):l.resource.resourceType==="hook"?m(`Installed hook "${l.resource.title}" to ${X(o,!!s.project)}`):l.memberResources&&l.memberResources.length>0?m(`Installed "${l.resource.title}" (${l.memberResources.length} resources)`):m(`Installed "${l.resource.title}" to ${d}`),l.resource.resourceType!=="mcp"&&l.resource.resourceType!=="hook"&&!(l.memberResources&&l.memberResources.length>0)&&m(` ${l.files.length} file${l.files.length===1?"":"s"} written`),l.memberResources&&l.memberResources.length>0){let y={};for(let k of l.memberResources){let C=k.resourceType||"other";y[C]||(y[C]=[]),y[C].push(k.title)}let S={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};m("");for(let[k,C]of Object.entries(y)){let A=S[k]||k;m(` ${A}: ${C.join(", ")}`)}}a||(m(""),m("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var it=class{buildFiles(e){let t=[],r=[],s=[],o={},a={};for(let i of e.files){let c=i.path.split("/"),l=c[0];if(l==="agents")s.push({path:i.path.slice(7),content:i.content});else if(l==="mcps"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(o,u.mcpServers);else if(i.path.includes("resources/")){let p=c.indexOf("resources"),d=p>0?c[p-1]:c[1];o[d]=u}}catch{t.push(`Failed to parse MCP config: ${i.path}`)}}else if(l==="hooks"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content),p=i.path.replace(/\/[^/]+$/,"");Mn(u,a,p)}catch{t.push(`Failed to parse hook config: ${i.path}`)}}else l==="skills"||l==="commands"||l==="files"?r.push({path:i.path.slice(l.length+1),content:i.content}):r.push(i)}return{mainFiles:r,agentFiles:s,mcpEntries:o,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=e.resource.slug||e.resource.id,i=T(r,o),c=Wn(e),l=(0,Ee.join)(i,...c),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(f=>!f.path.includes("/")),d=s.mainFiles.filter(f=>f.path.includes("/"));if(p.length>0){let f=p.find(g=>g.path==="README.md");f&&p.push({path:"SKILL.md",content:Hn(e,f.content)}),M(l,p),u+=p.length}d.length>0&&(M(i,d),u+=d.length)}if(s.agentFiles.length>0){let p=G(r,o);M(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Ln(V(r,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Qt(X(r,o),s.hookEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r,s){let o=[],i=T(r,t==="project"),c=(0,Ee.join)(i,e),l=!1;return(0,B.existsSync)(c)&&((0,B.rmSync)(c,{recursive:!0,force:!0}),l=!0),l||o.push(`Collection directory not found at ${c}`),{removed:l,warnings:o}}describeLocation(e,t,r){let s=T(r,t==="project");return(0,Ee.join)(s,e)}};function Mn(n,e,t){if(!n||typeof n!="object")return;let r=n,s=r.hooks&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)?r.hooks:r;for(let[o,a]of Object.entries(s))if(!(o==="name"||o==="description")&&Array.isArray(a)){e[o]||(e[o]=[]);for(let i of a){let c=t&&typeof i=="object"&&i!==null?{...i,_sc:t}:i;e[o].push(c)}}}function Qt(n,e,t){let r={};if((0,B.existsSync)(n))try{r=JSON.parse((0,B.readFileSync)(n,"utf-8"))}catch{r={}}let s=typeof r.hooks=="object"&&r.hooks&&!Array.isArray(r.hooks)?r.hooks:{};if(t)for(let[o,a]of Object.entries(s))Array.isArray(a)&&(s[o]=a.filter(i=>!i||typeof i!="object"||i._sc!==t),s[o].length===0&&delete s[o]);for(let[o,a]of Object.entries(e)){Array.isArray(s[o])||(s[o]=[]);for(let i of a){let c=t&&typeof i=="object"&&i!==null?{...i,_sc:t}:i,l=JSON.stringify(c);s[o].some(p=>JSON.stringify(p)===l)||s[o].push(c)}}r.hooks=s,(0,B.mkdirSync)((0,Ee.dirname)(n),{recursive:!0}),(0,B.writeFileSync)(n,JSON.stringify(r,null,2)+`
33
+ `,"utf-8")}function Zt(n,e){if(!(0,B.existsSync)(n))return!1;let t;try{t=JSON.parse((0,B.readFileSync)(n,"utf-8"))}catch{return!1}let r=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!r)return!1;let s=!1;for(let[o,a]of Object.entries(r)){if(!Array.isArray(a))continue;let i=a.filter(c=>!c||typeof c!="object"||c._sc!==e);i.length!==a.length&&(s=!0,i.length===0?delete r[o]:r[o]=i)}return s&&(t.hooks=r,(0,B.writeFileSync)(n,JSON.stringify(t,null,2)+`
34
+ `,"utf-8")),s}function Ln(n,e){let t={};if((0,B.existsSync)(n))try{t=JSON.parse((0,B.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,B.mkdirSync)((0,Ee.dirname)(n),{recursive:!0}),(0,B.writeFileSync)(n,JSON.stringify(t,null,2)+`
35
+ `,"utf-8")}function Hn(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
36
+ `)}function Wn(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 Q=require("fs"),Re=require("path");var Un={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},at=class{buildFiles(e){let t=[],r=[],s=[],o={},a={};for(let i of e.files){let c=i.path.split("/"),l=c[0];if(l==="agents")s.push({path:i.path.slice(7),content:i.content});else if(l==="mcps"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(o,u.mcpServers);else if(i.path.includes("resources/")){let p=c.indexOf("resources"),d=p>0?c[p-1]:c[1];o[d]=u}}catch{t.push(`Failed to parse MCP config: ${i.path}`)}}else if(l==="hooks"){if(i.path.endsWith(".json"))try{let u=JSON.parse(i.content);Vn(u,a)}catch{t.push(`Failed to parse hook config: ${i.path}`)}}else l==="skills"||l==="commands"||l==="files"?r.push({path:i.path.slice(l.length+1),content:i.content}):r.push(i)}return{mainFiles:r,agentFiles:s,mcpEntries:o,hookEntries:a,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=e.resource.slug||e.resource.id,i=T(r,o),c=Jn(e),l=(0,Re.join)(i,...c),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(f=>!f.path.includes("/")),d=s.mainFiles.filter(f=>f.path.includes("/"));if(p.length>0){let f=p.find(g=>g.path==="README.md");f&&p.push({path:"SKILL.md",content:Gn(e,f.content)}),M(l,p),u+=p.length}d.length>0&&(M(i,d),u+=d.length)}if(s.agentFiles.length>0){let p=G(r,o);M(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&qn(V(r,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Bn(X(r,o),s.hookEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=T(r,t==="project"),i=(0,Re.join)(a,e),c=!1;return(0,Q.existsSync)(i)&&((0,Q.rmSync)(i,{recursive:!0,force:!0}),c=!0),c||s.push(`Collection directory not found at ${i}`),{removed:c,warnings:s}}describeLocation(e,t,r){let s=T(r,t==="project");return(0,Re.join)(s,e)}};function Vn(n,e){if(!n||typeof n!="object")return;let t=n,r=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(r)){if(s==="name"||s==="description"||!Array.isArray(o))continue;let a=Un[s]||s;e[a]||(e[a]=[]);for(let i of o)e[a].push(i)}}function Bn(n,e){let t={};if((0,Q.existsSync)(n))try{t=JSON.parse((0,Q.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,o]of Object.entries(e)){Array.isArray(r[s])||(r[s]=[]);for(let a of o){let i=JSON.stringify(a);r[s].some(l=>JSON.stringify(l)===i)||r[s].push(a)}}t.hooks=r,(0,Q.mkdirSync)((0,Re.dirname)(n),{recursive:!0}),(0,Q.writeFileSync)(n,JSON.stringify(t,null,2)+`
37
+ `,"utf-8")}function qn(n,e){let t={};if((0,Q.existsSync)(n))try{t=JSON.parse((0,Q.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,Q.mkdirSync)((0,Re.dirname)(n),{recursive:!0}),(0,Q.writeFileSync)(n,JSON.stringify(t,null,2)+`
38
+ `,"utf-8")}function Gn(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
39
+ `)}function Jn(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 q=require("fs"),ye=require("path");var ct=class{buildFiles(e){let t=[],r=[],s=[],o={},a=[],i=e.resource.slug||e.resource.id;for(let c of e.files){let l=c.path.split("/"),u=l[0];if(u==="agents")s.push({path:c.path.slice(7),content:c.content});else if(u==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let d=l.indexOf("resources"),f=d>0?l[d-1]:l[1];o[f]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else u==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${c.path})`):u==="skills"||u==="commands"||u==="files"?r.push({path:c.path.slice(u.length+1),content:c.content}):r.push(c)}return{mainFiles:r,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:a,warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=T(r,o),i=zn(e),c=(0,ye.join)(a,...i),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(d=>!d.path.includes("/")),p=s.mainFiles.filter(d=>d.path.includes("/"));if(u.length>0){let d=u.find(f=>f.path==="README.md");d&&u.push({path:"SKILL.md",content:Kn(e,d.content)}),M(c,u),l+=u.length}p.length>0&&(M(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=G(r,o);M(u,s.agentFiles),l+=s.agentFiles.length}for(let u of s.customFiles)(0,q.mkdirSync)((0,ye.dirname)(u.absolutePath),{recursive:!0}),(0,q.writeFileSync)(u.absolutePath,u.content,"utf-8"),l++;return Object.keys(s.mcpEntries).length>0&&Yn(V(r,o),s.mcpEntries),{installDir:c,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=T(r,t==="project"),i=(0,ye.join)(a,e),c=!1;(0,q.existsSync)(i)&&((0,q.rmSync)(i,{recursive:!0,force:!0}),c=!0);let l=(0,ye.join)(homedir(),".cursor","rules");if((0,q.existsSync)(l))try{let u=(0,q.readdirSync)(l);for(let p of u)p.startsWith(`${e}-`)&&p.endsWith(".mdc")&&((0,q.unlinkSync)((0,ye.join)(l,p)),c=!0)}catch{s.push("Could not clean up Cursor rules")}return c||s.push(`Collection not found for Cursor at ${i}`),{removed:c,warnings:s}}describeLocation(e,t,r){let s=T(r,t==="project");return(0,ye.join)(s,e)}};function Yn(n,e){let t={};if((0,q.existsSync)(n))try{t=JSON.parse((0,q.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,q.mkdirSync)((0,ye.dirname)(n),{recursive:!0}),(0,q.writeFileSync)(n,JSON.stringify(t,null,2)+`
40
+ `,"utf-8")}function Kn(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
41
+ `)}function zn(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 pt=require("fs"),lt=require("path");var ut=class{buildFiles(e){let t=[],r=[],s=[];for(let o of e.files){let i=o.path.split("/")[0];i==="agents"?s.push({path:o.path.slice(7),content:o.content}):i==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):i==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):i==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):i==="skills"||i==="files"?r.push({path:o.path.slice(i.length+1),content:o.content}):r.push(o)}return{mainFiles:r,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=T(r,o),i=Qn(e),c=(0,lt.join)(a,...i),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(d=>!d.path.includes("/")),p=s.mainFiles.filter(d=>d.path.includes("/"));if(u.length>0){let d=u.find(f=>f.path==="README.md");d&&u.push({path:"SKILL.md",content:Xn(e,d.content)}),M(c,u),l+=u.length}p.length>0&&(M(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=G(r,o);M(u,s.agentFiles),l+=s.agentFiles.length}return{installDir:c,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=T(r,t==="project"),i=(0,lt.join)(a,e),c=!1;return(0,pt.existsSync)(i)&&((0,pt.rmSync)(i,{recursive:!0,force:!0}),c=!0),c||s.push(`Collection directory not found at ${i}`),{removed:c,warnings:s}}describeLocation(e,t,r){let s=T(r,t==="project");return(0,lt.join)(s,e)}};function Xn(n,e){let t=n.resource.title,r=n.resource.description||"",s=["---",`name: ${t}`];return r&&s.push(`description: ${r}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
42
+ `)}function Qn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var le=require("fs"),Ne=require("path");var dt=class{buildFiles(e){let t=[],r=[],s={};for(let o of e.files){let a=o.path.split("/"),i=a[0];if(i==="agents")r.push({path:o.path.slice(7),content:o.content});else if(i==="mcps"){if(o.path.endsWith(".json"))try{let c=JSON.parse(o.content);if(c.mcpServers&&typeof c.mcpServers=="object")Object.assign(s,c.mcpServers);else if(o.path.includes("resources/")){let l=a.indexOf("resources"),u=l>0?a[l-1]:a[1];s[u]=c}}catch{}}else i==="skills"||i==="commands"||i==="hooks"||i==="files"?t.push({path:o.path.slice(i.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:r,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,r){let s=this.buildFiles(e),o=t==="project",a=T(r,o),i=eo(e),c=(0,Ne.join)(a,...i),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(d=>!d.path.includes("/")),p=s.mainFiles.filter(d=>d.path.includes("/"));u.length>0&&(M(c,u),l+=u.length),p.length>0&&(M(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=G(r,o);M(u,s.agentFiles),l+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Zn(V(r,o),s.mcpEntries),{installDir:c,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let o=T(r,t==="project"),a=(0,Ne.join)(o,e),i=!1;return(0,le.existsSync)(a)&&((0,le.rmSync)(a,{recursive:!0,force:!0}),i=!0),{removed:i,warnings:[]}}describeLocation(e,t,r){let s=T(r,t==="project");return(0,Ne.join)(s,e)}};function Zn(n,e){let t={};if((0,le.existsSync)(n))try{t=JSON.parse((0,le.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,le.mkdirSync)((0,Ne.dirname)(n),{recursive:!0}),(0,le.writeFileSync)(n,JSON.stringify(t,null,2)+`
43
+ `,"utf-8")}function eo(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function ge(n){switch(n.id){case"claude-code":return new it;case"gemini-cli":case"antigravity":return new at;case"cursor":return new ct;case"codex":return new ut;default:return new dt}}var Zr=`---
39
44
  title: Resource Manager
40
45
  description: Search, install, and manage AI resources from the Shared Context library
41
46
  ---
@@ -181,30 +186,33 @@ npx shared-context-ai status # Auth status, detected agents, install
181
186
  \`\`\`
182
187
 
183
188
  **Error codes:** \`NOT_FOUND\`, \`AUTH_MISSING\`, \`NO_AGENTS\`, \`SKILL_NOT_FOUND\`, \`WRITE_FAILED\`, \`API_ERROR\`, \`UNEXPECTED\`
184
- `;var v=require("fs"),E=require("path"),zr=require("crypto");var at=".context-collection",ct="manifest.json";function Gr(n,e){return{version:1,name:n.name||"Untitled Plugin",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}function Vn(n,e){return{version:1,name:n.name||"Untitled Extension",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}function Bn(n,e){return{version:1,name:n.name||"Untitled Plugin",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}var Yt=[{path:`${at}/${ct}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:Gr,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:Gr,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:Vn,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:Bn,formatLabel:"Cursor Plugin"}];var Jr=[{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}],Yr=`${at}/${ct}`,qn=new Set(["py","sh","js","ts","rb","go","rs","bash","zsh"]),Gn=new Set(["json","yaml","yml","toml","xml","csv","txt","env","ini","cfg"]);function Le(n){let e={name:"",description:"",body:n};if(!n.startsWith(`---
189
+ `;var R=require("fs"),F=require("path"),ns=require("crypto");var mt=".context-collection",ft="manifest.json";function es(n,e){return{version:1,name:n.name||"Untitled Plugin",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}function to(n,e){return{version:1,name:n.name||"Untitled Extension",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}function ro(n,e){return{version:1,name:n.name||"Untitled Plugin",description:n.description||void 0,resources:e.map(t=>t.resourceRef),...n.author?{author:typeof n.author=="string"?{name:n.author}:{name:n.author.name||"",url:n.author.url}}:{},...n.homepage?{homepage:n.homepage}:{},...n.license?{license:n.license}:{}}}var er=[{path:`${mt}/${ft}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:es,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:es,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:to,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:ro,formatLabel:"Cursor Plugin"}];var ts=[{folder:"skills",mainFile:"SKILL.md",resourceType:"skill",canHaveChildren:!0},{folder:"commands",mainFile:null,resourceType:"skill",canHaveChildren:!0},{folder:"hooks",mainFile:"hook.json",resourceType:"hook",canHaveChildren:!1},{folder:"agents",mainFile:null,resourceType:"agent",canHaveChildren:!0},{folder:"mcps",mainFile:"mcp.json",resourceType:"mcp",canHaveChildren:!0},{folder:"collections",mainFile:"README.md",resourceType:"collection",canHaveChildren:!1}],rs=`${mt}/${ft}`,so=new Set(["py","sh","js","ts","rb","go","rs","bash","zsh"]),no=new Set(["json","yaml","yml","toml","xml","csv","txt","env","ini","cfg"]);function Ge(n){let e={name:"",description:"",body:n};if(!n.startsWith(`---
185
190
  `)&&!n.startsWith(`---\r
186
191
  `))return e;let t=n.indexOf(`
187
- ---`,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={},o=new Set(["requires","tools"]),l={},c=r.split(`
188
- `),p=null,u=!1;for(let d=0;d<c.length;d++){let b=c[d];if(p&&/^\s+-\s/.test(b)){let A=b.replace(/^\s+-\s/,"").trim();if(A){let S=$e(A);u?l[p].push(S):a[p].push(S)}continue}p=null,u=!1;let g=b.indexOf(":");if(g===-1)continue;let f=b.slice(0,g).trim(),m=b.slice(g+1).trim();if(!m&&f&&d+1<c.length&&/^\s+-\s/.test(c[d+1])){p=f,o.has(f)?(u=!0,l[f]=[]):(u=!1,a[f]=[]);continue}f==="name"||f==="title"?e.name=$e(m):f==="description"?e.description=$e(m):f==="skill_class"?e.skillClass=$e(m):f==="service"?e.service=$e(m):f&&m&&(i[f]=$e(m))}return l.requires?.length&&(e.requires=l.requires),l.tools?.length&&(e.tools=l.tools),Object.keys(i).length&&(e.fields=i),Object.keys(a).length&&(e.arrayFields=a),e}function $e(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 Jn(n){let{body:e}=Le(n);return e.replace(/\r\n/g,`
189
- `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Re(n){let e=Jn(n);return`sha256:${(0,zr.createHash)("sha256").update(e,"utf8").digest("hex")}`}function he(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Te(n){try{return(0,v.statSync)(n).isDirectory()}catch{return!1}}function Kr(n){try{return(0,v.readdirSync)(n).filter(e=>!e.startsWith(".")&&Te((0,E.join)(n,e)))}catch{return[]}}function lt(n){try{return(0,v.readdirSync)(n).filter(e=>!e.startsWith(".")&&!Te((0,E.join)(n,e)))}catch{return[]}}function Yn(n){let e=[],t=(0,E.join)(n,"scripts");if((0,v.existsSync)(t)&&Te(t))for(let s of lt(t)){let i=(0,E.extname)(s).slice(1);qn.has(i)&&e.push({category:"script",extension:i,filename:s,content:(0,v.readFileSync)((0,E.join)(t,s),"utf-8")})}let r=(0,E.join)(n,"resources");if((0,v.existsSync)(r)&&Te(r))for(let s of lt(r)){let i=(0,E.extname)(s).slice(1);Gn.has(i)&&e.push({category:"resource",extension:i,filename:s,content:(0,v.readFileSync)((0,E.join)(r,s),"utf-8")})}return e}function Ie(n){let e=[],t=[],r,s;function i(u,d){let b=[],g=[];for(let f of Jr){let m=(0,E.join)(u,f.folder);if(!(0,v.existsSync)(m)||!Te(m))continue;let A=d?`${d}/${f.folder}`:f.folder;if(f.folder==="files"){for(let S of lt(m)){if(!S.endsWith(".md"))continue;let C=(0,E.join)(m,S),N=(0,v.readFileSync)(C,"utf-8"),P=Le(N),V=P.name||(0,E.basename)(S,".md"),I=`${A}/${(0,E.basename)(S,".md")}`;b.push({importPath:I,resourceType:"file",title:V,description:P.description||null,body:P.body,bodyHash:Re(N),metadata:{},attachments:[]})}continue}for(let S of Kr(m)){let C=f.mainFile||`${S}.md`,N=(0,E.join)(m,S,C);if(!(0,v.existsSync)(N))continue;let P=(0,v.readFileSync)(N,"utf-8"),V=`${A}/${S}`,I,M,j,B={},R=null;if(f.resourceType==="hook"||f.resourceType==="mcp"){try{let te=JSON.parse(P);I=te.name||he(S),M=te.description||null}catch{I=he(S),M=null}j=P}else if(f.resourceType==="collection"){let te=(0,E.join)(m,S,at,ct);if((0,v.existsSync)(te))try{let fe=JSON.parse((0,v.readFileSync)(te,"utf-8"));I=fe.name||he(S),M=fe.description||null,j=P,fe.resources&&Array.isArray(fe.resources)&&g.push({collectionImportPath:V,memberImportPaths:fe.resources.map(Ae=>{let qe=Ae.split("/");return qe.length>=3?`${qe[0]}/${qe[qe.length-1]}`:Ae})})}catch{I=he(S),M=null,j=P}else R=Le(P),I=R.name||he(S),M=R.description||null,j=R.body,R.arrayFields?.resources&&g.push({collectionImportPath:V,memberImportPaths:R.arrayFields.resources.map(fe=>{let Ae=fe.split("/");return Ae.length>=3?`${Ae[0]}/${Ae[Ae.length-1]}`:fe})})}else R=Le(P),I=R.name||he(S),M=R.description||null,j=R.body,R.skillClass&&(B.skillClass=R.skillClass),R.service&&(B.service=R.service),R.requires?.length&&(B.requires=R.requires),R.tools?.length&&(B.tools=R.tools),R.fields&&Object.keys(R.fields).length&&(B.fields=R.fields);f.folder==="commands"&&(B.fields||(B.fields={}),B.fields["user-invocable"]="true");let Be=f.canHaveChildren?Yn((0,E.join)(m,S)):[];b.push({importPath:V,resourceType:f.resourceType,title:I,description:M,body:j,bodyHash:Re(P),metadata:B,attachments:Be})}}return{resources:b,memberships:g}}let a=i(n,"");e.push(...a.resources),t.push(...a.memberships);let o=(0,E.join)(n,".mcp.json");if((0,v.existsSync)(o))try{let u=JSON.parse((0,v.readFileSync)(o,"utf-8"));if(u.mcpServers&&typeof u.mcpServers=="object")for(let[d,b]of Object.entries(u.mcpServers)){let g=`mcps/${d}`;if(e.some(A=>A.importPath===g))continue;let f=he(d),m=JSON.stringify({name:f,description:`MCP server: ${d}`,mcpServers:{[d]:b}},null,2);e.push({importPath:g,resourceType:"mcp",title:f,description:`MCP server: ${d}`,body:m,bodyHash:Re(m),metadata:{},attachments:[]})}}catch{}for(let u of Yt){if(u.path===Yr)continue;let d=(0,E.join)(n,u.path);if((0,v.existsSync)(d)){try{let b=JSON.parse((0,v.readFileSync)(d,"utf-8"));if(r=r||b.name||void 0,s=u.formatLabel,!e.some(g=>g.resourceType==="collection")){let g=e.filter(C=>C.resourceType!=="collection").map(C=>({resourceRef:C.importPath})),f=u.converter(b,g),m=(0,E.join)(n,"README.md"),A=(0,v.existsSync)(m)?(0,v.readFileSync)(m,"utf-8"):"",S="collections/_root";e.push({importPath:S,resourceType:"collection",title:he(f.name),description:f.description||null,body:A,bodyHash:Re(A),metadata:{},attachments:[],manifestMetadata:{...f.author?{author:f.author}:{},...f.homepage?{homepage:f.homepage}:{},...f.license?{license:f.license}:{}}}),f.resources.length>0&&t.push({collectionImportPath:S,memberImportPaths:f.resources})}}catch{}break}}{let b=function(g,f,m){if(!(m>4))for(let A of Kr(g)){if(d.has(A))continue;let S=(0,E.join)(g,A),C=f?`${f}/${A}`:A;for(let N of Yt){if(N.path===Yr)continue;let P=(0,E.join)(S,N.path);if((0,v.existsSync)(P)){if(u.has(C))break;u.add(C);try{let V=JSON.parse((0,v.readFileSync)(P,"utf-8")),I=i(S,C);if(I.resources.length===0)break;e.push(...I.resources),t.push(...I.memberships);let M=I.resources.filter(te=>te.resourceType!=="collection").map(te=>({resourceRef:te.importPath})),j=N.converter(V,M),B=(0,E.join)(S,"README.md"),R=(0,v.existsSync)(B)?(0,v.readFileSync)(B,"utf-8"):"",Be=`${C}/_collection`;e.push({importPath:Be,resourceType:"collection",title:he(j.name),description:j.description||null,body:R,bodyHash:Re(R),metadata:{},attachments:[],manifestMetadata:{...j.author?{author:j.author}:{},...j.homepage?{homepage:j.homepage}:{},...j.license?{license:j.license}:{}}}),t.push({collectionImportPath:Be,memberImportPaths:I.resources.map(te=>te.importPath)}),r||(r=V.name||void 0),s||(s=N.formatLabel)}catch{}break}}b(S,C,m+1)}};var p=b;let u=new Set,d=new Set(Jr.map(g=>g.folder));b(n,"",0)}let l=(0,E.join)(n,"files");if((0,v.existsSync)(l)&&Te(l)&&!e.some(u=>u.resourceType==="file"))for(let u of lt(l)){if(!u.endsWith(".md"))continue;let d=(0,E.join)(l,u),b=(0,v.readFileSync)(d,"utf-8"),g=Le(b),f=g.name||(0,E.basename)(u,".md"),m=`files/${(0,E.basename)(u,".md")}`;e.some(A=>A.importPath===m)||e.push({importPath:m,resourceType:"file",title:f,description:g.description||null,body:g.body,bodyHash:Re(b),metadata:{},attachments:[]})}return{resources:[...e.filter(u=>u.resourceType!=="collection"),...e.filter(u=>u.resourceType==="collection")],collectionMemberships:t,pluginName:r,formatLabel:s}}var je="resource-manager",Xr="Resource Manager",Kt="collections/shared-context/essentials";function Kn(n,e){let t=_(n,e),r=(0,We.join)(t,je);return(0,ut.mkdirSync)(r,{recursive:!0}),(0,ut.writeFileSync)((0,We.join)(r,"SKILL.md"),qr,"utf-8"),(0,We.join)(r,"SKILL.md")}var zn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Zr(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:c}=await Promise.resolve().then(()=>(z(),Wr)),{saveAuth:p}=await Promise.resolve().then(()=>(Q(),Lr)),u=await c("/api/cli/auth",{code:r.code});u.ok||(y()?x("init",u.error.code,u.error.message):w(`Auth failed: ${u.error.message}`),process.exit(1)),p({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()}),y()||h(`Authenticated as ${u.data.user.email}`)}else T()||(y()?(x("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=ce(r.agent);if(!s){let c=le();y()?x("init","NO_AGENTS",c):w(c),process.exit(1)}let i=ae();if(i?.token){let c=(await import("os")).hostname(),p=await F("/api/cli/register-agent",{platform:s.platform,name:`CLI (${c})`});!p.ok&&!y()&&w(`Warning: Could not register agent connection: ${p.error.message}`)}let a=!1,o=[];if(i?.token)try{let c=await H(`/api/cli/resource/${Kt}`);if(c.ok){let p=c.data,d=await Ee(s).install(p,r.project?"project":"user",s),b={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};if(ne({resourceId:p.resource.id,slug:p.resource.slug||"essentials",installPath:Kt,title:p.resource.title,sha:p.resource.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString(),pluginFormat:b[s.id]||"directory",memberCount:p.memberResources?.length}),p.resource.latestSha&&await F("/api/cli/install",{resourceId:p.resource.id,agentPlatform:s.platform,installedSha:p.resource.latestSha}).catch(()=>{}),p.memberResources)for(let g of p.memberResources){let f=g.slug||g.id,m=zn[g.resourceType]||g.resourceType+"s",A=g.orgSlug||p.resource.orgSlug,S=A?`${m}/${A}/${f}`:`${m}/${f}`;ne({resourceId:g.id,slug:f,installPath:S,title:g.title,sha:g.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString(),collectionId:p.resource.id}),o.push({title:g.title,resourceType:g.resourceType}),g.latestSha&&await F("/api/cli/install",{resourceId:g.id,agentPlatform:s.platform,installedSha:g.latestSha}).catch(()=>{})}if(a=!0,!y()&&d.warnings.length>0)for(let g of d.warnings)w(`Warning: ${g}`)}}catch{}if(!a&&(Kn(s,!!r.project),ne({resourceId:"resource-manager",slug:je,installPath:`skills/${je}`,title:Xr,sha:"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()}),i?.token))try{let c=`skills/shared-context/${je}`,p=await H(`/api/cli/resource/${c}`);if(p.ok&&p.data.resource){let u=p.data.resource;u.latestSha&&await F("/api/cli/install",{resourceId:u.id,agentPlatform:s.platform,installedSha:u.latestSha}),ne({resourceId:u.id,slug:u.slug||je,installPath:`skills/shared-context/${u.slug||je}`,title:u.title||Xr,sha:u.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()})}}catch{}let l=[];if(i?.token)try{let c=(0,We.join)((0,Qr.homedir)(),s.dir),p=Ie(c),u=K(),d=new Set(u.installations.map(f=>f.installPath)),b=new Set(["resource-manager",".claude-plugin"]),g=p.resources.filter(f=>{if(d.has(f.importPath)||f.importPath.startsWith("."))return!1;let m=f.importPath.split("/").pop()||"";return!b.has(m)});if(g.length>0){let f={dryRun:!1,onConflict:"auto",visibility:"org",resources:g,collectionMemberships:p.collectionMemberships},m=await F("/api/cli/import",f,12e4);m.ok&&(l=[...m.data.created,...m.data.updated,...m.data.installed].map(S=>({resourceType:S.resourceType||S.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:S.slug||S.importPath.split("/").pop()||"",title:S.importPath.split("/").pop()||""})))}He({lastSyncAt:new Date().toISOString(),lastResult:{updatesAvailable:0,untrackedResources:0}})}catch{}if(y())O("init",{agent:s.id,collection:a?Kt:void 0,resourceManagerOnly:!a,...a?{membersInstalled:o.map(c=>({title:c.title,resourceType:c.resourceType}))}:{},...l.length>0?{importedResources:l.map(c=>({resourceType:c.resourceType,slug:c.slug,title:c.title}))}:{},authenticated:T()});else{if(h(""),a){h(`Shared Context Essentials installed for ${s.label} (${o.length} resources)`);let c={};for(let u of o)c[u.resourceType]||(c[u.resourceType]=[]),c[u.resourceType].push(u.title);let p={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};h("");for(let[u,d]of Object.entries(c)){let b=p[u]||u;h(` ${b}: ${d.join(", ")}`)}}else h(`Shared Context initialized for ${s.label}`),h("Resource Manager installed");if(l.length>0){h(""),h(`Imported ${l.length} existing resource${l.length===1?"":"s"}:`);for(let c of l)h(` ${c.resourceType.padEnd(12)} ${c.slug.padEnd(24)} ${c.title}`)}h(""),h("Quick reference:"),h(' shared-context-ai search "query" Search for resources'),h(" shared-context-ai install <installPath> Install a resource"),h(" shared-context-ai list List installed resources"),h(" shared-context-ai sync Check updates & discover resources"),h(" shared-context-ai preview <installPath> Preview before installing")}})}var Ps=require("http"),$s=require("crypto");Q();z();Q();async function Rs(n){let e=await F("/api/cli/auth",{code:n});return e.ok?(Mt({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()}),y()?O("login",{email:e.data.user.email,org:e.data.org.slug}):h(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(y()?x("login",e.error.code,e.error.message):w(`Login failed: ${e.error.message}`),!1)}async function di(){let n=(0,$s.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,Ps.createServer)((r,s)=>{let i=new URL(r.url||"/","http://localhost"),a=i.searchParams.get("code"),o=i.searchParams.get("state");if(!a||o!==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(),Rs(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=`${ge().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${n}`;y()||(h("Opening browser for authentication..."),h(`If the browser doesn't open, visit: ${a}`));try{let o=(await Promise.resolve().then(()=>(Es(),vs))).default;await o(a)}catch{y()||h(`Could not open browser. Please visit:
190
- ${a}`)}setTimeout(()=>{t.close(),y()||w("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function Ts(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 Rs(e.code):t=await di(),process.exit(t?0:1)})}z();var hi={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Is(n){let e=hi[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 js(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=T()?`/api/cli/search?${r}`:`/api/public/search?${r}`,i=await H(s);i.ok||(y()?x("search",i.error.code,i.error.message):h(`Search failed: ${i.error.message}`),process.exit(1));let a=i.data.results;if(y()){let l=a.map(c=>{let p=Is(c);return{installPath:p,installCommand:`npx shared-context-ai install ${p}`,title:c.title,description:c.description,resourceType:c.resourceType,installCount:c.installCount,topicTags:c.topicTags}});O("search",{results:l,count:l.length});return}if(a.length===0){let l=t.type?`${t.type}s`:"results";h(`No ${l} found.`);return}h(`Found ${a.length} result${a.length===1?"":"s"}:
191
- `);let o=a.map(l=>[Is(l),l.title,`\u2193${l.installCount}`]);h(re(o)),h(`
192
- Install a skill: npx shared-context-ai install <installPath>`)})}z();Q();function Fs(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 Ds(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if(T()){let e=await H("/api/cli/installed");e.ok||(y()?x("list",e.error.code,e.error.message):h(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(y()){let s=t.map(i=>({...i,installPath:Fs(i)}));O("list",{installations:s,count:s.length});return}if(t.length===0){h("No skills installed."),h("Use 'shared-context-ai search' to find skills to install.");return}h(`${t.length} skill${t.length===1?"":"s"} installed:
193
- `);let r=t.map(s=>[Fs(s),s.title,s.hasUpdate?"(update available)":"(current)"]);h(re(r))}else{let t=K().installations;if(y()){O("list",{installations:t,count:t.length});return}if(t.length===0){h("No skills installed locally.");return}h(`${t.length} skill${t.length===1?"":"s"} installed locally:
194
- `);let r=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);h(re(r)),h(`
195
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}z();function Ns(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let r=T()?"/api/cli/resource":"/api/public/resource",s=await H(`${r}/${e}/preview`);s.ok||(y()?x("preview",s.error.code,s.error.message):w(`Preview failed: ${s.error.message}`),process.exit(1)),y()?O("preview",s.data):h(s.data.content)})}z();function Ms(n){n.command("check").description("Check for skill updates").action(async()=>{T()||(y()?x("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 H("/api/cli/updates");e.ok||(y()?x("check",e.error.code,e.error.message):w(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:r}=e.data;if(y()){O("check",{updates:t,count:r});return}if(r===0){h("All skills are up to date.");return}h(`${r} update${r===1?"":"s"} available:
196
- `);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)}`]});h(re(s)),h(`
197
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var gr=require("path");z();Q();var fi={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Hs(n){let e=n.slug||n.resourceId,t=fi[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 Ls(n){n.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,r)=>{let s=r.optsWithGlobals();T()||(y()?x("update","AUTH_MISSING","Login required to update resources."):w("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let i=ce(s.agent);if(!i){let c=le();y()?x("update","NO_AGENTS",c):w(c),process.exit(1)}let a=await H("/api/cli/updates");a.ok||(y()?x("update",a.error.code,a.error.message):w(`Failed to check updates: ${a.error.message}`),process.exit(1));let o=a.data.updates;if(e&&(o=o.filter(c=>Hs(c)===e||c.slug===e||c.resourceId===e),o.length===0)){y()?x("update","SKILL_NOT_FOUND",`No update available for "${e}".`):h(`No update available for "${e}".`);return}if(o.length===0){y()?O("update",{updated:[],count:0}):h("All resources are up to date.");return}let l=[];for(let c of o){let p=Hs(c),u=await H(`/api/cli/resource/${p}`);if(!u.ok){y()||w(` Failed to fetch ${p}: ${u.error.message}`);continue}let d=u.data,b=p.split("/").slice(1);if(d.resource.resourceType==="agent"){let g=U(i,!!s.project),f=(0,gr.join)(g,...b);$(f,d.files)}else if(d.resource.resourceType==="mcp")qt(i,!!s.project,d);else{let g=_(i,!!s.project),f=(0,gr.join)(g,...b);$(f,d.files)}d.resource.latestSha&&await F("/api/cli/update",{resourceId:d.resource.id,installedSha:d.resource.latestSha}),ne({resourceId:d.resource.id,slug:d.resource.slug||d.resource.id,installPath:p,title:d.resource.title,sha:d.resource.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString()}),l.push({installPath:p,title:d.resource.title}),y()||h(` Updated ${p}`)}y()?O("update",{updated:l,count:l.length}):l.length>0&&h(`
198
- ${l.length} resource${l.length===1?"":"s"} updated.`)})}var D=require("fs"),De=require("path");z();Q();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=ce(s.agent);if(!i){let b=le();y()?x("uninstall","NO_AGENTS",b):w(b),process.exit(1)}let o=K().installations.find(b=>b.installPath===e||b.slug===e||b.resourceId===e),l=e.split("/"),p=["skills","files","commands","hooks","collections","agents","mcps"].includes(l[0])?l[0]:null,u=p?l.slice(1):l,d=!1;if(p==="collections"){let b=Ee(i),g=u[u.length-1],f=s.project?"project":"user",m=await b.uninstall(g,f,i,o?.resourceId);if(d=m.removed,!y())for(let A of m.warnings)w(`Warning: ${A}`);if(o){let S=K().installations.filter(C=>C.collectionId===o.resourceId&&C.agent===i.id);for(let C of S){let N=C.installPath.split("/"),P=N[0],V=N.slice(1);if(P==="agents"){let I=U(i,!!s.project),M=(0,De.join)(I,...V);(0,D.existsSync)(M)&&(0,D.rmSync)(M,{recursive:!0,force:!0})}else if(P==="mcps"){let I=V[V.length-1],M=G(i,!!s.project);if((0,D.existsSync)(M))try{let j=JSON.parse((0,D.readFileSync)(M,"utf-8"));if(typeof j.mcpServers=="object"&&j.mcpServers&&!Array.isArray(j.mcpServers)){let B=j.mcpServers;I in B&&(delete B[I],j.mcpServers=B,(0,D.writeFileSync)(M,JSON.stringify(j,null,2)+`
199
- `,"utf-8"))}}catch{}}else if(P==="hooks")Jt(ie(i,!!s.project),C.installPath);else{let I=_(i,!!s.project),M=(0,De.join)(I,...V);(0,D.existsSync)(M)&&(0,D.rmSync)(M,{recursive:!0,force:!0})}Xe(C.resourceId,i.id)}}}else if(p==="agents"){let b=U(i,!!s.project),g=(0,De.join)(b,...u);d=(0,D.existsSync)(g),d&&(0,D.rmSync)(g,{recursive:!0,force:!0})}else if(p==="mcps"){let b=u[u.length-1],g=G(i,!!s.project);if((0,D.existsSync)(g))try{let f=JSON.parse((0,D.readFileSync)(g,"utf-8"));if(typeof f.mcpServers=="object"&&f.mcpServers&&!Array.isArray(f.mcpServers)){let m=f.mcpServers;b in m&&(delete m[b],f.mcpServers=m,(0,D.writeFileSync)(g,JSON.stringify(f,null,2)+`
200
- `,"utf-8"),d=!0)}}catch{}}else if(p==="hooks"){let b=ie(i,!!s.project);d=Jt(b,e),!d&&!y()&&w(`Note: No tagged hook entries found in ${b} \u2014 may need manual removal if installed before v0.1.10`)}else{let b=_(i,!!s.project),g=(0,De.join)(b,...u);if(d=(0,D.existsSync)(g),d&&(0,D.rmSync)(g,{recursive:!0,force:!0}),!d&&o?.slug){let f=(0,De.join)(b,o.slug);(0,D.existsSync)(f)&&(0,D.rmSync)(f,{recursive:!0,force:!0})}}if(T()&&o){let b=await F("/api/cli/uninstall",{resourceId:o.resourceId});!b.ok&&!y()&&w(`Warning: Could not record uninstall on server: ${b.error.message}`)}o&&Xe(o.resourceId,i.id),y()?O("uninstall",{path:e,removed:!0}):h(`Uninstalled "${e}"`)})}Q();function Us(n){n.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=ae(),t=ge(),r=K(),s=Bt(),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(y()){O("status",i);return}h("Shared Context CLI Status"),h("\u2500".repeat(30)),e?.token?h(` Auth: ${e.email} (${e.orgSlug})`):h(" Auth: Not logged in"),h(` API: ${t.apiBase}`),s.length>0?h(` Agents: ${s.map(a=>a.label).join(", ")}`):h(" Agents: None detected"),h(` Skills: ${r.installations.length} installed`)})}Q();z();function Vs(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=ae();e.revoke&&T()&&await Ut("/api/cli/auth"),Ht(),y()?O("logout",{email:t?.email||null}):h("Logged out.")})}var gt=require("fs"),Bs=require("path");z();function qs(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&&(y()?x("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&&(y()?x("import","INVALID_ARGS","Provide a local path or --github <url>"):w("Error: Provide a local path or --github <url>"),process.exit(1)),T()||(y()?x("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"&&(y()?x("import","INVALID_ARGS","--on-conflict is not supported with --github"):w("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(y()?x("import","INVALID_ARGS","--dry-run is not supported with --github"):w("Error: --dry-run is not supported with --github"),process.exit(1));let g={url:i};t.resourceType&&(g.resourceType=t.resourceType),y()||h(`
201
- Importing from GitHub: ${i}`);let f=await F("/api/cli/github-import",g);f.ok||(y()?x("import",f.error.code,f.error.message):w(`
202
- Import failed: ${f.error.message}`),process.exit(1));let m=f.data;if(y()){O("import",m);return}h(""),h(` Source: ${m.source.owner}/${m.source.repo}`),h(` Type: ${m.resourceType}`),h(` Title: ${m.title}`),m.slug&&h(` Slug: ${m.slug}`),h(` URL: ${m.url}`),h(""),h("Import complete: 1 created");return}let a=(0,Bs.resolve)(e);(!(0,gt.existsSync)(a)||!(0,gt.statSync)(a).isDirectory())&&(y()?x("import","INVALID_PATH",`Not a directory: ${a}`):w(`Error: Not a directory: ${a}`),process.exit(1));let o=Ie(a);if(o.resources.length===0){y()?O("import",{resources:[],message:"No resources found"}):h("No resources found in the specified directory.");return}if(!y()){let g=new Map;for(let m of o.resources)g.set(m.resourceType,(g.get(m.resourceType)||0)+1);let f=[...g.entries()].map(([m,A])=>`${A} ${m}${A===1?"":"s"}`).join(", ");h(`
203
- Discovered ${o.resources.length} resources in ${e}:`),h(` ${f}`),o.formatLabel&&o.pluginName?h(` ${o.formatLabel}: ${o.pluginName}`):o.pluginName&&h(` Plugin: ${o.pluginName}`)}let l=t.tags?t.tags.split(",").map(g=>g.trim()).filter(Boolean):void 0,c={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:l,resources:o.resources,collectionMemberships:o.collectionMemberships.length>0?o.collectionMemberships:void 0};!y()&&!t.dryRun?h(`
204
- Executing import...`):y()||h(`
205
- Dry run \u2014 previewing changes...`);let p=await F("/api/cli/import",c,12e4);p.ok||(y()?x("import",p.error.code,p.error.message):w(`
206
- Import failed: ${p.error.message}`),process.exit(1));let u=p.data;if(y()){O("import",u);return}let d=[...u.created.map(g=>({...g,action:"created"})),...u.updated.map(g=>({...g,action:"updated"})),...u.installed.map(g=>({...g,action:"installed"})),...u.cloned.map(g=>({...g,action:"cloned"})),...u.skipped.map(g=>({...g,action:"skipped"})),...u.errors.map(g=>({...g,action:"error"}))];if(d.length>0){h("");let g=d.length,f=d.map((m,A)=>{let S=`[${String(A+1).padStart(String(g).length)}/${g}]`,C=(m.resourceType||"").padEnd(10),N=(m.importPath.split("/").pop()||"").padEnd(24),P="";switch(m.action){case"created":P=`\u2713 created${m.slug?` (slug: ${m.slug})`:""}`;break;case"updated":P="\u2713 updated";break;case"installed":{let V=m.versionsBehind;P=`\u2713 installed${V?` (${V} versions behind)`:""}`;break}case"cloned":P=`\u2713 cloned${m.slug?` (slug: ${m.slug})`:""}`;break;case"skipped":P=`\u2713 skipped (${m.reason||"up to date"})`;break;case"error":P=`\u2717 error: ${m.error||"unknown"}`;break}return` ${S} ${C} ${N} ${P}`});for(let m of f)h(m)}if(u.collections.length>0)for(let g of u.collections){let f=g.importPath.split("/").pop()||g.importPath;h(` collection ${f.padEnd(20)} \u2713 ${g.membersLinked} members linked${g.membersFailed>0?`, ${g.membersFailed} failed`:""}`)}h("");let b=[u.created.length>0?`${u.created.length} created`:null,u.installed.length>0?`${u.installed.length} installed`:null,u.cloned.length>0?`${u.cloned.length} cloned`:null,u.updated.length>0?`${u.updated.length} updated`:null,u.skipped.length>0?`${u.skipped.length} skipped`:null,u.errors.length>0?`${u.errors.length} errors`:null].filter(Boolean);t.dryRun?h(`Dry run complete: ${b.join(", ")}`):h(`Import complete: ${b.join(", ")}`),u.errors.length>0&&process.exit(1)})}var Ys=require("path"),Ks=require("os");z();Q();function zs(n){n.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--import","Auto-import untracked resources to your dashboard").action(async(e,t)=>{let r={...e,...t.optsWithGlobals()};if(!r.force&&!Wt()){let f=Qe();if(f){let m={...f.lastResult,updates:[],untracked:[],summary:Gs(f.lastResult.updatesAvailable,f.lastResult.untrackedResources),throttled:!0};Js(m,!!r.quiet);return}}T()||(y()?x("sync","AUTH_MISSING","Login required to sync."):w("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=ce(r.agent);if(!s){let f=le();y()?x("sync","NO_AGENTS",f):w(f),process.exit(1)}let i=[],a=await H("/api/cli/updates");a.ok&&(i=a.data.updates);let o=(0,Ys.join)((0,Ks.homedir)(),s.dir),l=Ie(o),c=K(),p=new Set(c.installations.map(f=>f.installPath)),u=new Set(["resource-manager",".claude-plugin"]),d=l.resources.filter(f=>{if(p.has(f.importPath)||f.importPath.startsWith("."))return!1;let m=f.importPath.split("/").pop()||"";return!u.has(m)});if(r.import&&d.length>0){let f={dryRun:!1,onConflict:"auto",visibility:"org",resources:d,collectionMemberships:l.collectionMemberships},m=await F("/api/cli/import",f,12e4);if(m.ok){let A=[...m.data.created,...m.data.updated,...m.data.installed];if(!y()&&!r.quiet){if(A.length>0){h(`
207
- Imported ${A.length} resource${A.length===1?"":"s"}:`);let S=A.map(C=>[` ${(C.resourceType||"").padEnd(12)}`,(C.slug||C.importPath.split("/").pop()||"").padEnd(24),C.importPath]);h(re(S))}m.data.errors.length>0&&w(`
208
- ${m.data.errors.length} import error(s)`)}d.length=0}else y()||w(`Import failed: ${m.error.message}`)}let b={updatesAvailable:i.length,untrackedResources:d.length};He({lastSyncAt:new Date().toISOString(),lastResult:b});let g={...b,updates:i,untracked:d.map(f=>({importPath:f.importPath,resourceType:f.resourceType,title:f.title})),summary:Gs(i.length,d.length),throttled:!1};Js(g,!!r.quiet)})}function Gs(n,e){let t=[];return n>0&&t.push(`${n} update${n===1?"":"s"} available`),e>0&&t.push(`${e} untracked resource${e===1?"":"s"}`),t.length===0?"Everything is up to date.":t.join(", ")}function Js(n,e){if(y()){O("sync",n);return}if(e){let t=n.summary;n.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),n.untrackedResources>0&&(t+=" \u2014 run 'shared-context-ai sync --import' to import"),h(t);return}if(h(""),n.updates.length>0){h(`${n.updates.length} update${n.updates.length===1?"":"s"} available:
209
- `);let t=n.updates.map(r=>{let s=r.slug||r.resourceId,i=r.resourceType==="skill"?"skills":`${r.resourceType}s`;return[` ${r.storageType==="github"&&r.githubOwner?`${i}/external/${r.githubOwner}/${s}`:r.orgSlug?`${i}/${r.orgSlug}/${s}`:`${i}/${s}`}`,r.title,`${r.installedSha.slice(0,7)} \u2192 ${r.latestSha.slice(0,7)}`]});h(re(t)),h("")}if(n.untracked.length>0){h(`${n.untracked.length} untracked resource${n.untracked.length===1?"":"s"}:
210
- `);let t=n.untracked.map(r=>[` ${r.resourceType.padEnd(12)}`,r.importPath.padEnd(30),r.title]);h(re(t)),h("")}n.updatesAvailable===0&&n.untrackedResources===0?h("Everything is up to date."):(n.updatesAvailable>0&&h("Run 'shared-context-ai update' to update installed resources."),n.untrackedResources>0&&h("Run 'shared-context-ai sync --import' to import untracked resources.")),h("")}var Xs={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."},yt=class extends Error{constructor(t,r){super(r||Xs[t]);this.code=t;this.name="CliError"}get recovery(){return Xs[this.code]}};var Y=new $r;Y.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();Ir(!!e.json,!!e.human)});Zr(Y);Ts(Y);js(Y);Br(Y);Ds(Y);Ns(Y);Ms(Y);Ls(Y);Ws(Y);Us(Y);Vs(Y);qs(Y);zs(Y);process.on("uncaughtException",n=>{n instanceof yt?y()?x(process.argv[2]||"unknown",n.code,n.message):(w(`Error: ${n.message}`),w(n.recovery)):y()?x(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):w(`Error: ${n.message||n}`),process.exit(1)});Y.parse();
192
+ ---`,3);if(t===-1)return e;let r=n.slice(4,t),s=n.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let o={},a={},i=new Set(["requires","tools"]),c={},l=r.split(`
193
+ `),u=null,p=!1;for(let d=0;d<l.length;d++){let f=l[d];if(u&&/^\s+-\s/.test(f)){let y=f.replace(/^\s+-\s/,"").trim();if(y){let S=Me(y);p?c[u].push(S):a[u].push(S)}continue}u=null,p=!1;let g=f.indexOf(":");if(g===-1)continue;let h=f.slice(0,g).trim(),b=f.slice(g+1).trim();if(!b&&h&&d+1<l.length&&/^\s+-\s/.test(l[d+1])){u=h,i.has(h)?(p=!0,c[h]=[]):(p=!1,a[h]=[]);continue}h==="name"||h==="title"?e.name=Me(b):h==="description"?e.description=Me(b):h==="skill_class"?e.skillClass=Me(b):h==="service"?e.service=Me(b):h&&b&&(o[h]=Me(b))}return c.requires?.length&&(e.requires=c.requires),c.tools?.length&&(e.tools=c.tools),Object.keys(o).length&&(e.fields=o),Object.keys(a).length&&(e.arrayFields=a),e}function Me(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 oo(n){let{body:e}=Ge(n);return e.replace(/\r\n/g,`
194
+ `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function $e(n){let e=oo(n);return`sha256:${(0,ns.createHash)("sha256").update(e,"utf8").digest("hex")}`}function fe(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Le(n){try{return(0,R.statSync)(n).isDirectory()}catch{return!1}}function ss(n){try{return(0,R.readdirSync)(n).filter(e=>!e.startsWith(".")&&Le((0,F.join)(n,e)))}catch{return[]}}function ht(n){try{return(0,R.readdirSync)(n).filter(e=>!e.startsWith(".")&&!Le((0,F.join)(n,e)))}catch{return[]}}function io(n){let e=[],t=(0,F.join)(n,"scripts");if((0,R.existsSync)(t)&&Le(t))for(let s of ht(t)){let o=(0,F.extname)(s).slice(1);so.has(o)&&e.push({category:"script",extension:o,filename:s,content:(0,R.readFileSync)((0,F.join)(t,s),"utf-8")})}let r=(0,F.join)(n,"resources");if((0,R.existsSync)(r)&&Le(r))for(let s of ht(r)){let o=(0,F.extname)(s).slice(1);no.has(o)&&e.push({category:"resource",extension:o,filename:s,content:(0,R.readFileSync)((0,F.join)(r,s),"utf-8")})}return e}function He(n,e){let t=[],r=[],s,o;function a(f,g){let h=[],b=[];for(let y of ts){let S=(0,F.join)(f,y.folder);if(!(0,R.existsSync)(S)||!Le(S))continue;let k=g?`${g}/${y.folder}`:y.folder;if(y.folder==="files"){for(let C of ht(S)){if(!C.endsWith(".md"))continue;let A=(0,F.join)(S,C),O=(0,R.readFileSync)(A,"utf-8"),v=Ge(O),P=v.name||(0,F.basename)(C,".md"),I=`${k}/${(0,F.basename)(C,".md")}`;h.push({importPath:I,resourceType:"file",title:P,description:v.description||null,body:v.body,bodyHash:$e(O),metadata:{},attachments:[]})}continue}for(let C of ss(S)){let A=y.mainFile||`${C}.md`,O=(0,F.join)(S,C,A);if(!(0,R.existsSync)(O))continue;let v=(0,R.readFileSync)(O,"utf-8"),P=`${k}/${C}`,I,J,H,W={},D=null;if(y.resourceType==="hook"||y.resourceType==="mcp"){try{let ae=JSON.parse(v);I=ae.name||fe(C),J=ae.description||null}catch{I=fe(C),J=null}H=v}else if(y.resourceType==="collection"){let ae=(0,F.join)(S,C,mt,ft);if((0,R.existsSync)(ae))try{let be=JSON.parse((0,R.readFileSync)(ae,"utf-8"));I=be.name||fe(C),J=be.description||null,H=v,be.resources&&Array.isArray(be.resources)&&b.push({collectionImportPath:P,memberImportPaths:be.resources.map(_e=>{let ze=_e.split("/");return ze.length>=3?`${ze[0]}/${ze[ze.length-1]}`:_e})})}catch{I=fe(C),J=null,H=v}else D=Ge(v),I=D.name||fe(C),J=D.description||null,H=D.body,D.arrayFields?.resources&&b.push({collectionImportPath:P,memberImportPaths:D.arrayFields.resources.map(be=>{let _e=be.split("/");return _e.length>=3?`${_e[0]}/${_e[_e.length-1]}`:be})})}else D=Ge(v),I=D.name||fe(C),J=D.description||null,H=D.body,D.skillClass&&(W.skillClass=D.skillClass),D.service&&(W.service=D.service),D.requires?.length&&(W.requires=D.requires),D.tools?.length&&(W.tools=D.tools),D.fields&&Object.keys(D.fields).length&&(W.fields=D.fields);y.folder==="commands"&&(W.fields||(W.fields={}),W.fields["user-invocable"]="true");let Oe=y.canHaveChildren?io((0,F.join)(S,C)):[];h.push({importPath:P,resourceType:y.resourceType,title:I,description:J,body:H,bodyHash:$e(v),metadata:W,attachments:Oe})}}return{resources:h,memberships:b}}let i=a(n,"");t.push(...i.resources),r.push(...i.memberships);let c=new Set;e?.mcpConfigPath&&c.add(e.mcpConfigPath);let l=(0,F.join)(n,".mcp.json");(0,R.existsSync)(l)&&c.add(l);for(let f of c)if((0,R.existsSync)(f))try{let g=JSON.parse((0,R.readFileSync)(f,"utf-8"));if(g.mcpServers&&typeof g.mcpServers=="object")for(let[h,b]of Object.entries(g.mcpServers)){let y=`mcps/${h}`;if(t.some(C=>C.importPath===y))continue;let S=fe(h),k=JSON.stringify({name:S,description:`MCP server: ${h}`,mcpServers:{[h]:b}},null,2);t.push({importPath:y,resourceType:"mcp",title:S,description:`MCP server: ${h}`,body:k,bodyHash:$e(k),metadata:{},attachments:[]})}}catch{}if(e?.settingsPath&&(0,R.existsSync)(e.settingsPath))try{let f=JSON.parse((0,R.readFileSync)(e.settingsPath,"utf-8"));if(f.hooks&&typeof f.hooks=="object"&&!Array.isArray(f.hooks)){let g={};for(let[h,b]of Object.entries(f.hooks))if(Array.isArray(b))for(let y of b){if(!y||typeof y!="object")continue;let S=y,k=S._sc;if(!k)continue;g[k]||(g[k]={}),g[k][h]||(g[k][h]=[]);let{_sc:C,...A}=S;g[k][h].push(A)}for(let[h,b]of Object.entries(g)){let y=h;if(t.some(A=>A.importPath===y))continue;let S=h.split("/").pop()||h,k=fe(S),C=JSON.stringify({name:k,description:`Hook: ${k}`,hooks:b},null,2);t.push({importPath:y,resourceType:"hook",title:k,description:`Hook: ${k}`,body:C,bodyHash:$e(C),metadata:{},attachments:[]})}}}catch{}for(let f of er){if(f.path===rs)continue;let g=(0,F.join)(n,f.path);if((0,R.existsSync)(g)){try{let h=JSON.parse((0,R.readFileSync)(g,"utf-8"));if(s=s||h.name||void 0,o=f.formatLabel,!t.some(b=>b.resourceType==="collection")){let b=t.filter(A=>A.resourceType!=="collection").map(A=>({resourceRef:A.importPath})),y=f.converter(h,b),S=(0,F.join)(n,"README.md"),k=(0,R.existsSync)(S)?(0,R.readFileSync)(S,"utf-8"):"",C="collections/_root";t.push({importPath:C,resourceType:"collection",title:fe(y.name),description:y.description||null,body:k,bodyHash:$e(k),metadata:{},attachments:[],manifestMetadata:{...y.author?{author:y.author}:{},...y.homepage?{homepage:y.homepage}:{},...y.license?{license:y.license}:{}}}),y.resources.length>0&&r.push({collectionImportPath:C,memberImportPaths:y.resources})}}catch{}break}}{let h=function(b,y,S){if(!(S>4))for(let k of ss(b)){if(g.has(k))continue;let C=(0,F.join)(b,k),A=y?`${y}/${k}`:k;for(let O of er){if(O.path===rs)continue;let v=(0,F.join)(C,O.path);if((0,R.existsSync)(v)){if(f.has(A))break;f.add(A);try{let P=JSON.parse((0,R.readFileSync)(v,"utf-8")),I=a(C,A);if(I.resources.length===0)break;t.push(...I.resources),r.push(...I.memberships);let J=I.resources.filter(ae=>ae.resourceType!=="collection").map(ae=>({resourceRef:ae.importPath})),H=O.converter(P,J),W=(0,F.join)(C,"README.md"),D=(0,R.existsSync)(W)?(0,R.readFileSync)(W,"utf-8"):"",Oe=`${A}/_collection`;t.push({importPath:Oe,resourceType:"collection",title:fe(H.name),description:H.description||null,body:D,bodyHash:$e(D),metadata:{},attachments:[],manifestMetadata:{...H.author?{author:H.author}:{},...H.homepage?{homepage:H.homepage}:{},...H.license?{license:H.license}:{}}}),r.push({collectionImportPath:Oe,memberImportPaths:I.resources.map(ae=>ae.importPath)}),s||(s=P.name||void 0),o||(o=O.formatLabel)}catch{}break}}h(C,A,S+1)}};var d=h;let f=new Set,g=new Set(ts.map(b=>b.folder));h(n,"",0)}let u=(0,F.join)(n,"files");if((0,R.existsSync)(u)&&Le(u)&&!t.some(f=>f.resourceType==="file"))for(let f of ht(u)){if(!f.endsWith(".md"))continue;let g=(0,F.join)(u,f),h=(0,R.readFileSync)(g,"utf-8"),b=Ge(h),y=b.name||(0,F.basename)(f,".md"),S=`files/${(0,F.basename)(f,".md")}`;t.some(k=>k.importPath===S)||t.push({importPath:S,resourceType:"file",title:y,description:b.description||null,body:b.body,bodyHash:$e(h),metadata:{},attachments:[]})}return{resources:[...t.filter(f=>f.resourceType!=="collection"),...t.filter(f=>f.resourceType==="collection")],collectionMemberships:r,pluginName:s,formatLabel:o}}function ao(){if(process.platform==="darwin")try{let{execSync:n}=require("child_process"),e=n("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var We="resource-manager",os="Resource Manager",tr="collections/shared-context/essentials";function co(n,e){let t=T(n,e),r=(0,Je.join)(t,We);return(0,gt.mkdirSync)(r,{recursive:!0}),(0,gt.writeFileSync)((0,Je.join)(r,"SKILL.md"),Zr,"utf-8"),(0,Je.join)(r,"SKILL.md")}var lo={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function as(n){n.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let r={...e,...t.optsWithGlobals()};if(r.code){let{post:u}=await Promise.resolve().then(()=>(z(),Gr)),{saveAuth:p}=await Promise.resolve().then(()=>(te(),Yt)),d=await u("/api/cli/auth",{code:r.code});d.ok?(p({token:d.data.token,email:d.data.user.email,orgId:d.data.org.id,orgSlug:d.data.org.slug,orgName:d.data.org.name,createdAt:new Date().toISOString()}),w()||m(`Authenticated as ${d.data.user.email}`)):N()?w()||m("Auth code already used, continuing with saved credentials."):(w()?_("init",d.error.code,d.error.message):x(`Auth failed: ${d.error.message}`),process.exit(1))}else N()||(w()?(_("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(x("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(r.agent){let u=ue(r.agent);if(!u){let p=`Unknown agent: ${r.agent}. Available: ${Fe().map(d=>d.id).join(", ")||"none detected"}`;w()?_("init","NO_AGENTS",p):x(p),process.exit(1)}s=[u]}else if(s=Fe(),s.length===0){let u=pe();w()?_("init","NO_AGENTS",u):x(u),process.exit(1)}let o=ie(),a=ao(),i;if(r.linkProject){if(!o?.token){let S="Authentication required for project linking. Run init with --code first.";w()?_("init","AUTH_REQUIRED",S):x(S),process.exit(1)}let u=s[0],p=await j("/api/cli/register-agent",{platform:u.platform,name:`CLI (${a})`});p.ok&&(i=p.data.connectionId);let d=await j(`/api/cli/projects/${r.linkProject}/join`,{localPath:process.cwd()});d.ok||(w()?_("init",d.error.code,d.error.message):x(`Failed to join project: ${d.error.message}`),process.exit(1));let{project:f,resources:g,members:h}=d.data;Kr({projectId:f.id,projectName:f.name,projectSlug:f.slug});let b=ge(u),y=[];for(let S of g)try{let k=S.installPath,C=await L(`/api/cli/resource/${k}`);if(!C.ok)continue;let A=C.data;await b.install(A,"project",u),ee({resourceId:S.id,slug:S.slug||S.id,installPath:k,title:S.title,sha:S.latestSha||"",scope:"project",agent:u.id,installedAt:new Date().toISOString(),projectId:f.id}),S.latestSha&&await j("/api/cli/install",{resourceId:S.id,agentPlatform:u.platform,installedSha:S.latestSha}).catch(()=>{}),y.push({title:S.title,resourceType:S.resourceType})}catch{}if(await j(`/api/cli/projects/${f.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Ie({lastSyncAt:new Date().toISOString(),lastResult:{updatesAvailable:0,untrackedResources:0}}),w())E("init",{project:{id:f.id,name:f.name,slug:f.slug},agent:u.id,resourcesInstalled:y.length,memberCount:h.length});else{if(m(""),m(`Joined project: ${f.name}`),f.description&&m(`"${f.description}"`),m(""),y.length>0){m(`Installed ${y.length} resource${y.length===1?"":"s"}:`);let S={};for(let C of y)S[C.resourceType]||(S[C.resourceType]=[]),S[C.resourceType].push(C.title);let k={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[C,A]of Object.entries(S))m(` ${k[C]||C}: ${A.join(", ")}`)}else m("No resources to install (project is empty)");h.length>0&&(m(""),m(`Team (${h.length}): ${h.map(S=>S.name).join(", ")}`)),m(""),m("Quick reference:"),m(" shared-context-ai status View project sync status"),m(" shared-context-ai sync Check for resource updates")}return}let c=[],l={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let u of s){let p=!1,d=[],f=[];if(o?.token){let g=await j("/api/cli/register-agent",{platform:u.platform,name:`CLI (${a})`});if(g.ok){if(!i){i=g.data.connectionId;let{saveAuth:h}=await Promise.resolve().then(()=>(te(),Yt));h({...o,connectionId:i})}}else w()||x(`Warning: Could not register ${u.label} connection: ${g.error.message}`)}if(o?.token)try{let g=await L(`/api/cli/resource/${tr}`);if(g.ok){let h=g.data,y=await ge(u).install(h,r.project?"project":"user",u);if(ee({resourceId:h.resource.id,slug:h.resource.slug||"essentials",installPath:tr,title:h.resource.title,sha:h.resource.latestSha||"",scope:r.project?"project":"global",agent:u.id,installedAt:new Date().toISOString(),pluginFormat:l[u.id]||"directory",memberCount:h.memberResources?.length}),h.resource.latestSha&&await j("/api/cli/install",{resourceId:h.resource.id,agentPlatform:u.platform,installedSha:h.resource.latestSha}).catch(()=>{}),h.memberResources)for(let S of h.memberResources){let k=S.slug||S.id,C=lo[S.resourceType]||S.resourceType+"s",A=S.orgSlug||h.resource.orgSlug,O=A?`${C}/${A}/${k}`:`${C}/${k}`;ee({resourceId:S.id,slug:k,installPath:O,title:S.title,sha:S.latestSha||"",scope:r.project?"project":"global",agent:u.id,installedAt:new Date().toISOString(),collectionId:h.resource.id}),d.push({title:S.title,resourceType:S.resourceType}),S.latestSha&&await j("/api/cli/install",{resourceId:S.id,agentPlatform:u.platform,installedSha:S.latestSha}).catch(()=>{})}if(p=!0,!w()&&y.warnings.length>0)for(let S of y.warnings)x(`Warning: ${S}`)}}catch{}if(!p&&(co(u,!!r.project),ee({resourceId:"resource-manager",slug:We,installPath:`skills/${We}`,title:os,sha:"",scope:r.project?"project":"global",agent:u.id,installedAt:new Date().toISOString()}),o?.token))try{let g=`skills/shared-context/${We}`,h=await L(`/api/cli/resource/${g}`);if(h.ok&&h.data.resource){let b=h.data.resource;b.latestSha&&await j("/api/cli/install",{resourceId:b.id,agentPlatform:u.platform,installedSha:b.latestSha}),ee({resourceId:b.id,slug:b.slug||We,installPath:`skills/shared-context/${b.slug||We}`,title:b.title||os,sha:b.latestSha||"",scope:r.project?"project":"global",agent:u.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let g=(0,Je.join)((0,is.homedir)(),u.dir),h=He(g,{settingsPath:X(u,!!r.project),mcpConfigPath:V(u,!!r.project)}),b=Y(),y=new Set(b.installations.map(A=>A.installPath)),S=new Map;for(let A of b.installations){let O=A.installPath.split("/"),v=O[0],P=O[O.length-1];S.has(v)||S.set(v,new Set),S.get(v).add(P)}let k=new Set(["resource-manager",".claude-plugin"]),C=h.resources.filter(A=>{if(y.has(A.importPath))return!1;let O=A.importPath.split("/"),v=O[0],P=O[O.length-1];return!((v==="mcps"||v==="hooks")&&S.get(v)?.has(P)||A.importPath.startsWith(".")||k.has(P))});if(C.length>0){let A={dryRun:!1,onConflict:"auto",visibility:"org",resources:C,collectionMemberships:h.collectionMemberships},O=await j("/api/cli/import",A,12e4);O.ok&&(f=[...O.data.created,...O.data.updated,...O.data.installed].map(P=>({resourceType:P.resourceType||P.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:P.slug||P.importPath.split("/").pop()||"",title:P.importPath.split("/").pop()||""})))}}catch{}c.push({agent:u,collectionInstalled:p,installedMembers:d,importedResources:f})}if(Ie({lastSyncAt:new Date().toISOString(),lastResult:{updatesAvailable:0,untrackedResources:0}}),i){let u=c.reduce((p,d)=>p+d.importedResources.length,0);j("/api/cli/sync-report",{connectionId:i,lastSyncResult:{updatesAvailable:0,importedCount:u}}).catch(()=>{})}if(w()){let u=p=>({agent:p.agent.id,collection:p.collectionInstalled?tr:void 0,resourceManagerOnly:!p.collectionInstalled,...p.collectionInstalled?{membersInstalled:p.installedMembers.map(d=>({title:d.title,resourceType:d.resourceType}))}:{},...p.importedResources.length>0?{importedResources:p.importedResources.map(d=>({resourceType:d.resourceType,slug:d.slug,title:d.title}))}:{}});E("init",{...u(c[0]),agents:c.map(u),authenticated:N()})}else{for(let u of c){if(m(""),u.collectionInstalled){m(`Shared Context Essentials installed for ${u.agent.label} (${u.installedMembers.length} resources)`);let p={};for(let f of u.installedMembers)p[f.resourceType]||(p[f.resourceType]=[]),p[f.resourceType].push(f.title);let d={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};m("");for(let[f,g]of Object.entries(p)){let h=d[f]||f;m(` ${h}: ${g.join(", ")}`)}}else m(`Shared Context initialized for ${u.agent.label}`),m("Resource Manager installed");if(u.importedResources.length>0){m(""),m(`Imported ${u.importedResources.length} existing resource${u.importedResources.length===1?"":"s"}:`);for(let p of u.importedResources)m(` ${p.resourceType.padEnd(12)} ${p.slug.padEnd(24)} ${p.title}`)}}m(""),m("Quick reference:"),m(' shared-context-ai search "query" Search for resources'),m(" shared-context-ai install <installPath> Install a resource"),m(" shared-context-ai list List installed resources"),m(" shared-context-ai sync Check updates & discover resources"),m(" shared-context-ai preview <installPath> Preview before installing")}})}var Ns=require("http"),Ms=require("crypto");te();z();te();async function Ls(n){let e=await j("/api/cli/auth",{code:n});return e.ok?(Bt({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()}),w()?E("login",{email:e.data.user.email,org:e.data.org.slug}):m(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(w()?_("login",e.error.code,e.error.message):x(`Login failed: ${e.error.message}`),!1)}async function vo(){let n=(0,Ms.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,Ns.createServer)((r,s)=>{let o=new URL(r.url||"/","http://localhost"),a=o.searchParams.get("code"),i=o.searchParams.get("state");if(!a||i!==n){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),Ls(a).then(e)});t.listen(0,"127.0.0.1",async()=>{let r=t.address();if(!r||typeof r=="string"){t.close(),e(!1);return}let s=r.port,a=`${Se().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${n}`;w()||(m("Opening browser for authentication..."),m(`If the browser doesn't open, visit: ${a}`));try{let i=(await Promise.resolve().then(()=>(Ds(),Fs))).default;await i(a)}catch{w()||m(`Could not open browser. Please visit:
195
+ ${a}`)}setTimeout(()=>{t.close(),w()||x("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function Hs(n){n.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await Ls(e.code):t=await vo(),process.exit(t?0:1)})}z();var Po={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ws(n){let e=Po[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${e}/external/${n.githubOwner}/${n.slug}`:n.orgSlug?`${e}/${n.orgSlug}/${n.slug}`:`${e}/${n.slug}`}function Us(n){n.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let r=new URLSearchParams({q:e});t.type&&r.set("type",t.type),t.tag&&r.set("tag",t.tag),t.limit&&r.set("limit",t.limit);let s=N()?`/api/cli/search?${r}`:`/api/public/search?${r}`,o=await L(s);o.ok||(w()?_("search",o.error.code,o.error.message):m(`Search failed: ${o.error.message}`),process.exit(1));let a=o.data.results;if(w()){let c=a.map(l=>{let u=Ws(l);return{installPath:u,installCommand:`npx shared-context-ai install ${u}`,title:l.title,description:l.description,resourceType:l.resourceType,installCount:l.installCount,topicTags:l.topicTags}});E("search",{results:c,count:c.length});return}if(a.length===0){let c=t.type?`${t.type}s`:"results";m(`No ${c} found.`);return}m(`Found ${a.length} result${a.length===1?"":"s"}:
196
+ `);let i=a.map(c=>[Ws(c),c.title,`\u2193${c.installCount}`]);m(se(i)),m(`
197
+ Install a skill: npx shared-context-ai install <installPath>`)})}z();te();function Vs(n){let e=n.slug||n.resourceId;return n.storageType==="github"&&n.githubOwner?`skills/external/${n.githubOwner}/${e}`:n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function Bs(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if(N()){let e=await L("/api/cli/installed");e.ok||(w()?_("list",e.error.code,e.error.message):m(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(w()){let s=t.map(o=>({...o,installPath:Vs(o)}));E("list",{installations:s,count:s.length});return}if(t.length===0){m("No skills installed."),m("Use 'shared-context-ai search' to find skills to install.");return}m(`${t.length} skill${t.length===1?"":"s"} installed:
198
+ `);let r=t.map(s=>[Vs(s),s.title,s.hasUpdate?"(update available)":"(current)"]);m(se(r))}else{let t=Y().installations;if(w()){E("list",{installations:t,count:t.length});return}if(t.length===0){m("No skills installed locally.");return}m(`${t.length} skill${t.length===1?"":"s"} installed locally:
199
+ `);let r=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);m(se(r)),m(`
200
+ Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}z();function qs(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let r=N()?"/api/cli/resource":"/api/public/resource",s=await L(`${r}/${e}/preview`);s.ok||(w()?_("preview",s.error.code,s.error.message):x(`Preview failed: ${s.error.message}`),process.exit(1)),w()?E("preview",s.data):m(s.data.content)})}z();function Gs(n){n.command("check").description("Check for skill updates").action(async()=>{N()||(w()?_("check","AUTH_MISSING","Login required to check for updates."):x("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await L("/api/cli/updates");e.ok||(w()?_("check",e.error.code,e.error.message):x(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:r}=e.data;if(w()){E("check",{updates:t,count:r});return}if(r===0){m("All skills are up to date.");return}m(`${r} update${r===1?"":"s"} available:
201
+ `);let s=t.map(o=>{let a=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${a}`:o.orgSlug?`skills/${o.orgSlug}/${a}`:`skills/${a}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});m(se(s)),m(`
202
+ Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var Cr=require("path");z();te();var Eo={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Js(n){let e=n.slug||n.resourceId,t=Eo[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${t}/external/${n.githubOwner}/${e}`:n.orgSlug?`${t}/${n.orgSlug}/${e}`:`${t}/${e}`}function Ys(n){n.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,r)=>{let s=r.optsWithGlobals();N()||(w()?_("update","AUTH_MISSING","Login required to update resources."):x("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=ue(s.agent);if(!o){let l=pe();w()?_("update","NO_AGENTS",l):x(l),process.exit(1)}let a=await L("/api/cli/updates");a.ok||(w()?_("update",a.error.code,a.error.message):x(`Failed to check updates: ${a.error.message}`),process.exit(1));let i=a.data.updates;if(e&&(i=i.filter(l=>Js(l)===e||l.slug===e||l.resourceId===e),i.length===0)){w()?_("update","SKILL_NOT_FOUND",`No update available for "${e}".`):m(`No update available for "${e}".`);return}if(i.length===0){w()?E("update",{updated:[],count:0}):m("All resources are up to date.");return}let c=[];for(let l of i){let u=Js(l),p=await L(`/api/cli/resource/${u}`);if(!p.ok){w()||x(` Failed to fetch ${u}: ${p.error.message}`);continue}let d=p.data,f=u.split("/").slice(1);if(d.resource.resourceType==="agent"){let g=G(o,!!s.project),h=(0,Cr.join)(g,...f);M(h,d.files)}else if(d.resource.resourceType==="mcp")Xt(o,!!s.project,d);else{let g=T(o,!!s.project),h=(0,Cr.join)(g,...f);M(h,d.files)}d.resource.latestSha&&await j("/api/cli/update",{resourceId:d.resource.id,installedSha:d.resource.latestSha}),ee({resourceId:d.resource.id,slug:d.resource.slug||d.resource.id,installPath:u,title:d.resource.title,sha:d.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString()}),c.push({installPath:u,title:d.resource.title}),w()||m(` Updated ${u}`)}w()?E("update",{updated:c,count:c.length}):c.length>0&&m(`
203
+ ${c.length} resource${c.length===1?"":"s"} updated.`)})}var U=require("fs"),Ve=require("path");z();te();function Ks(n){n.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{if(!e){let g=Y().installations;if(g.length===0&&(w()?_("uninstall","NOTHING_INSTALLED","No resources installed."):m("No resources installed."),process.exit(0)),w())E("uninstall",{installations:g.map(h=>({path:h.installPath||h.slug,title:h.title,agent:h.agent}))});else{m(`Installed resources:
204
+ `);let h=g.map(b=>[b.installPath||b.slug,b.title||"",`(${b.agent})`]);m(se(h)),m(`
205
+ Usage: shared-context-ai uninstall <path>`)}return}let s=r.optsWithGlobals(),o=ue(s.agent);if(!o){let f=pe();w()?_("uninstall","NO_AGENTS",f):x(f),process.exit(1)}let i=Y().installations.find(f=>f.installPath===e||f.slug===e||f.resourceId===e),c=e.split("/"),u=["skills","files","commands","hooks","collections","agents","mcps"].includes(c[0])?c[0]:null,p=u?c.slice(1):c,d=!1;if(u==="collections"){let f=ge(o),g=p[p.length-1],h=s.project?"project":"user",b=await f.uninstall(g,h,o,i?.resourceId);if(d=b.removed,!w())for(let y of b.warnings)x(`Warning: ${y}`);if(i){let S=Y().installations.filter(k=>k.collectionId===i.resourceId&&k.agent===o.id);for(let k of S){let C=k.installPath.split("/"),A=C[0],O=C.slice(1);if(A==="agents"){let v=G(o,!!s.project),P=(0,Ve.join)(v,...O);(0,U.existsSync)(P)&&(0,U.rmSync)(P,{recursive:!0,force:!0})}else if(A==="mcps"){let v=O[O.length-1],P=V(o,!!s.project);if((0,U.existsSync)(P))try{let I=JSON.parse((0,U.readFileSync)(P,"utf-8"));if(typeof I.mcpServers=="object"&&I.mcpServers&&!Array.isArray(I.mcpServers)){let J=I.mcpServers;v in J&&(delete J[v],I.mcpServers=J,(0,U.writeFileSync)(P,JSON.stringify(I,null,2)+`
206
+ `,"utf-8"))}}catch{}}else if(A==="hooks")Zt(X(o,!!s.project),k.installPath);else{let v=T(o,!!s.project),P=(0,Ve.join)(v,...O);(0,U.existsSync)(P)&&(0,U.rmSync)(P,{recursive:!0,force:!0})}rt(k.resourceId,o.id)}}}else if(u==="agents"){let f=G(o,!!s.project),g=(0,Ve.join)(f,...p);d=(0,U.existsSync)(g),d&&(0,U.rmSync)(g,{recursive:!0,force:!0})}else if(u==="mcps"){let f=p[p.length-1],g=V(o,!!s.project);if((0,U.existsSync)(g))try{let h=JSON.parse((0,U.readFileSync)(g,"utf-8"));if(typeof h.mcpServers=="object"&&h.mcpServers&&!Array.isArray(h.mcpServers)){let b=h.mcpServers;f in b&&(delete b[f],h.mcpServers=b,(0,U.writeFileSync)(g,JSON.stringify(h,null,2)+`
207
+ `,"utf-8"),d=!0)}}catch{}}else if(u==="hooks"){let f=X(o,!!s.project);d=Zt(f,e),!d&&!w()&&x(`Note: No tagged hook entries found in ${f} \u2014 may need manual removal if installed before v0.1.10`)}else{let f=T(o,!!s.project),g=(0,Ve.join)(f,...p);if(d=(0,U.existsSync)(g),d&&(0,U.rmSync)(g,{recursive:!0,force:!0}),!d&&i?.slug){let h=(0,Ve.join)(f,i.slug);(0,U.existsSync)(h)&&(0,U.rmSync)(h,{recursive:!0,force:!0})}}if(N()&&i){let f=await j("/api/cli/uninstall",{resourceId:i.resourceId});!f.ok&&!w()&&x(`Warning: Could not record uninstall on server: ${f.error.message}`)}i&&rt(i.resourceId,o.id),w()?E("uninstall",{path:e,removed:!0}):m(`Uninstalled "${e}"`)})}te();z();function zs(n){n.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=ie(),t=Se(),r=Y(),s=Fe(),o=De(),a=r.installations.filter(p=>!p.projectId),i=r.installations.filter(p=>p.projectId),c=new Map;for(let p of i){let d=p.projectId;c.has(d)||c.set(d,[]),c.get(d).push(p)}let l=[];if(N()&&c.size>0)for(let[p,d]of c){let f=await L(`/api/cli/projects/${p}/resources`).catch(()=>null),g=f&&f.ok?f.data.resources.length:d.length,h=o?.projectId===p?o.projectName:`Project ${p.slice(0,8)}`;l.push({projectId:p,projectName:h,localCount:d.length,serverCount:g,synced:d.length>=g})}let u={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(p=>p.id),installedCount:r.installations.length,globalCount:a.length,projects:l};if(w()){E("status",u);return}if(m("Shared Context CLI Status"),m("\u2500".repeat(40)),e?.token?m(` Auth: ${e.email} (${e.orgSlug})`):m(" Auth: Not logged in"),m(` API: ${t.apiBase}`),s.length>0?m(` Agents: ${s.map(p=>p.label).join(", ")}`):m(" Agents: None detected"),m(` Global: ${a.length} resource${a.length===1?"":"s"} installed`),l.length>0){m(""),m("Projects:");for(let p of l){let d=p.synced?"\u2713 synced":`\u26A0 ${p.serverCount-p.localCount} new`;m(` ${p.projectName}: ${p.localCount}/${p.serverCount} resources (${d})`)}}else o&&(m(""),m(` Project: ${o.projectName} (linked)`))})}te();z();function Xs(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=ie();e.revoke&&N()&&await Kt("/api/cli/auth"),qt(),w()?E("logout",{email:t?.email||null}):m("Logged out.")})}var Ct=require("fs"),Qs=require("path");z();function Zs(n){n.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,r)=>{let s=r.optsWithGlobals(),o=t.github;if(o&&e&&(w()?_("import","INVALID_ARGS","Cannot use --github with a local path"):x("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(w()?_("import","INVALID_ARGS","Provide a local path or --github <url>"):x("Error: Provide a local path or --github <url>"),process.exit(1)),N()||(w()?_("import","AUTH_MISSING","Authentication required for import"):x("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(w()?_("import","INVALID_ARGS","--on-conflict is not supported with --github"):x("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(w()?_("import","INVALID_ARGS","--dry-run is not supported with --github"):x("Error: --dry-run is not supported with --github"),process.exit(1));let g={url:o};t.resourceType&&(g.resourceType=t.resourceType),w()||m(`
208
+ Importing from GitHub: ${o}`);let h=await j("/api/cli/github-import",g);h.ok||(w()?_("import",h.error.code,h.error.message):x(`
209
+ Import failed: ${h.error.message}`),process.exit(1));let b=h.data;if(w()){E("import",b);return}m(""),m(` Source: ${b.source.owner}/${b.source.repo}`),m(` Type: ${b.resourceType}`),m(` Title: ${b.title}`),b.slug&&m(` Slug: ${b.slug}`),m(` URL: ${b.url}`),m(""),m("Import complete: 1 created");return}let a=(0,Qs.resolve)(e);(!(0,Ct.existsSync)(a)||!(0,Ct.statSync)(a).isDirectory())&&(w()?_("import","INVALID_PATH",`Not a directory: ${a}`):x(`Error: Not a directory: ${a}`),process.exit(1));let i=He(a);if(i.resources.length===0){w()?E("import",{resources:[],message:"No resources found"}):m("No resources found in the specified directory.");return}if(!w()){let g=new Map;for(let b of i.resources)g.set(b.resourceType,(g.get(b.resourceType)||0)+1);let h=[...g.entries()].map(([b,y])=>`${y} ${b}${y===1?"":"s"}`).join(", ");m(`
210
+ Discovered ${i.resources.length} resources in ${e}:`),m(` ${h}`),i.formatLabel&&i.pluginName?m(` ${i.formatLabel}: ${i.pluginName}`):i.pluginName&&m(` Plugin: ${i.pluginName}`)}let c=t.tags?t.tags.split(",").map(g=>g.trim()).filter(Boolean):void 0,l={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:c,resources:i.resources,collectionMemberships:i.collectionMemberships.length>0?i.collectionMemberships:void 0};!w()&&!t.dryRun?m(`
211
+ Executing import...`):w()||m(`
212
+ Dry run \u2014 previewing changes...`);let u=await j("/api/cli/import",l,12e4);u.ok||(w()?_("import",u.error.code,u.error.message):x(`
213
+ Import failed: ${u.error.message}`),process.exit(1));let p=u.data;if(w()){E("import",p);return}let d=[...p.created.map(g=>({...g,action:"created"})),...p.updated.map(g=>({...g,action:"updated"})),...p.installed.map(g=>({...g,action:"installed"})),...p.cloned.map(g=>({...g,action:"cloned"})),...p.skipped.map(g=>({...g,action:"skipped"})),...p.errors.map(g=>({...g,action:"error"}))];if(d.length>0){m("");let g=d.length,h=d.map((b,y)=>{let S=`[${String(y+1).padStart(String(g).length)}/${g}]`,k=(b.resourceType||"").padEnd(10),C=(b.importPath.split("/").pop()||"").padEnd(24),A="";switch(b.action){case"created":A=`\u2713 created${b.slug?` (slug: ${b.slug})`:""}`;break;case"updated":A="\u2713 updated";break;case"installed":{let O=b.versionsBehind;A=`\u2713 installed${O?` (${O} versions behind)`:""}`;break}case"cloned":A=`\u2713 cloned${b.slug?` (slug: ${b.slug})`:""}`;break;case"skipped":A=`\u2713 skipped (${b.reason||"up to date"})`;break;case"error":A=`\u2717 error: ${b.error||"unknown"}`;break}return` ${S} ${k} ${C} ${A}`});for(let b of h)m(b)}if(p.collections.length>0)for(let g of p.collections){let h=g.importPath.split("/").pop()||g.importPath;m(` collection ${h.padEnd(20)} \u2713 ${g.membersLinked} members linked${g.membersFailed>0?`, ${g.membersFailed} failed`:""}`)}m("");let f=[p.created.length>0?`${p.created.length} created`:null,p.installed.length>0?`${p.installed.length} installed`:null,p.cloned.length>0?`${p.cloned.length} cloned`:null,p.updated.length>0?`${p.updated.length} updated`:null,p.skipped.length>0?`${p.skipped.length} skipped`:null,p.errors.length>0?`${p.errors.length} errors`:null].filter(Boolean);t.dryRun?m(`Dry run complete: ${f.join(", ")}`):m(`Import complete: ${f.join(", ")}`),p.errors.length>0&&process.exit(1)})}var rn=require("path"),sn=require("os");z();te();function nn(n){n.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").action(async(e,t)=>{let r={...e,...t.optsWithGlobals()};if(!r.force&&!Jt()){let A=st();if(A){let O={...A.lastResult,updates:[],untracked:[],summary:en(A.lastResult.updatesAvailable,A.lastResult.untrackedResources),throttled:!0};tn(O,!!r.quiet);return}}N()||(w()?_("sync","AUTH_MISSING","Login required to sync."):x("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=ue(r.agent);if(!s){let A=pe();w()?_("sync","NO_AGENTS",A):x(A),process.exit(1)}let o=[],a=await L("/api/cli/updates");a.ok&&(o=a.data.updates);let i=(0,rn.join)((0,sn.homedir)(),s.dir),c=He(i,{settingsPath:X(s,!!r.project),mcpConfigPath:V(s,!!r.project)}),l=Y(),u=new Set(l.installations.map(A=>A.installPath)),p=new Map;for(let A of l.installations){let O=A.installPath.split("/"),v=O[0],P=O[O.length-1];p.has(v)||p.set(v,new Set),p.get(v).add(P)}let d=new Set(["resource-manager",".claude-plugin"]),f=c.resources.filter(A=>{if(u.has(A.importPath))return!1;let O=A.importPath.split("/"),v=O[0],P=O[O.length-1];return!((v==="mcps"||v==="hooks")&&p.get(v)?.has(P)||A.importPath.startsWith(".")||d.has(P))}),g=f.length;if(r.import!==!1&&f.length>0){let A={dryRun:!1,onConflict:"auto",visibility:"org",resources:f,collectionMemberships:c.collectionMemberships},O=await j("/api/cli/import",A,12e4);if(O.ok){let v=[...O.data.created,...O.data.updated,...O.data.installed];if(!w()&&!r.quiet){if(v.length>0){m(`
214
+ Imported ${v.length} resource${v.length===1?"":"s"}:`);let P=v.map(I=>[` ${(I.resourceType||"").padEnd(12)}`,(I.slug||I.importPath.split("/").pop()||"").padEnd(24),I.importPath]);m(se(P))}O.data.errors.length>0&&x(`
215
+ ${O.data.errors.length} import error(s)`)}f.length=0}else w()||x(`Import failed: ${O.error.message}`)}let h=De(),b=0;if(h){let A=await L(`/api/cli/projects/${h.projectId}/resources`);if(!A.ok)!w()&&!r.quiet&&(x(`Warning: Project "${h.projectName}" not found on server (may have been deleted).`),x(" Remove .shared-context/project.json to unlink this directory."));else if(A.ok){let O=A.data.resources,P=Y().installations.filter(H=>H.projectId===h.projectId),I=new Set(P.map(H=>H.resourceId)),J=O.filter(H=>!I.has(H.id));if(J.length>0){let H=ge(s);for(let W of J){let D=W.installPath;try{let Oe=await L(`/api/cli/resource/${D}`);if(!Oe.ok)continue;await H.install(Oe.data,"project",s),ee({resourceId:W.id,slug:W.slug||W.id,installPath:D,title:W.title,sha:W.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:h.projectId}),W.latestSha&&await j("/api/cli/install",{resourceId:W.id,agentPlatform:s.platform,installedSha:W.latestSha}).catch(()=>{}),b++}catch{}}!w()&&!r.quiet&&b>0&&m(`
216
+ Project "${h.projectName}": installed ${b} new resource${b===1?"":"s"}`)}await j(`/api/cli/projects/${h.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let y=g-f.length,S={updatesAvailable:o.length,untrackedResources:f.length};Ie({lastSyncAt:new Date().toISOString(),lastResult:S});let k=ie();k?.connectionId&&j("/api/cli/sync-report",{connectionId:k.connectionId,lastSyncResult:{updatesAvailable:o.length,importedCount:y}}).catch(()=>{});let C={...S,updates:o,untracked:f.map(A=>({importPath:A.importPath,resourceType:A.resourceType,title:A.title})),summary:en(o.length,f.length),throttled:!1};tn(C,!!r.quiet)})}function en(n,e){let t=[];return n>0&&t.push(`${n} update${n===1?"":"s"} available`),e>0&&t.push(`${e} untracked resource${e===1?"":"s"}`),t.length===0?"Everything is up to date.":t.join(", ")}function tn(n,e){if(w()){E("sync",n);return}if(e){let t=n.summary;n.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),n.untrackedResources>0&&(t+=` \u2014 ${n.untrackedResources} untracked`),m(t);return}if(m(""),n.updates.length>0){m(`${n.updates.length} update${n.updates.length===1?"":"s"} available:
217
+ `);let t=n.updates.map(r=>{let s=r.slug||r.resourceId,o=r.resourceType==="skill"?"skills":`${r.resourceType}s`;return[` ${r.storageType==="github"&&r.githubOwner?`${o}/external/${r.githubOwner}/${s}`:r.orgSlug?`${o}/${r.orgSlug}/${s}`:`${o}/${s}`}`,r.title,`${r.installedSha.slice(0,7)} \u2192 ${r.latestSha.slice(0,7)}`]});m(se(t)),m("")}if(n.untracked.length>0){m(`${n.untracked.length} untracked resource${n.untracked.length===1?"":"s"}:
218
+ `);let t=n.untracked.map(r=>[` ${r.resourceType.padEnd(12)}`,r.importPath.padEnd(30),r.title]);m(se(t)),m("")}n.updatesAvailable===0&&n.untrackedResources===0?m("Everything is up to date."):(n.updatesAvailable>0&&m("Run 'shared-context-ai update' to update installed resources."),n.untrackedResources>0&&m("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),m("")}var on={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."},kt=class extends Error{constructor(t,r){super(r||on[t]);this.code=t;this.name="CliError"}get recovery(){return on[this.code]}};var Z=new Dr;Z.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();Lr(!!e.json,!!e.human)});as(Z);Hs(Z);Us(Z);Qr(Z);Bs(Z);qs(Z);Gs(Z);Ys(Z);Ks(Z);zs(Z);Xs(Z);Zs(Z);nn(Z);process.on("uncaughtException",n=>{n instanceof kt?w()?_(process.argv[2]||"unknown",n.code,n.message):(x(`Error: ${n.message}`),x(n.recovery)):w()?_(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):x(`Error: ${n.message||n}`),process.exit(1)});Z.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shared-context-ai",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "CLI for Shared Context - search, install, and manage AI skills",
5
5
  "bin": {
6
6
  "shared-context-ai": "dist/index.js"