shared-context-ai 0.1.10 → 0.1.11

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 +48 -47
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,40 +1,41 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Xs=Object.create;var bt=Object.defineProperty;var Qs=Object.getOwnPropertyDescriptor;var Zs=Object.getOwnPropertyNames;var en=Object.getPrototypeOf,tn=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})},rn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zs(e))!tn.call(n,s)&&s!==t&&bt(n,s,{get:()=>e[s],enumerable:!(r=Qs(e,s))||r.enumerable});return n};var B=(n,e,t)=>(t=n!=null?Xs(en(n)):{},rn(e||!n||!n.__esModule?bt(t,"default",{value:n,enumerable:!0}):t,n));var Me=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:sn}=Me(),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 sn(`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 nn(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Ct.Argument=xt;Ct.humanReadableArgName=nn});var _t=xe(Ot=>{"use strict";var{humanReadableArgName:on}=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=>on(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 o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(a),s),""]));let l=t.visibleArguments(e).map(u=>i(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));l.length>0&&(o=o.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&&(o=o.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&&(o=o.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&&(o=o.concat([t.styleTitle("Commands:"),...p,""])),o.join(`
3
- `)}displayWidth(e){return gr(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 o=" ".repeat(2);if(!r)return o+e;let a=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)),o+a+" ".repeat(l)+u.replace(/\n/g,`
5
- ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,i=[];return r.forEach(o=>{let a=o.match(s);if(a===null){i.push("");return}let l=[a.shift()],c=this.displayWidth(l[0]);a.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 gr(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}Ot.Help=kt;Ot.stripColor=gr});var $t=xe(Pt=>{"use strict";var{InvalidArgumentError:an}=Me(),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=cn(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 an(`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?yr(this.name().replace(/^no-/,"")):yr(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},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 yr(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function cn(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 o=i[0],a=`option creation failed due to '${o}' in option flags '${n}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
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}
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(o)?new Error(`${a}
10
- - too many short flags`):s.test(o)?new Error(`${a}
11
- - too many long flags`):new Error(`${a}
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 Sr=xe(br=>{"use strict";function ln(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 un(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=ln(n,o),l=Math.max(n.length,o.length);(l-a)/l>i&&(a<s?(s=a,r=[o]):a===s&&r.push(o))}),r.sort((o,a)=>o.localeCompare(a)),t&&(r=r.map(o=>`--${o}`)),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(`${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?`
13
13
  (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
14
- (Did you mean ${r[0]}?)`:""}br.suggestSimilar=un});var Cr=xe(Ft=>{"use strict";var pn=require("events").EventEmitter,Rt=require("child_process"),me=require("path"),Ye=require("fs"),k=require("process"),{Argument:mn,humanReadableArgName:dn}=Je(),{CommanderError:Tt}=Me(),{Help:hn,stripColor:fn}=_t(),{Option:wr,DualOptions:gn}=$t(),{suggestSimilar:Ar}=Sr(),It=class n extends pn{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=>fn(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[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);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,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new n(e)}createHelp(){return Object.assign(new hn,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 mn(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",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let 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 wr(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{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,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):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,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,r,s,i){if(typeof t=="object"&&t instanceof wr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,c)=>{let p=a.exec(l);return p?p[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}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.
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
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
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 o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let p;try{p=Ye.realpathSync(this._scriptPath)}catch{p=this._scriptPath}a=me.resolve(me.dirname(p),a)}if(a){let p=i(a,o);if(!p&&!e._executableFile&&this._scriptPath){let u=me.basename(this._scriptPath,me.extname(this._scriptPath));u!==this._name&&(p=i(a,`${u}-${e._name}`))}o=p||o}r=s.includes(me.extname(o));let l;k.platform!=="win32"?r?(t.unshift(o),t=xr(k.execArgv).concat(t),l=Rt.spawn(k.argv[0],t,{stdio:"inherit"})):l=Rt.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=xr(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(o,a,e._name);else if(p.code==="EACCES")throw new Error(`'${o}' 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 o=s;if(s!==null&&r.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,a)}return o};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((o,a)=>e(r,a,o),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(o=>{s.push({hookedCommand:i,callback:o})})}),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 o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}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 o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){s===r&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(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&&!o(i[0])&&(p=i.shift()),this.emit(`option:${c.name()}`,p)}else this.emit(`option:${c.name()}`);a=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(o(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(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}
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 gn(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=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(u=>u.negate&&a===u.attributeName()),p=this.options.find(u=>!u.negate&&a===u.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:p||o},s=o=>{let a=r(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.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 o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Ar(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=Ar(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>dn(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=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(r=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),r(a)),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(o=>o.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(o=>o.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 o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
27
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function xr(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 vr=xe(ee=>{"use strict";var{Argument:kr}=Je(),{Command:Dt}=Cr(),{CommanderError:yn,InvalidArgumentError:Or}=Me(),{Help:bn}=_t(),{Option:_r}=$t();ee.program=new Dt;ee.createCommand=n=>new Dt(n);ee.createOption=(n,e)=>new _r(n,e);ee.createArgument=(n,e)=>new kr(n,e);ee.Command=Dt;ee.Option=_r;ee.Argument=kr;ee.Help=bn;ee.CommanderError=yn;ee.InvalidArgumentError=Or;ee.InvalidOptionArgumentError=Or});var Hr={};St(Hr,{addToManifest:()=>ne,clearAuth:()=>Ht,getAuth:()=>oe,getConfig:()=>ge,getManifest:()=>K,getSyncState:()=>Qe,removeFromManifest:()=>Xe,saveAuth:()=>Nt,saveConfig:()=>Mr,saveManifest:()=>Lt,saveSyncState:()=>He,shouldSync:()=>Wt,updateConfig:()=>An});function Ne(){let n=process.env.SC_PROFILE;return n?(0,Ce.join)(Ir,"profiles",n):Ir}function Mt(){return(0,Ce.join)(Ne(),"auth.json")}function Fr(){return(0,Ce.join)(Ne(),"config.json")}function Dr(){return(0,Ce.join)(Ne(),"manifest.json")}function Sn(){(0,se.mkdirSync)(Ne(),{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(Sn(),(0,se.writeFileSync)(n,JSON.stringify(e,null,2)+`
28
- `,"utf-8"),t)try{(0,se.chmodSync)(n,384)}catch{}}function oe(){return Ke(Mt(),null)}function Nt(n){ze(Mt(),n,!0)}function Ht(){try{(0,se.writeFileSync)(Mt(),"{}","utf-8")}catch{}}function ge(){return Ke(Fr(),wn)}function Mr(n){ze(Fr(),n)}function An(n){let e=ge();Mr({...e,...n})}function K(){return Ke(Dr(),xn)}function Lt(n){ze(Dr(),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 Nr(){return(0,Ce.join)(Ne(),"last-sync.json")}function Qe(){return Ke(Nr(),null)}function He(n){ze(Nr(),n)}function Wt(n=Cn){let e=Qe();return e?.lastSyncAt?Date.now()-new Date(e.lastSyncAt).getTime()>=n:!0}var se,Ce,jr,Ir,wn,xn,Cn,Q=X(()=>{"use strict";se=require("fs"),Ce=require("path"),jr=require("os"),Ir=(0,Ce.join)((0,jr.homedir)(),".config","shared-context");wn={apiBase:"https://sharedcontext.ai"};xn={installations:[]};Cn=720*60*1e3});var Lr={};St(Lr,{del:()=>Ut,get:()=>H,isAuthenticated:()=>T,patch:()=>_n,post:()=>F});function kn(){return ge().apiBase||"https://sharedcontext.ai"}function On(){let n={"Content-Type":"application/json"},e=oe();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function T(){return!!oe()?.token}async function Ze(n,e,t,r){let s=`${kn()}${e}`;try{let i={method:n,headers:On(),body:t?JSON.stringify(t):void 0};r&&(i.signal=AbortSignal.timeout(r));let o=await fetch(s,i),a=o.headers.get("content-type")||"";if(!a.includes("application/json"))return o.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${a||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${o.status}`,message:o.statusText}};let l=await o.json();return o.ok?{ok:!0,data:l.data??l}:{ok:!1,error:{code:l?.error?.code||`HTTP_${o.status}`,message:l?.error?.message||l?.message||o.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 _n(n,e){return Ze("PATCH",n,e)}function Ut(n,e){return Ze("DELETE",n,e)}var z=X(()=>{"use strict";Q()});function zn(){try{return zt.default.statSync("/.dockerenv"),!0}catch{return!1}}function Xn(){try{return zt.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Xt(){return Kt===void 0&&(Kt=zn()||Xn()),Kt}var zt,Kt,Zr=X(()=>{"use strict";zt=B(require("fs"),1)});function _e(){return Qt===void 0&&(Qt=Qn()||Xt()),Qt}var es,Qt,Qn,Zt=X(()=>{"use strict";es=B(require("fs"),1);Zr();Qn=()=>{try{return es.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var er,rs,pt,ts,be,tr=X(()=>{"use strict";er=B(require("process"),1),rs=B(require("os"),1),pt=B(require("fs"),1);Zt();ts=()=>{if(er.default.platform!=="linux")return!1;if(rs.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=er.default.env.__IS_WSL_TEST__?ts:ts()});var rr,Ue,Zn,ei,sr,ss=X(()=>{"use strict";rr=B(require("process"),1),Ue=B(require("fs/promises"),1);tr();tr();Zn=(()=>{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}})(),ei=async()=>`${await Zn()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,sr=async()=>be?ei():`${rr.default.env.SYSTEMROOT||rr.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 ns=X(()=>{"use strict"});async function nr(){if(os.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await ti("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 is,os,as,ti,cs=X(()=>{"use strict";is=require("util"),os=B(require("process"),1),as=require("child_process"),ti=(0,is.promisify)(as.execFile)});async function ps(n,{humanReadableOutput:e=!0,signal:t}={}){if(ls.default.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await ri("osascript",["-e",n,r],s);return i.trim()}var ls,us,ir,ri,ms=X(()=>{"use strict";ls=B(require("process"),1),us=require("util"),ir=require("child_process"),ri=(0,us.promisify)(ir.execFile)});async function or(n){return ps(`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 ds=X(()=>{"use strict";ms()});async function cr(n=si){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 ar(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,s=r.lastIndexOf("."),i=r.lastIndexOf("-"),o=s===-1?void 0:r.slice(0,s),a=i===-1?void 0:r.slice(0,i);return mt[r]??mt[o]??mt[a]??{name:r,id:r}}var hs,fs,si,mt,Ho,ar,gs=X(()=>{"use strict";hs=require("util"),fs=require("child_process"),si=(0,hs.promisify)(fs.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"}},Ho=new Map(Object.entries(mt)),ar=class extends Error{}});async function lr(){if(dt.default.platform==="darwin"){let n=await nr();return{name:await or(n),id:n}}if(dt.default.platform==="linux"){let{stdout:n}=await ni("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:ii(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(dt.default.platform==="win32")return cr();throw new Error("Only macOS, Linux, and Windows are supported")}var ys,dt,bs,ni,ii,Ss=X(()=>{"use strict";ys=require("util"),dt=B(require("process"),1),bs=require("child_process");cs();ds();gs();ni=(0,ys.promisify)(bs.execFile),ii=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var _s={};St(_s,{apps:()=>we,default:()=>ui,openApp:()=>li});async function ai(){let n=await sr(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=mr.Buffer.from(e,"utf16le").toString("base64"),{stdout:r}=await oi(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 Cs(n){if(typeof n=="string"||Array.isArray(n))return n;let{[As]:e}=n;if(!e)throw new Error(`${As} is not supported`);return e}function ft({[Fe]:n},{wsl:e}){if(e&&be)return Cs(e);if(!n)throw new Error(`${Fe} is not supported`);return Cs(n)}var pr,mr,dr,ks,Os,hr,ht,pi,oi,ur,ws,Fe,As,xs,Ve,ci,li,we,ui,vs=X(()=>{"use strict";pr=B(require("process"),1),mr=require("buffer"),dr=B(require("path"),1),ks=require("url"),Os=require("util"),hr=B(require("child_process"),1),ht=B(require("fs/promises"),1);ss();ns();Ss();Zt();pi={},oi=(0,Os.promisify)(hr.default.execFile),ur=dr.default.dirname((0,ks.fileURLToPath)(pi.url)),ws=dr.default.join(ur,"xdg-open"),{platform:Fe,arch:As}=pr.default;xs=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 xs(n.app,a=>Ve({...n,app:a}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return xs(e,a=>Ve({...n,app:{name:a,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let a={"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 ai():await lr();if(c.id in a){let p=a[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 sr(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),be||(i.windowsVerbatimArguments=!0);let a=["Start"];n.wait&&a.push("-Wait"),e?(a.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&a.push(`"${n.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),n.target=mr.Buffer.from(a.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let a=!ur||ur==="/",l=!1;try{await ht.default.access(ws,ht.constants.X_OK),l=!0}catch{}r=pr.default.versions.electron??(Fe==="android"||a||!l)?"xdg-open":ws}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 o=hr.default.spawn(r,s,i);return n.wait?new Promise((a,l)=>{o.once("error",l),o.once("close",c=>{if(!n.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}a(o)})}):(o.unref(),o)},ci=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return Ve({...e,target:n})},li=(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");ui=ci});var Er=B(vr(),1),{program:Ci,createCommand:ki,createArgument:Oi,createOption:_i,CommanderError:vi,InvalidArgumentError:Ei,InvalidOptionArgumentError:Pi,Command:Pr,Argument:$i,Option:Ri,Help:Ti}=Er.default;var $r=!1,Rr=!1;function Tr(n,e){$r=n,Rr=e}function y(){return $r?!0:Rr?!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"),Xr=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 ae(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 ce(){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 W(n,e){return e?(0,Z.join)(process.cwd(),n.dir,"agents"):(0,Z.join)((0,ye.homedir)(),n.dir,"agents")}function q(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 le(n,e){return e?(0,Z.join)(process.cwd(),n.dir,"settings.json"):(0,Z.join)((0,ye.homedir)(),n.dir,"settings.json")}var G=require("fs"),ke=require("path");var pe=require("fs"),ue=require("path");z();Q();var Ur={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 vn(n){let e=n.resource.slug||n.resource.id,t=Ur[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 Wr(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=q(n,e),o=t.resource.slug||t.resource.id,a={};if((0,pe.existsSync)(i))try{a=JSON.parse((0,pe.readFileSync)(i,"utf-8"))}catch{a={}}let l=typeof a.mcpServers=="object"&&a.mcpServers&&!Array.isArray(a.mcpServers)?a.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(l,s.mcpServers):l[o]=s,a.mcpServers=l,(0,pe.mkdirSync)((0,ue.dirname)(i),{recursive:!0}),(0,pe.writeFileSync)(i,JSON.stringify(a,null,2)+`
31
- `,"utf-8")}function En(n,e,t){let r=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"));if(!r)throw new Error("Hook package does not contain a hook.json file");let s=JSON.parse(r.content),i=le(n,e),o={},a=s.hooks&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)?s.hooks:s;for(let[l,c]of Object.entries(a))if(!(l==="name"||l==="description")&&Array.isArray(c)){o[l]||(o[l]=[]);for(let p of c)o[l].push(p)}if(Object.keys(o).length===0)throw new Error("Hook package does not contain any hook event handlers");return Gt(i,o),i}function Vr(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=ae(s.agent);if(!i){let m=ce();y()?x("install","NO_AGENTS",m):w(m),process.exit(1)}let o=T(),l=await H(`${o?"/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=vn(c),d;if(c.resource.resourceType==="agent"){let m=W(i,!!s.project);d=(0,ue.join)(m,...Wr(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{En(i,!!s.project,c)}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,...Wr(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(o&&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=Ur[m.resourceType]||m.resourceType+"s",C=m.orgSlug||c.resource.orgSlug,M=C?`${S}/${C}/${A}`:`${S}/${A}`;ne({resourceId:m.id,slug:A,installPath:M,title:m.title,sha:m.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString(),collectionId:c.resource.id}),o&&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:q(i,!!s.project)}:{},...c.resource.resourceType==="hook"?{settingsPath:le(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 ${q(i,!!s.project)}`):c.resource.resourceType==="hook"?h(`Installed hook "${c.resource.title}" to ${le(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 M=A[S]||S;h(` ${M}: ${C.join(", ")}`)}}o||(h(""),h("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var et=class{buildFiles(e){let t=[],r=[],s=[],i={},o={};for(let a of e.files){let l=a.path.split("/"),c=l[0];if(c==="agents")s.push({path:a.path.slice(7),content:a.content});else if(c==="mcps"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(i,p.mcpServers);else if(a.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: ${a.path}`)}}else if(c==="hooks"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content);Pn(p,o)}catch{t.push(`Failed to parse hook config: ${a.path}`)}}else c==="skills"||c==="commands"||c==="files"?r.push({path:a.path.slice(c.length+1),content:a.content}):r.push(a)}return{mainFiles:r,agentFiles:s,mcpEntries:i,hookEntries:o,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",o=e.resource.slug||e.resource.id,a=_(r,i),l=Rn(e),c=(0,ke.join)(a,...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&&($(a,d),p+=d.length)}if(s.agentFiles.length>0){let u=W(r,i);$(u,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&$n(q(r,i),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Gt(le(r,i),s.hookEntries),{installDir:c,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,r,s){let i=[],a=_(r,t==="project"),l=(0,ke.join)(a,e),c=!1;return(0,G.existsSync)(l)&&((0,G.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 Pn(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)){e[s]||(e[s]=[]);for(let o of i)e[s].push(o)}}function Gt(n,e){let t={};if((0,G.existsSync)(n))try{t=JSON.parse((0,G.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.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 o of i){let a=JSON.stringify(o);r[s].some(c=>JSON.stringify(c)===a)||r[s].push(o)}}t.hooks=r,(0,G.mkdirSync)((0,ke.dirname)(n),{recursive:!0}),(0,G.writeFileSync)(n,JSON.stringify(t,null,2)+`
32
- `,"utf-8")}function $n(n,e){let t={};if((0,G.existsSync)(n))try{t=JSON.parse((0,G.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,G.mkdirSync)((0,ke.dirname)(n),{recursive:!0}),(0,G.writeFileSync)(n,JSON.stringify(t,null,2)+`
33
- `,"utf-8")}function Rn(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 Tn={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},tt=class{buildFiles(e){let t=[],r=[],s=[],i={},o={};for(let a of e.files){let l=a.path.split("/"),c=l[0];if(c==="agents")s.push({path:a.path.slice(7),content:a.content});else if(c==="mcps"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(i,p.mcpServers);else if(a.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: ${a.path}`)}}else if(c==="hooks"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content);In(p,o)}catch{t.push(`Failed to parse hook config: ${a.path}`)}}else c==="skills"||c==="commands"||c==="files"?r.push({path:a.path.slice(c.length+1),content:a.content}):r.push(a)}return{mainFiles:r,agentFiles:s,mcpEntries:i,hookEntries:o,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",o=e.resource.slug||e.resource.id,a=_(r,i),l=Dn(e),c=(0,Oe.join)(a,...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&&($(a,d),p+=d.length)}if(s.agentFiles.length>0){let u=W(r,i);$(u,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Fn(q(r,i),s.mcpEntries),Object.keys(s.hookEntries).length>0&&jn(le(r,i),s.hookEntries),{installDir:c,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,r){let s=[],o=_(r,t==="project"),a=(0,Oe.join)(o,e),l=!1;return(0,J.existsSync)(a)&&((0,J.rmSync)(a,{recursive:!0,force:!0}),l=!0),l||s.push(`Collection directory not found at ${a}`),{removed:l,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,Oe.join)(s,e)}};function In(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 o=Tn[s]||s;e[o]||(e[o]=[]);for(let a of i)e[o].push(a)}}function jn(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 o of i){let a=JSON.stringify(o);r[s].some(c=>JSON.stringify(c)===a)||r[s].push(o)}}t.hooks=r,(0,J.mkdirSync)((0,Oe.dirname)(n),{recursive:!0}),(0,J.writeFileSync)(n,JSON.stringify(t,null,2)+`
34
- `,"utf-8")}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.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)+`
35
- `,"utf-8")}function Dn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var L=require("fs"),de=require("path");var rt=class{buildFiles(e){let t=[],r=[],s=[],i={},o=[],a=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:o,warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",o=_(r,i),a=Nn(e),l=(0,de.join)(o,...a),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&&($(o,u),c+=u.length)}if(s.agentFiles.length>0){let p=W(r,i);$(p,s.agentFiles),c+=s.agentFiles.length}for(let p of s.customFiles)(0,L.mkdirSync)((0,de.dirname)(p.absolutePath),{recursive:!0}),(0,L.writeFileSync)(p.absolutePath,p.content,"utf-8"),c++;return Object.keys(s.mcpEntries).length>0&&Mn(q(r,i),s.mcpEntries),{installDir:l,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let s=[],o=_(r,t==="project"),a=(0,de.join)(o,e),l=!1;(0,L.existsSync)(a)&&((0,L.rmSync)(a,{recursive:!0,force:!0}),l=!0);let c=(0,de.join)(homedir(),".cursor","rules");if((0,L.existsSync)(c))try{let p=(0,L.readdirSync)(c);for(let u of p)u.startsWith(`${e}-`)&&u.endsWith(".mdc")&&((0,L.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 ${a}`),{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,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,de.dirname)(n),{recursive:!0}),(0,L.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 it=require("fs"),st=require("path");var nt=class{buildFiles(e){let t=[],r=[],s=[];for(let i of e.files){let a=i.path.split("/")[0];a==="agents"?s.push({path:i.path.slice(7),content:i.content}):a==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${i.path})`):a==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${i.path})`):a==="commands"?t.push(`Commands are not supported by Codex (skipped: ${i.path})`):a==="skills"||a==="files"?r.push({path:i.path.slice(a.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",o=_(r,i),a=Hn(e),l=(0,st.join)(o,...a),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&&($(o,u),c+=u.length)}if(s.agentFiles.length>0){let p=W(r,i);$(p,s.agentFiles),c+=s.agentFiles.length}return{installDir:l,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let s=[],o=_(r,t==="project"),a=(0,st.join)(o,e),l=!1;return(0,it.existsSync)(a)&&((0,it.rmSync)(a,{recursive:!0,force:!0}),l=!0),l||s.push(`Collection directory not found at ${a}`),{removed:l,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,st.join)(s,e)}};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 ie=require("fs"),Pe=require("path");var ot=class{buildFiles(e){let t=[],r=[],s={};for(let i of e.files){let o=i.path.split("/"),a=o[0];if(a==="agents")r.push({path:i.path.slice(7),content:i.content});else if(a==="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=o.indexOf("resources"),p=c>0?o[c-1]:o[1];s[p]=l}}catch{}}else a==="skills"||a==="commands"||a==="hooks"||a==="files"?t.push({path:i.path.slice(a.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",o=_(r,i),a=Wn(e),l=(0,Pe.join)(o,...a),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&&($(o,u),c+=u.length)}if(s.agentFiles.length>0){let p=W(r,i);$(p,s.agentFiles),c+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Ln(q(r,i),s.mcpEntries),{installDir:l,filesWritten:c,warnings:s.warnings}}async uninstall(e,t,r){let i=_(r,t==="project"),o=(0,Pe.join)(i,e),a=!1;return(0,ie.existsSync)(o)&&((0,ie.rmSync)(o,{recursive:!0,force:!0}),a=!0),{removed:a,warnings:[]}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,Pe.join)(s,e)}};function Ln(n,e){let t={};if((0,ie.existsSync)(n))try{t=JSON.parse((0,ie.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,ie.mkdirSync)((0,Pe.dirname)(n),{recursive:!0}),(0,ie.writeFileSync)(n,JSON.stringify(t,null,2)+`
37
- `,"utf-8")}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]}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 Br=`---
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=`---
38
39
  title: Resource Manager
39
40
  description: Search, install, and manage AI resources from the Shared Context library
40
41
  ---
@@ -180,30 +181,30 @@ npx shared-context-ai status # Auth status, detected agents, install
180
181
  \`\`\`
181
182
 
182
183
  **Error codes:** \`NOT_FOUND\`, \`AUTH_MISSING\`, \`NO_AGENTS\`, \`SKILL_NOT_FOUND\`, \`WRITE_FAILED\`, \`API_ERROR\`, \`UNEXPECTED\`
183
- `;var v=require("fs"),E=require("path"),Kr=require("crypto");var at=".context-collection",ct="manifest.json";function qr(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 Un(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 Vn(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 Jt=[{path:`${at}/${ct}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:qr,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:qr,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:Un,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:Vn,formatLabel:"Cursor Plugin"}];var Gr=[{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}],Jr=`${at}/${ct}`,Bn=new Set(["py","sh","js","ts","rb","go","rs","bash","zsh"]),qn=new Set(["json","yaml","yml","toml","xml","csv","txt","env","ini","cfg"]);function Le(n){let e={name:"",description:"",body:n};if(!n.startsWith(`---
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(`---
184
185
  `)&&!n.startsWith(`---\r
185
186
  `))return e;let t=n.indexOf(`
186
- ---`,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={},o={},a=new Set(["requires","tools"]),l={},c=r.split(`
187
- `),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):o[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,a.has(f)?(u=!0,l[f]=[]):(u=!1,o[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(o).length&&(e.arrayFields=o),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 Gn(n){let{body:e}=Le(n);return e.replace(/\r\n/g,`
188
- `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Re(n){let e=Gn(n);return`sha256:${(0,Kr.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 Yr(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 Jn(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);Bn.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);qn.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 Gr){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),M=(0,v.readFileSync)(C,"utf-8"),P=Le(M),U=P.name||(0,E.basename)(S,".md"),I=`${A}/${(0,E.basename)(S,".md")}`;b.push({importPath:I,resourceType:"file",title:U,description:P.description||null,body:P.body,bodyHash:Re(M),metadata:{},attachments:[]})}continue}for(let S of Yr(m)){let C=f.mainFile||`${S}.md`,M=(0,E.join)(m,S,C);if(!(0,v.existsSync)(M))continue;let P=(0,v.readFileSync)(M,"utf-8"),U=`${A}/${S}`,I,N,j,V={},R=null;if(f.resourceType==="hook"||f.resourceType==="mcp"){try{let te=JSON.parse(P);I=te.name||he(S),N=te.description||null}catch{I=he(S),N=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),N=fe.description||null,j=P,fe.resources&&Array.isArray(fe.resources)&&g.push({collectionImportPath:U,memberImportPaths:fe.resources.map(Ae=>{let qe=Ae.split("/");return qe.length>=3?`${qe[0]}/${qe[qe.length-1]}`:Ae})})}catch{I=he(S),N=null,j=P}else R=Le(P),I=R.name||he(S),N=R.description||null,j=R.body,R.arrayFields?.resources&&g.push({collectionImportPath:U,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),N=R.description||null,j=R.body,R.skillClass&&(V.skillClass=R.skillClass),R.service&&(V.service=R.service),R.requires?.length&&(V.requires=R.requires),R.tools?.length&&(V.tools=R.tools),R.fields&&Object.keys(R.fields).length&&(V.fields=R.fields);f.folder==="commands"&&(V.fields||(V.fields={}),V.fields["user-invocable"]="true");let Be=f.canHaveChildren?Jn((0,E.join)(m,S)):[];b.push({importPath:U,resourceType:f.resourceType,title:I,description:N,body:j,bodyHash:Re(P),metadata:V,attachments:Be})}}return{resources:b,memberships:g}}let o=i(n,"");e.push(...o.resources),t.push(...o.memberships);let a=(0,E.join)(n,".mcp.json");if((0,v.existsSync)(a))try{let u=JSON.parse((0,v.readFileSync)(a,"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 Jt){if(u.path===Jr)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 Yr(g)){if(d.has(A))continue;let S=(0,E.join)(g,A),C=f?`${f}/${A}`:A;for(let M of Jt){if(M.path===Jr)continue;let P=(0,E.join)(S,M.path);if((0,v.existsSync)(P)){if(u.has(C))break;u.add(C);try{let U=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 N=I.resources.filter(te=>te.resourceType!=="collection").map(te=>({resourceRef:te.importPath})),j=M.converter(U,N),V=(0,E.join)(S,"README.md"),R=(0,v.existsSync)(V)?(0,v.readFileSync)(V,"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=U.name||void 0),s||(s=M.formatLabel)}catch{}break}}b(S,C,m+1)}};var p=b;let u=new Set,d=new Set(Gr.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",zr="Resource Manager",Yt="collections/shared-context/essentials";function Yn(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"),Br,"utf-8"),(0,We.join)(r,"SKILL.md")}var Kn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Qr(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(),Lr)),{saveAuth:p}=await Promise.resolve().then(()=>(Q(),Hr)),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=ae(r.agent);if(!s){let c=ce();y()?x("init","NO_AGENTS",c):w(c),process.exit(1)}let i=oe();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 o=!1,a=[];if(i?.token)try{let c=await H(`/api/cli/resource/${Yt}`);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:Yt,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=Kn[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}),a.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(o=!0,!y()&&d.warnings.length>0)for(let g of d.warnings)w(`Warning: ${g}`)}}catch{}if(!o&&(Yn(s,!!r.project),ne({resourceId:"resource-manager",slug:je,installPath:`skills/${je}`,title:zr,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||zr,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,Xr.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:o?Yt:void 0,resourceManagerOnly:!o,...o?{membersInstalled:a.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(""),o){h(`Shared Context Essentials installed for ${s.label} (${a.length} resources)`);let c={};for(let u of a)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 Es=require("http"),Ps=require("crypto");Q();z();Q();async function $s(n){let e=await F("/api/cli/auth",{code:n});return e.ok?(Nt({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 mi(){let n=(0,Ps.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,Es.createServer)((r,s)=>{let i=new URL(r.url||"/","http://localhost"),o=i.searchParams.get("code"),a=i.searchParams.get("state");if(!o||a!==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(),$s(o).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,o=`${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: ${o}`));try{let a=(await Promise.resolve().then(()=>(vs(),_s))).default;await a(o)}catch{y()||h(`Could not open browser. Please visit:
189
- ${o}`)}setTimeout(()=>{t.close(),y()||w("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function Rs(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 $s(e.code):t=await mi(),process.exit(t?0:1)})}z();var di={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ts(n){let e=di[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 Is(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 o=i.data.results;if(y()){let l=o.map(c=>{let p=Ts(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(o.length===0){let l=t.type?`${t.type}s`:"results";h(`No ${l} found.`);return}h(`Found ${o.length} result${o.length===1?"":"s"}:
190
- `);let a=o.map(l=>[Ts(l),l.title,`\u2193${l.installCount}`]);h(re(a)),h(`
191
- Install a skill: npx shared-context-ai install <installPath>`)})}z();Q();function js(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 Fs(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:js(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:
192
- `);let r=t.map(s=>[js(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:
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:
193
194
  `);let r=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);h(re(r)),h(`
194
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}z();function Ds(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:
195
- `);let s=t.map(i=>{let o=i.slug||i.resourceId;return[i.storageType==="github"&&i.githubOwner?`skills/external/${i.githubOwner}/${o}`:i.orgSlug?`skills/${i.orgSlug}/${o}`:`skills/${o}`,i.title,`${i.installedSha.slice(0,7)} \u2192 ${i.latestSha.slice(0,7)}`]});h(re(s)),h(`
196
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var fr=require("path");z();Q();var hi={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ns(n){let e=n.slug||n.resourceId,t=hi[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 Hs(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=ae(s.agent);if(!i){let c=ce();y()?x("update","NO_AGENTS",c):w(c),process.exit(1)}let o=await H("/api/cli/updates");o.ok||(y()?x("update",o.error.code,o.error.message):w(`Failed to check updates: ${o.error.message}`),process.exit(1));let a=o.data.updates;if(e&&(a=a.filter(c=>Ns(c)===e||c.slug===e||c.resourceId===e),a.length===0)){y()?x("update","SKILL_NOT_FOUND",`No update available for "${e}".`):h(`No update available for "${e}".`);return}if(a.length===0){y()?O("update",{updated:[],count:0}):h("All resources are up to date.");return}let l=[];for(let c of a){let p=Ns(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=W(i,!!s.project),f=(0,fr.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,fr.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(`
197
- ${l.length} resource${l.length===1?"":"s"} updated.`)})}var D=require("fs"),De=require("path");z();Q();function Ls(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=ae(s.agent);if(!i){let b=ce();y()?x("uninstall","NO_AGENTS",b):w(b),process.exit(1)}let a=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,a?.resourceId);if(d=m.removed,!y())for(let A of m.warnings)w(`Warning: ${A}`);if(a){let S=K().installations.filter(C=>C.collectionId===a.resourceId&&C.agent===i.id);for(let C of S){let M=C.installPath.split("/"),P=M[0],U=M.slice(1);if(P==="agents"){let I=W(i,!!s.project),N=(0,De.join)(I,...U);(0,D.existsSync)(N)&&(0,D.rmSync)(N,{recursive:!0,force:!0})}else if(P==="mcps"){let I=U[U.length-1],N=q(i,!!s.project);if((0,D.existsSync)(N))try{let j=JSON.parse((0,D.readFileSync)(N,"utf-8"));if(typeof j.mcpServers=="object"&&j.mcpServers&&!Array.isArray(j.mcpServers)){let V=j.mcpServers;I in V&&(delete V[I],j.mcpServers=V,(0,D.writeFileSync)(N,JSON.stringify(j,null,2)+`
198
- `,"utf-8"))}}catch{}}else{let I=_(i,!!s.project),N=(0,De.join)(I,...U);(0,D.existsSync)(N)&&(0,D.rmSync)(N,{recursive:!0,force:!0})}Xe(C.resourceId,i.id)}}}else if(p==="agents"){let b=W(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=q(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)+`
199
- `,"utf-8"),d=!0)}}catch{}}else if(p==="hooks"){let b=le(i,!!s.project);d=!0,y()||w(`Note: Hook entries may remain in ${b} \u2014 review and remove manually if needed`)}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&&a?.slug){let f=(0,De.join)(b,a.slug);(0,D.existsSync)(f)&&(0,D.rmSync)(f,{recursive:!0,force:!0})}}if(T()&&a){let b=await F("/api/cli/uninstall",{resourceId:a.resourceId});!b.ok&&!y()&&w(`Warning: Could not record uninstall on server: ${b.error.message}`)}a&&Xe(a.resourceId,i.id),y()?O("uninstall",{path:e,removed:!0}):h(`Uninstalled "${e}"`)})}Q();function Ws(n){n.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=oe(),t=ge(),r=K(),s=Bt(),i={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(o=>o.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(o=>o.label).join(", ")}`):h(" Agents: None detected"),h(` Skills: ${r.installations.length} installed`)})}Q();z();function Us(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=oe();e.revoke&&T()&&await Ut("/api/cli/auth"),Ht(),y()?O("logout",{email:t?.email||null}):h("Logged out.")})}var gt=require("fs"),Vs=require("path");z();function Bs(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(`
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(`
200
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(`
201
- 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 o=(0,Vs.resolve)(e);(!(0,gt.existsSync)(o)||!(0,gt.statSync)(o).isDirectory())&&(y()?x("import","INVALID_PATH",`Not a directory: ${o}`):w(`Error: Not a directory: ${o}`),process.exit(1));let a=Ie(o);if(a.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 a.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(`
202
- Discovered ${a.resources.length} resources in ${e}:`),h(` ${f}`),a.formatLabel&&a.pluginName?h(` ${a.formatLabel}: ${a.pluginName}`):a.pluginName&&h(` Plugin: ${a.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:a.resources,collectionMemberships:a.collectionMemberships.length>0?a.collectionMemberships:void 0};!y()&&!t.dryRun?h(`
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(`
203
204
  Executing import...`):y()||h(`
204
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(`
205
- 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),M=(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 U=m.versionsBehind;P=`\u2713 installed${U?` (${U} 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} ${M} ${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 Js=require("path"),Ys=require("os");z();Q();function Ks(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:qs(f.lastResult.updatesAvailable,f.lastResult.untrackedResources),throttled:!0};Gs(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=ae(r.agent);if(!s){let f=ce();y()?x("sync","NO_AGENTS",f):w(f),process.exit(1)}let i=[],o=await H("/api/cli/updates");o.ok&&(i=o.data.updates);let a=(0,Js.join)((0,Ys.homedir)(),s.dir),l=Ie(a),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(`
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(`
206
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(`
207
- ${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:qs(i.length,d.length),throttled:!1};Gs(g,!!r.quiet)})}function qs(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 Gs(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:
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:
208
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"}:
209
- `);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 zs={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||zs[t]);this.code=t;this.name="CliError"}get recovery(){return zs[this.code]}};var Y=new Pr;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();Tr(!!e.json,!!e.human)});Qr(Y);Rs(Y);Is(Y);Vr(Y);Fs(Y);Ds(Y);Ms(Y);Hs(Y);Ls(Y);Ws(Y);Us(Y);Bs(Y);Ks(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();
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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shared-context-ai",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "CLI for Shared Context - search, install, and manage AI skills",
5
5
  "bin": {
6
6
  "shared-context-ai": "dist/index.js"