shared-context-ai 0.1.25 → 0.1.27

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 +75 -74
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,52 +1,52 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ni=Object.create;var ur=Object.defineProperty;var si=Object.getOwnPropertyDescriptor;var oi=Object.getOwnPropertyNames;var ii=Object.getPrototypeOf,ai=Object.prototype.hasOwnProperty;var pe=(r,e)=>()=>(r&&(e=r(r=0)),e);var Z=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),gt=(r,e)=>{for(var t in e)ur(r,t,{get:e[t],enumerable:!0})},ci=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of oi(e))!ai.call(r,s)&&s!==t&&ur(r,s,{get:()=>e[s],enumerable:!(n=si(e,s))||n.enumerable});return r};var me=(r,e,t)=>(t=r!=null?ni(ii(r)):{},ci(e||!r||!r.__esModule?ur(t,"default",{value:r,enumerable:!0}):t,r));var yt=Z(dr=>{"use strict";var xt=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},fr=class extends xt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};dr.CommanderError=xt;dr.InvalidArgumentError=fr});var Ot=Z(mr=>{"use strict";var{InvalidArgumentError:li}=yt(),pr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new li(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ui(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}mr.Argument=pr;mr.humanReadableArgName=ui});var yr=Z(gr=>{"use strict";var{humanReadableArgName:fi}=Ot(),hr=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>fi(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth??80;function o(g,_){return t.formatItem(g,n,_,t)}let l=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],c=t.commandDescription(e);c.length>0&&(l=l.concat([t.boxWrap(t.styleCommandDescription(c),s),""]));let u=t.visibleArguments(e).map(g=>o(t.styleArgumentTerm(t.argumentTerm(g)),t.styleArgumentDescription(t.argumentDescription(g))));u.length>0&&(l=l.concat([t.styleTitle("Arguments:"),...u,""]));let a=t.visibleOptions(e).map(g=>o(t.styleOptionTerm(t.optionTerm(g)),t.styleOptionDescription(t.optionDescription(g))));if(a.length>0&&(l=l.concat([t.styleTitle("Options:"),...a,""])),t.showGlobalOptions){let g=t.visibleGlobalOptions(e).map(_=>o(t.styleOptionTerm(t.optionTerm(_)),t.styleOptionDescription(t.optionDescription(_))));g.length>0&&(l=l.concat([t.styleTitle("Global Options:"),...g,""]))}let p=t.visibleCommands(e).map(g=>o(t.styleSubcommandTerm(t.subcommandTerm(g)),t.styleSubcommandDescription(t.subcommandDescription(g))));return p.length>0&&(l=l.concat([t.styleTitle("Commands:"),...p,""])),l.join(`
3
- `)}displayWidth(e){return _n(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,s){let l=" ".repeat(2);if(!n)return l+e;let c=e.padEnd(t+e.length-s.displayWidth(e)),u=2,p=(this.helpWidth??80)-t-u-2,g;return p<this.minWidthToWrap||s.preformatted(n)?g=n:g=s.boxWrap(n,p).replace(/\n/g,`
4
- `+" ".repeat(t+u)),l+c+" ".repeat(u)+g.replace(/\n/g,`
5
- ${l}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(l=>{let c=l.match(s);if(c===null){o.push("");return}let u=[c.shift()],a=this.displayWidth(u[0]);c.forEach(p=>{let g=this.displayWidth(p);if(a+g<=t){u.push(p),a+=g;return}o.push(u.join(""));let _=p.trimStart();u=[_],a=this.displayWidth(_)}),o.push(u.join(""))}),o.join(`
6
- `)}};function _n(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}gr.Help=hr;gr.stripColor=_n});var wr=Z(Cr=>{"use strict";var{InvalidArgumentError:di}=yt(),Sr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=pi(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new di(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?xn(this.name().replace(/^no-/,"")):xn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Er=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function xn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function pi(r){let e,t,n=/^-[^-]$/,s=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let l=o[0],c=`option creation failed due to '${l}' in option flags '${r}'`;throw/^-[^-][^-]/.test(l)?new Error(`${c}
2
+ "use strict";var fi=Object.create;var mr=Object.defineProperty;var di=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,hi=Object.prototype.hasOwnProperty;var he=(r,e)=>()=>(r&&(e=r(r=0)),e);var K=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),St=(r,e)=>{for(var t in e)mr(r,t,{get:e[t],enumerable:!0})},gi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pi(e))!hi.call(r,s)&&s!==t&&mr(r,s,{get:()=>e[s],enumerable:!(n=di(e,s))||n.enumerable});return r};var ge=(r,e,t)=>(t=r!=null?fi(mi(r)):{},gi(e||!r||!r.__esModule?mr(t,"default",{value:r,enumerable:!0}):t,r));var Et=K(gr=>{"use strict";var Tt=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},hr=class extends Tt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};gr.CommanderError=Tt;gr.InvalidArgumentError=hr});var Rt=K(Sr=>{"use strict";var{InvalidArgumentError:yi}=Et(),yr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new yi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Si(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Sr.Argument=yr;Sr.humanReadableArgName=Si});var wr=K(Cr=>{"use strict";var{humanReadableArgName:Ei}=Rt(),Er=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>Ei(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth??80;function o(y,b){return t.formatItem(y,n,b,t)}let c=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(c=c.concat([t.boxWrap(t.styleCommandDescription(a),s),""]));let u=t.visibleArguments(e).map(y=>o(t.styleArgumentTerm(t.argumentTerm(y)),t.styleArgumentDescription(t.argumentDescription(y))));u.length>0&&(c=c.concat([t.styleTitle("Arguments:"),...u,""]));let l=t.visibleOptions(e).map(y=>o(t.styleOptionTerm(t.optionTerm(y)),t.styleOptionDescription(t.optionDescription(y))));if(l.length>0&&(c=c.concat([t.styleTitle("Options:"),...l,""])),t.showGlobalOptions){let y=t.visibleGlobalOptions(e).map(b=>o(t.styleOptionTerm(t.optionTerm(b)),t.styleOptionDescription(t.optionDescription(b))));y.length>0&&(c=c.concat([t.styleTitle("Global Options:"),...y,""]))}let p=t.visibleCommands(e).map(y=>o(t.styleSubcommandTerm(t.subcommandTerm(y)),t.styleSubcommandDescription(t.subcommandDescription(y))));return p.length>0&&(c=c.concat([t.styleTitle("Commands:"),...p,""])),c.join(`
3
+ `)}displayWidth(e){return Pn(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,s){let c=" ".repeat(2);if(!n)return c+e;let a=e.padEnd(t+e.length-s.displayWidth(e)),u=2,p=(this.helpWidth??80)-t-u-2,y;return p<this.minWidthToWrap||s.preformatted(n)?y=n:y=s.boxWrap(n,p).replace(/\n/g,`
4
+ `+" ".repeat(t+u)),c+a+" ".repeat(u)+y.replace(/\n/g,`
5
+ ${c}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(c=>{let a=c.match(s);if(a===null){o.push("");return}let u=[a.shift()],l=this.displayWidth(u[0]);a.forEach(p=>{let y=this.displayWidth(p);if(l+y<=t){u.push(p),l+=y;return}o.push(u.join(""));let b=p.trimStart();u=[b],l=this.displayWidth(b)}),o.push(u.join(""))}),o.join(`
6
+ `)}};function Pn(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}Cr.Help=Er;Cr.stripColor=Pn});var xr=K(Ir=>{"use strict";var{InvalidArgumentError:Ci}=Et(),br=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=wi(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Ci(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?jn(this.name().replace(/^no-/,"")):jn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ar=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function jn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function wi(r){let e,t,n=/^-[^-]$/,s=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let c=o[0],a=`option creation failed due to '${c}' in option flags '${r}'`;throw/^-[^-][^-]/.test(c)?new Error(`${a}
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')`):n.test(l)?new Error(`${c}
10
- - too many short flags`):s.test(l)?new Error(`${c}
11
- - too many long flags`):new Error(`${c}
12
- - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}Cr.Option=Sr;Cr.DualOptions=Er});var kn=Z(On=>{"use strict";function mi(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let o=1;r[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function hi(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(l=>l.slice(2)));let n=[],s=3,o=.4;return e.forEach(l=>{if(l.length<=1)return;let c=mi(r,l),u=Math.max(r.length,l.length);(u-c)/u>o&&(c<s?(s=c,n=[l]):c===s&&n.push(l))}),n.sort((l,c)=>l.localeCompare(c)),t&&(n=n.map(l=>`--${l}`)),n.length>1?`
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(c)?new Error(`${a}
10
+ - too many short flags`):s.test(c)?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 '${r}'.`);return{shortFlag:e,longFlag:t}}Ir.Option=br;Ir.DualOptions=Ar});var Nn=K(Dn=>{"use strict";function bi(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let o=1;r[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function Ai(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(c=>c.slice(2)));let n=[],s=3,o=.4;return e.forEach(c=>{if(c.length<=1)return;let a=bi(r,c),u=Math.max(r.length,c.length);(u-a)/u>o&&(a<s?(s=a,n=[c]):a===s&&n.push(c))}),n.sort((c,a)=>c.localeCompare(a)),t&&(n=n.map(c=>`--${c}`)),n.length>1?`
13
13
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
14
- (Did you mean ${n[0]}?)`:""}On.suggestSimilar=hi});var Pn=Z(xr=>{"use strict";var gi=require("events").EventEmitter,br=require("child_process"),Re=require("path"),kt=require("fs"),F=require("process"),{Argument:yi,humanReadableArgName:Si}=Ot(),{CommanderError:Ar}=yt(),{Help:Ei,stripColor:Ci}=yr(),{Option:vn,DualOptions:wi}=wr(),{suggestSimilar:Tn}=kn(),Ir=class r extends gi{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>F.stdout.write(t),writeErr:t=>F.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>F.stdout.isTTY?F.stdout.columns:void 0,getErrHelpWidth:()=>F.stderr.isTTY?F.stderr.columns:void 0,getOutHasColors:()=>_r()??(F.stdout.isTTY&&F.stdout.hasColors?.()),getErrHasColors:()=>_r()??(F.stderr.isTTY&&F.stderr.hasColors?.()),stripColor:t=>Ci(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,l,c]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(l);return s&&(u.description(s),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,c&&u.arguments(c),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Ei,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 yi(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",l=this.createCommand(n);return l.helpOption(!1),s&&l.arguments(s),o&&l.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=l,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Ar(e,t,n)),F.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new vn(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let l=`${s} ${o.message}`;this.error(l,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
17
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,l,c)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,l):o!==null&&e.variadic&&(o=e._concatValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,c)};return this.on("option:"+t,o=>{let l=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,l,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let l=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,l,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof vn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let l=this.createOption(t,n);if(l.makeOptionMandatory(!!e.mandatory),typeof s=="function")l.default(o).argParser(s);else if(s instanceof RegExp){let c=s;s=(u,a)=>{let p=c.exec(u);return p?p[0]:a},l.default(o).argParser(s)}else l.default(s);return this.addOption(l)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){F.versions?.electron&&(t.from="electron");let s=F.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=F.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":F.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
18
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(kt.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
14
+ (Did you mean ${n[0]}?)`:""}Dn.suggestSimilar=Ai});var Mn=K(Tr=>{"use strict";var Ii=require("events").EventEmitter,_r=require("child_process"),$e=require("path"),Pt=require("fs"),H=require("process"),{Argument:xi,humanReadableArgName:_i}=Rt(),{CommanderError:Or}=Et(),{Help:Oi,stripColor:vi}=wr(),{Option:$n,DualOptions:ki}=xr(),{suggestSimilar:Ln}=Nn(),vr=class r extends Ii{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=>H.stdout.write(t),writeErr:t=>H.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.stderr.columns:void 0,getOutHasColors:()=>kr()??(H.stdout.isTTY&&H.stdout.hasColors?.()),getErrHasColors:()=>kr()??(H.stderr.isTTY&&H.stderr.hasColors?.()),stripColor:t=>vi(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,c,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(c);return s&&(u.description(s),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Oi,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 xi(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",c=this.createCommand(n);return c.helpOption(!1),s&&c.arguments(s),o&&c.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=c,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
16
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Or(e,t,n)),H.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new $n(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let c=`${s} ${o.message}`;this.error(c,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
17
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,c,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let u=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,u,c):o!==null&&e.variadic&&(o=e._concatValue(o,u)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+t,o=>{let c=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,c,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let c=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,c,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof $n)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let c=this.createOption(t,n);if(c.makeOptionMandatory(!!e.mandatory),typeof s=="function")c.default(o).argParser(s);else if(s instanceof RegExp){let a=s;s=(u,l)=>{let p=a.exec(u);return p?p[0]:l},c.default(o).argParser(s)}else c.default(s);return this.addOption(c)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){H.versions?.electron&&(t.from="electron");let s=H.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=H.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":H.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
18
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(Pt.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
19
19
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
20
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
- - ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(p,g){let _=Re.resolve(p,g);if(kt.existsSync(_))return _;if(s.includes(Re.extname(g)))return;let f=s.find(h=>kt.existsSync(`${_}${h}`));if(f)return`${_}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let l=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let p;try{p=kt.realpathSync(this._scriptPath)}catch{p=this._scriptPath}c=Re.resolve(Re.dirname(p),c)}if(c){let p=o(c,l);if(!p&&!e._executableFile&&this._scriptPath){let g=Re.basename(this._scriptPath,Re.extname(this._scriptPath));g!==this._name&&(p=o(c,`${g}-${e._name}`))}l=p||l}n=s.includes(Re.extname(l));let u;F.platform!=="win32"?n?(t.unshift(l),t=Rn(F.execArgv).concat(t),u=br.spawn(F.argv[0],t,{stdio:"inherit"})):u=br.spawn(l,t,{stdio:"inherit"}):(this._checkForMissingExecutable(l,c,e._name),t.unshift(l),t=Rn(F.execArgv).concat(t),u=br.spawn(F.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(g=>{F.on(g,()=>{u.killed===!1&&u.exitCode===null&&u.kill(g)})});let a=this._exitCallback;u.on("close",p=>{p=p??1,a?a(new Ar(p,"commander.executeSubCommandAsync","(close)")):F.exit(p)}),u.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(l,c,e._name);else if(p.code==="EACCES")throw new Error(`'${l}' not executable`);if(!a)F.exit(1);else{let g=new Ar(1,"commander.executeSubCommandAsync","(error)");g.nestedError=p,a(g)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,o)=>{let l=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;l=this._callParseArg(n,s,o,c)}return l};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((l,c)=>e(n,c,l),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(l=>{s.push({hookedCommand:o,callback:l})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let l;return l=this._chainOrCallHooks(l,"preAction"),l=this._chainOrCall(l,()=>this._actionHandler(this.processedArgs)),this.parent&&(l=this._chainOrCall(l,()=>{this.parent.emit(o,e,t)})),l=this._chainOrCallHooks(l,"postAction"),l}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function l(u){return u.length>1&&u[0]==="-"}let c=null;for(;o.length;){let u=o.shift();if(u==="--"){s===n&&s.push(u),s.push(...o);break}if(c&&!l(u)){this.emit(`option:${c.name()}`,u);continue}if(c=null,l(u)){let a=this._findOption(u);if(a){if(a.required){let p=o.shift();p===void 0&&this.optionMissingArgument(a),this.emit(`option:${a.name()}`,p)}else if(a.optional){let p=null;o.length>0&&!l(o[0])&&(p=o.shift()),this.emit(`option:${a.name()}`,p)}else this.emit(`option:${a.name()}`);c=a.variadic?a:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let a=this._findOption(`-${u[1]}`);if(a){a.required||a.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${a.name()}`,u.slice(2)):(this.emit(`option:${a.name()}`),o.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let a=u.indexOf("="),p=this._findOption(u.slice(0,a));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,u.slice(a+1));continue}}if(l(u)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(u),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(u),o.length>0&&s.push(...o);break}s.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
21
+ - ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(p,y){let b=$e.resolve(p,y);if(Pt.existsSync(b))return b;if(s.includes($e.extname(y)))return;let f=s.find(m=>Pt.existsSync(`${b}${m}`));if(f)return`${b}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let c=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let p;try{p=Pt.realpathSync(this._scriptPath)}catch{p=this._scriptPath}a=$e.resolve($e.dirname(p),a)}if(a){let p=o(a,c);if(!p&&!e._executableFile&&this._scriptPath){let y=$e.basename(this._scriptPath,$e.extname(this._scriptPath));y!==this._name&&(p=o(a,`${y}-${e._name}`))}c=p||c}n=s.includes($e.extname(c));let u;H.platform!=="win32"?n?(t.unshift(c),t=Fn(H.execArgv).concat(t),u=_r.spawn(H.argv[0],t,{stdio:"inherit"})):u=_r.spawn(c,t,{stdio:"inherit"}):(this._checkForMissingExecutable(c,a,e._name),t.unshift(c),t=Fn(H.execArgv).concat(t),u=_r.spawn(H.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(y=>{H.on(y,()=>{u.killed===!1&&u.exitCode===null&&u.kill(y)})});let l=this._exitCallback;u.on("close",p=>{p=p??1,l?l(new Or(p,"commander.executeSubCommandAsync","(close)")):H.exit(p)}),u.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(c,a,e._name);else if(p.code==="EACCES")throw new Error(`'${c}' not executable`);if(!l)H.exit(1);else{let y=new Or(1,"commander.executeSubCommandAsync","(error)");y.nestedError=p,l(y)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,o)=>{let c=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;c=this._callParseArg(n,s,o,a)}return c};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((c,a)=>e(n,a,c),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(c=>{s.push({hookedCommand:o,callback:c})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let c;return c=this._chainOrCallHooks(c,"preAction"),c=this._chainOrCall(c,()=>this._actionHandler(this.processedArgs)),this.parent&&(c=this._chainOrCall(c,()=>{this.parent.emit(o,e,t)})),c=this._chainOrCallHooks(c,"postAction"),c}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function c(u){return u.length>1&&u[0]==="-"}let a=null;for(;o.length;){let u=o.shift();if(u==="--"){s===n&&s.push(u),s.push(...o);break}if(a&&!c(u)){this.emit(`option:${a.name()}`,u);continue}if(a=null,c(u)){let l=this._findOption(u);if(l){if(l.required){let p=o.shift();p===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,p)}else if(l.optional){let p=null;o.length>0&&!c(o[0])&&(p=o.shift()),this.emit(`option:${l.name()}`,p)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,u.slice(2)):(this.emit(`option:${l.name()}`),o.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),p=this._findOption(u.slice(0,l));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,u.slice(l+1));continue}}if(c(u)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(u),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(u),o.length>0&&s.push(...o);break}s.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
- `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in F.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()}`,F.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new wi(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=l=>{let c=l.attributeName(),u=this.getOptionValue(c),a=this.options.find(g=>g.negate&&c===g.attributeName()),p=this.options.find(g=>!g.negate&&c===g.attributeName());return a&&(a.presetArg===void 0&&u===!1||a.presetArg!==void 0&&u===a.presetArg)?a:p||l},s=l=>{let c=n(l),u=c.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let l=o.createHelp().visibleOptions(o).filter(c=>c.long).map(c=>c.long);s=s.concat(l),o=o.parent}while(o&&!o._enablePositionalOptions);t=Tn(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=Tn(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Si(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Re.basename(e,Re.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=t.formatHelp(this,t);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,n,s,o;return t?(n=c=>this._outputConfiguration.writeErr(c),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=c=>this._outputConfiguration.writeOut(c),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:c=>(s||(c=this._outputConfiguration.stripColor(c)),n(c)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(l=>l.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(l=>l.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(F.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
- Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let l;typeof t=="function"?l=t({error:o.error,command:o.command}):l=t,l&&o.write(`${l}
27
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Rn(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}function _r(){if(F.env.NO_COLOR||F.env.FORCE_COLOR==="0"||F.env.FORCE_COLOR==="false")return!1;if(F.env.FORCE_COLOR||F.env.CLICOLOR_FORCE!==void 0)return!0}xr.Command=Ir;xr.useColor=_r});var $n=Z(be=>{"use strict";var{Argument:jn}=Ot(),{Command:Or}=Pn(),{CommanderError:bi,InvalidArgumentError:Dn}=yt(),{Help:Ai}=yr(),{Option:Nn}=wr();be.program=new Or;be.createCommand=r=>new Or(r);be.createOption=(r,e)=>new Nn(r,e);be.createArgument=(r,e)=>new jn(r,e);be.Command=Or;be.Option=Nn;be.Argument=jn;be.Help=Ai;be.CommanderError=bi;be.InvalidArgumentError=Dn;be.InvalidOptionArgumentError=Dn});function Hn(r,e){Mn=r,Un=e}function x(){return Mn?!0:Un?!1:!process.stdout.isTTY}function N(r,e){console.log(JSON.stringify({ok:!0,command:r,data:e}))}function D(r,e,t){console.log(JSON.stringify({ok:!1,command:r,errors:[{code:e,message:t}]}))}function w(r){console.log(r)}function T(r){console.error(r)}function he(r,e=2){if(r.length===0)return"";let t=[];for(let n of r)for(let s=0;s<n.length;s++)t[s]=Math.max(t[s]||0,n[s].length);return r.map(n=>n.map((s,o)=>o<n.length-1?s.padEnd(t[o]+e):s).join("")).join(`
28
- `)}var Mn,Un,re=pe(()=>{"use strict";Mn=!1,Un=!1});var Rt={};gt(Rt,{addToManifest:()=>ae,clearAuth:()=>Rr,clearLastSyncAt:()=>$e,getAuth:()=>Ae,getConfig:()=>Ie,getManifest:()=>V,getSyncState:()=>vi,removeFromManifest:()=>wt,saveAuth:()=>Tr,saveConfig:()=>qn,saveManifest:()=>Ne,saveSyncState:()=>Ti,shouldSync:()=>jr,updateConfig:()=>vt,updateManifestMeta:()=>Tt});function St(){let r=process.env.SC_PROFILE;return r?(0,Ke.join)(Bn,"profiles",r):Bn}function vr(){return(0,Ke.join)(St(),"auth.json")}function Vn(){return(0,Ke.join)(St(),"config.json")}function kr(){return(0,Ke.join)(St(),"manifest.json")}function Ii(){(0,Ee.mkdirSync)(St(),{recursive:!0})}function Et(r,e){try{return(0,Ee.existsSync)(r)?JSON.parse((0,Ee.readFileSync)(r,"utf-8")):e}catch{return e}}function Ct(r,e,t=!1){if(Ii(),(0,Ee.writeFileSync)(r,JSON.stringify(e,null,2)+`
29
- `,"utf-8"),t)try{(0,Ee.chmodSync)(r,384)}catch{}}function Ae(){return Et(vr(),null)}function Tr(r){Ct(vr(),r,!0)}function Rr(){try{(0,Ee.writeFileSync)(vr(),"{}","utf-8")}catch{}}function Ie(){return Et(Vn(),_i)}function qn(r){Ct(Vn(),r)}function vt(r){let e=Ie();qn({...e,...r})}function Oi(r){if(r.version&&r.version>=2)return r;let e={version:2,installations:r.installations.map(s=>({...s,serverSynced:!1}))},t=Pr(),n=Et(t,null);n?.lastSyncAt&&(e.lastSyncAt=n.lastSyncAt);try{(0,Ee.unlinkSync)(t)}catch{}return e}function V(){let r=Et(kr(),xi),e=Oi(r);return(!r.version||r.version<2)&&Ct(kr(),e),e}function Ne(r){Ct(kr(),r)}function ae(r){let e=V(),t=e.installations.findIndex(n=>n.resourceId===r.resourceId&&n.agent===r.agent);t>=0?e.installations[t]=r:e.installations.push(r),Ne(e)}function wt(r,e){let t=V();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),Ne(t)}function $e(){let r=V();delete r.lastSyncAt,Ne(r)}function Tt(r){let e=V();r.lastSyncAt!==void 0&&(e.lastSyncAt=r.lastSyncAt),Ne(e)}function Pr(){return(0,Ke.join)(St(),"last-sync.json")}function vi(){return Et(Pr(),null)}function Ti(r){Ct(Pr(),r)}function jr(){let r=parseInt(process.env.SC_SYNC_COOLDOWN||"",10),e=r>=0?r:ki,t=V();return t.lastSyncAt?Date.now()-new Date(t.lastSyncAt).getTime()>=e:!0}var Ee,Ke,Wn,Bn,_i,xi,ki,ce=pe(()=>{"use strict";Ee=require("fs"),Ke=require("path"),Wn=require("os"),Bn=(0,Ke.join)((0,Wn.homedir)(),".config","shared-context");_i={apiBase:"https://sharedcontext.ai"};xi={version:2,installations:[]};ki=720*60*1e3});var Zn={};gt(Zn,{del:()=>Dr,fetchRaw:()=>Nr,get:()=>G,isAuthenticated:()=>L,patch:()=>Ri,post:()=>$});function Gn(){return Ie().apiBase||"https://sharedcontext.ai"}function zn(){let r={"Content-Type":"application/json"},e=Ae();return e?.token&&(r.Authorization=`Bearer ${e.token}`),r}function L(){return!!Ae()?.token}async function Pt(r,e,t,n){let s=`${Gn()}${e}`;try{let o={method:r,headers:zn(),body:t?JSON.stringify(t):void 0};n&&(o.signal=AbortSignal.timeout(n));let l=await fetch(s,o),c=l.headers.get("content-type")||"";if(!c.includes("application/json"))return l.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${c||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${l.status}`,message:l.statusText}};let u=await l.json();return l.ok?{ok:!0,data:u.data??u}:{ok:!1,error:{code:u?.error?.code||`HTTP_${l.status}`,message:u?.error?.message||u?.message||l.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function G(r){return Pt("GET",r)}function $(r,e,t){return Pt("POST",r,e,t)}function Ri(r,e){return Pt("PATCH",r,e)}function Dr(r,e){return Pt("DELETE",r,e)}async function Nr(r){let e=`${Gn()}${r}`,t=await fetch(e,{headers:zn()});if(!t.ok)throw new Error(`Download failed: ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}var ne=pe(()=>{"use strict";ce()});var Lr=Z((Sc,Jn)=>{"use strict";Jn.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var jt=Z(Xn=>{"use strict";var Kn={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Pi(r){return function(...e){return e.length&&(r=r.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+r)}}for(let r of Object.keys(Kn))Xn[r]=Pi(Kn[r])});var rs=Z((Cc,ts)=>{"use strict";var ji=require("fs"),oe=require("path"),Yn=Lr(),Di=jt(),Ni=typeof process=="object"&&process.platform==="win32",Qn=r=>typeof r=="object"&&r!==null,es=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function X(r){this.sep=oe.sep,this.fs=ji,Qn(r)&&Qn(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}ts.exports=X;X.prototype.makeDir=function(r){let e=this;function t(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(o){if(!(!o||o.substr(-1,1)===":")){s+=e.sep+o;var l;try{l=e.fs.statSync(s)}catch{e.fs.mkdirSync(s)}if(l&&l.isFile())throw Di.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};X.prototype.writeFileTo=function(r,e,t,n){let s=this;if(s.fs.existsSync(r)){if(!t)return!1;var o=s.fs.statSync(r);if(o.isDirectory())return!1}var l=oe.dirname(r);s.fs.existsSync(l)||s.makeDir(l);var c;try{c=s.fs.openSync(r,"w",438)}catch{s.fs.chmodSync(r,438),c=s.fs.openSync(r,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(r,n||438),!0};X.prototype.writeFileToAsync=function(r,e,t,n,s){typeof n=="function"&&(s=n,n=void 0);let o=this;o.fs.exists(r,function(l){if(l&&!t)return s(!1);o.fs.stat(r,function(c,u){if(l&&u.isDirectory())return s(!1);var a=oe.dirname(r);o.fs.exists(a,function(p){p||o.makeDir(a),o.fs.open(r,"w",438,function(g,_){g?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(f,h){o.fs.write(h,e,0,e.length,0,function(){o.fs.close(h,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):_?o.fs.write(_,e,0,e.length,0,function(){o.fs.close(_,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};X.prototype.findFiles=function(r){let e=this;function t(n,s,o){typeof s=="boolean"&&(o=s,s=void 0);let l=[];return e.fs.readdirSync(n).forEach(function(c){let u=oe.join(n,c),a=e.fs.statSync(u);(!s||s.test(u))&&l.push(oe.normalize(u)+(a.isDirectory()?e.sep:"")),a.isDirectory()&&o&&(l=l.concat(t(u,s,o)))}),l}return t(r,void 0,!0)};X.prototype.findFilesAsync=function(r,e){let t=this,n=[];t.fs.readdir(r,function(s,o){if(s)return e(s);let l=o.length;if(!l)return e(null,n);o.forEach(function(c){c=oe.join(r,c),t.fs.stat(c,function(u,a){if(u)return e(u);a&&(n.push(oe.normalize(c)+(a.isDirectory()?t.sep:"")),a.isDirectory()?t.findFilesAsync(c,function(p,g){if(p)return e(p);n=n.concat(g),--l||e(null,n)}):--l||e(null,n))})})})};X.prototype.getAttributes=function(){};X.prototype.setAttributes=function(){};X.crc32update=function(r,e){return es[(r^e)&255]^r>>>8};X.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=X.crc32update(t,r[n++]);return~t>>>0};X.methodToString=function(r){switch(r){case Yn.STORED:return"STORED ("+r+")";case Yn.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};X.canonical=function(r){if(!r)return"";let e=oe.posix.normalize("/"+r.split("\\").join("/"));return oe.join(".",e)};X.zipnamefix=function(r){if(!r)return"";let e=oe.posix.normalize("/"+r.split("\\").join("/"));return oe.posix.join(".",e)};X.findLast=function(r,e){if(!Array.isArray(r))throw new TypeError("arr is not array");let t=r.length>>>0;for(let n=t-1;n>=0;n--)if(e(r[n],n,r))return r[n]};X.sanitize=function(r,e){r=oe.resolve(oe.normalize(r));for(var t=e.split("/"),n=0,s=t.length;n<s;n++){var o=oe.normalize(oe.join(r,t.slice(n,s).join(oe.sep)));if(o.indexOf(r)===0)return o}return oe.normalize(oe.join(r,oe.basename(e)))};X.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};X.readBigUInt64LE=function(r,e){var t=Buffer.from(r.slice(e,e+8));return t.swap64(),parseInt(`0x${t.toString("hex")}`)};X.fromDOS2Date=function(r){return new Date((r>>25&127)+1980,Math.max((r>>21&15)-1,0),Math.max(r>>16&31,1),r>>11&31,r>>5&63,(r&31)<<1)};X.fromDate2DOS=function(r){let e=0,t=0;return r.getFullYear()>1979&&(e=(r.getFullYear()-1980&127)<<9|r.getMonth()+1<<5|r.getDate(),t=r.getHours()<<11|r.getMinutes()<<5|r.getSeconds()>>1),e<<16|t};X.isWin=Ni;X.crcTable=es});var ss=Z((wc,ns)=>{"use strict";var $i=require("path");ns.exports=function(r,{fs:e}){var t=r||"",n=o(),s=null;function o(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(s=e.statSync(t),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=$i.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var is=Z((bc,os)=>{"use strict";os.exports={efs:!0,encode:r=>Buffer.from(r,"utf8"),decode:r=>r.toString("utf8")}});var ct=Z((Ac,at)=>{"use strict";at.exports=rs();at.exports.Constants=Lr();at.exports.Errors=jt();at.exports.FileAttr=ss();at.exports.decoder=is()});var cs=Z((Ic,as)=>{"use strict";var Ue=ct(),R=Ue.Constants;as.exports=function(){var r=20,e=10,t=0,n=0,s=0,o=0,l=0,c=0,u=0,a=0,p=0,g=0,_=0,f=0,h=0;r|=Ue.isWin?2560:768,t|=R.FLG_EFS;let E={extraLen:0},y=i=>Math.max(0,i)>>>0,C=i=>Math.max(0,i)&65535,m=i=>Math.max(0,i)&255;return s=Ue.fromDate2DOS(new Date),{get made(){return r},set made(i){r=i},get version(){return e},set version(i){e=i},get flags(){return t},set flags(i){t=i},get flags_efs(){return(t&R.FLG_EFS)>0},set flags_efs(i){i?t|=R.FLG_EFS:t&=~R.FLG_EFS},get flags_desc(){return(t&R.FLG_DESC)>0},set flags_desc(i){i?t|=R.FLG_DESC:t&=~R.FLG_DESC},get method(){return n},set method(i){switch(i){case R.STORED:this.version=10;case R.DEFLATED:default:this.version=20}n=i},get time(){return Ue.fromDOS2Date(this.timeval)},set time(i){this.timeval=Ue.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=y(i)},get timeHighByte(){return m(s>>>8)},get crc(){return o},set crc(i){o=y(i)},get compressedSize(){return l},set compressedSize(i){l=y(i)},get size(){return c},set size(i){c=y(i)},get fileNameLength(){return u},set fileNameLength(i){u=i},get extraLength(){return a},set extraLength(i){a=i},get extraLocalLength(){return E.extraLen},set extraLocalLength(i){E.extraLen=i},get commentLength(){return p},set commentLength(i){p=i},get diskNumStart(){return g},set diskNumStart(i){g=y(i)},get inAttr(){return _},set inAttr(i){_=y(i)},get attr(){return f},set attr(i){f=y(i)},get fileAttr(){return(f||0)>>16&4095},get offset(){return h},set offset(i){h=y(i)},get encrypted(){return(t&R.FLG_ENC)===R.FLG_ENC},get centralHeaderSize(){return R.CENHDR+u+a+p},get realDataOffset(){return h+R.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:function(i){var d=i.slice(h,h+R.LOCHDR);if(d.readUInt32LE(0)!==R.LOCSIG)throw Ue.Errors.INVALID_LOC();E.version=d.readUInt16LE(R.LOCVER),E.flags=d.readUInt16LE(R.LOCFLG),E.method=d.readUInt16LE(R.LOCHOW),E.time=d.readUInt32LE(R.LOCTIM),E.crc=d.readUInt32LE(R.LOCCRC),E.compressedSize=d.readUInt32LE(R.LOCSIZ),E.size=d.readUInt32LE(R.LOCLEN),E.fnameLen=d.readUInt16LE(R.LOCNAM),E.extraLen=d.readUInt16LE(R.LOCEXT);let S=h+R.LOCHDR+E.fnameLen,b=S+E.extraLen;return i.slice(S,b)},loadFromBinary:function(i){if(i.length!==R.CENHDR||i.readUInt32LE(0)!==R.CENSIG)throw Ue.Errors.INVALID_CEN();r=i.readUInt16LE(R.CENVEM),e=i.readUInt16LE(R.CENVER),t=i.readUInt16LE(R.CENFLG),n=i.readUInt16LE(R.CENHOW),s=i.readUInt32LE(R.CENTIM),o=i.readUInt32LE(R.CENCRC),l=i.readUInt32LE(R.CENSIZ),c=i.readUInt32LE(R.CENLEN),u=i.readUInt16LE(R.CENNAM),a=i.readUInt16LE(R.CENEXT),p=i.readUInt16LE(R.CENCOM),g=i.readUInt16LE(R.CENDSK),_=i.readUInt16LE(R.CENATT),f=i.readUInt32LE(R.CENATX),h=i.readUInt32LE(R.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(R.LOCHDR);return i.writeUInt32LE(R.LOCSIG,0),i.writeUInt16LE(e,R.LOCVER),i.writeUInt16LE(t,R.LOCFLG),i.writeUInt16LE(n,R.LOCHOW),i.writeUInt32LE(s,R.LOCTIM),i.writeUInt32LE(o,R.LOCCRC),i.writeUInt32LE(l,R.LOCSIZ),i.writeUInt32LE(c,R.LOCLEN),i.writeUInt16LE(u,R.LOCNAM),i.writeUInt16LE(E.extraLen,R.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(R.CENHDR+u+a+p);return i.writeUInt32LE(R.CENSIG,0),i.writeUInt16LE(r,R.CENVEM),i.writeUInt16LE(e,R.CENVER),i.writeUInt16LE(t,R.CENFLG),i.writeUInt16LE(n,R.CENHOW),i.writeUInt32LE(s,R.CENTIM),i.writeUInt32LE(o,R.CENCRC),i.writeUInt32LE(l,R.CENSIZ),i.writeUInt32LE(c,R.CENLEN),i.writeUInt16LE(u,R.CENNAM),i.writeUInt16LE(a,R.CENEXT),i.writeUInt16LE(p,R.CENCOM),i.writeUInt16LE(g,R.CENDSK),i.writeUInt16LE(_,R.CENATT),i.writeUInt32LE(f,R.CENATX),i.writeUInt32LE(h,R.CENOFF),i},toJSON:function(){let i=function(d){return d+" bytes"};return{made:r,version:e,flags:t,method:Ue.methodToString(n),time:this.time,crc:"0x"+o.toString(16).toUpperCase(),compressedSize:i(l),size:i(c),fileNameLength:i(u),extraLength:i(a),commentLength:i(p),diskNumStart:g,inAttr:_,attr:f,offset:h,centralHeaderSize:i(R.CENHDR+u+a+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var us=Z((_c,ls)=>{"use strict";var lt=ct(),J=lt.Constants;ls.exports=function(){var r=0,e=0,t=0,n=0,s=0;return{get diskEntries(){return r},set diskEntries(o){r=e=o},get totalEntries(){return e},set totalEntries(o){e=r=o},get size(){return t},set size(o){t=o},get offset(){return n},set offset(o){n=o},get commentLength(){return s},set commentLength(o){s=o},get mainHeaderSize(){return J.ENDHDR+s},loadFromBinary:function(o){if((o.length!==J.ENDHDR||o.readUInt32LE(0)!==J.ENDSIG)&&(o.length<J.ZIP64HDR||o.readUInt32LE(0)!==J.ZIP64SIG))throw lt.Errors.INVALID_END();o.readUInt32LE(0)===J.ENDSIG?(r=o.readUInt16LE(J.ENDSUB),e=o.readUInt16LE(J.ENDTOT),t=o.readUInt32LE(J.ENDSIZ),n=o.readUInt32LE(J.ENDOFF),s=o.readUInt16LE(J.ENDCOM)):(r=lt.readBigUInt64LE(o,J.ZIP64SUB),e=lt.readBigUInt64LE(o,J.ZIP64TOT),t=lt.readBigUInt64LE(o,J.ZIP64SIZE),n=lt.readBigUInt64LE(o,J.ZIP64OFF),s=0)},toBinary:function(){var o=Buffer.alloc(J.ENDHDR+s);return o.writeUInt32LE(J.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(r,J.ENDSUB),o.writeUInt16LE(e,J.ENDTOT),o.writeUInt32LE(t,J.ENDSIZ),o.writeUInt32LE(n,J.ENDOFF),o.writeUInt16LE(s,J.ENDCOM),o.fill(" ",J.ENDHDR),o},toJSON:function(){let o=function(l,c){let u=l.toString(16).toUpperCase();for(;u.length<c;)u="0"+u;return"0x"+u};return{diskEntries:r,totalEntries:e,size:t+" bytes",offset:o(n,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Mr=Z(Fr=>{"use strict";Fr.EntryHeader=cs();Fr.MainHeader=us()});var ds=Z((Oc,fs)=>{"use strict";fs.exports=function(r){var e=require("zlib"),t={chunkSize:(parseInt(r.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(r,t)},deflateAsync:function(n){var s=e.createDeflateRaw(t),o=[],l=0;s.on("data",function(c){o.push(c),l+=c.length}),s.on("end",function(){var c=Buffer.alloc(l),u=0;c.fill(0);for(var a=0;a<o.length;a++){var p=o[a];p.copy(c,u),u+=p.length}n&&n(c)}),s.end(r)}}}});var ms=Z((kc,ps)=>{"use strict";var Li=+(process.versions?process.versions.node:"").split(".")[0]||0;ps.exports=function(r,e){var t=require("zlib");let n=Li>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(r,n)},inflateAsync:function(s){var o=t.createInflateRaw(n),l=[],c=0;o.on("data",function(u){l.push(u),c+=u.length}),o.on("end",function(){var u=Buffer.alloc(c),a=0;u.fill(0);for(var p=0;p<l.length;p++){var g=l[p];g.copy(u,a),a+=g.length}s&&s(u)}),o.end(r)}}}});var Es=Z((vc,Ss)=>{"use strict";var{randomFillSync:hs}=require("crypto"),Fi=jt(),Mi=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),ys=(r,e)=>Math.imul(r,e)>>>0,gs=(r,e)=>Mi[(r^e)&255]^r>>>8,bt=()=>typeof hs=="function"?hs(Buffer.alloc(12)):bt.node();bt.node=()=>{let r=Buffer.alloc(12),e=r.length;for(let t=0;t<e;t++)r[t]=Math.random()*256&255;return r};var Dt={genSalt:bt};function Nt(r){let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}Nt.prototype.updateKeys=function(r){let e=this.keys;return e[0]=gs(e[0],r),e[1]+=e[0]&255,e[1]=ys(e[1],134775813)+1,e[2]=gs(e[2],e[1]>>>24),r};Nt.prototype.next=function(){let r=(this.keys[2]|2)>>>0;return ys(r,r^1)>>8&255};function Ui(r){let e=new Nt(r);return function(t){let n=Buffer.alloc(t.length),s=0;for(let o of t)n[s++]=e.updateKeys(o^e.next());return n}}function Hi(r){let e=new Nt(r);return function(t,n,s=0){n||(n=Buffer.alloc(t.length));for(let o of t){let l=e.next();n[s++]=o^l,e.updateKeys(o)}return n}}function Bi(r,e,t){if(!r||!Buffer.isBuffer(r)||r.length<12)return Buffer.alloc(0);let n=Ui(t),s=n(r.slice(0,12)),o=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==o)throw Fi.WRONG_PASSWORD();return n(r.slice(12))}function Wi(r){Buffer.isBuffer(r)&&r.length>=12?Dt.genSalt=function(){return r.slice(0,12)}:r==="node"?Dt.genSalt=bt.node:Dt.genSalt=bt}function Vi(r,e,t,n=!1){r==null&&(r=Buffer.alloc(0)),Buffer.isBuffer(r)||(r=Buffer.from(r.toString()));let s=Hi(t),o=Dt.genSalt();o[11]=e.crc>>>24&255,n&&(o[10]=e.crc>>>16&255);let l=Buffer.alloc(r.length+12);return s(o,l),s(r,l,12)}Ss.exports={decrypt:Bi,encrypt:Vi,_salter:Wi}});var Cs=Z($t=>{"use strict";$t.Deflater=ds();$t.Inflater=ms();$t.ZipCrypto=Es()});var Hr=Z((Rc,ws)=>{"use strict";var B=ct(),qi=Mr(),Y=B.Constants,Ur=Cs();ws.exports=function(r,e){var t=new qi.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),o=!1,l=null,c=Buffer.alloc(0),u=Buffer.alloc(0),a=!0;let p=r,g=typeof p.decoder=="object"?p.decoder:B.decoder;a=g.hasOwnProperty("efs")?g.efs:!1;function _(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function f(i){if(t.flags_desc){let d={},S=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(S)==Y.LOCSIG||e.readUInt32LE(S)==Y.CENSIG)throw B.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(S)==Y.EXTSIG)d.crc=e.readUInt32LE(S+Y.EXTCRC),d.compressedSize=e.readUInt32LE(S+Y.EXTSIZ),d.size=e.readUInt32LE(S+Y.EXTLEN);else if(e.readUInt16LE(S+12)===19280)d.crc=e.readUInt32LE(S+Y.EXTCRC-4),d.compressedSize=e.readUInt32LE(S+Y.EXTSIZ-4),d.size=e.readUInt32LE(S+Y.EXTLEN-4);else throw B.Errors.DESCRIPTOR_UNKNOWN();if(d.compressedSize!==t.compressedSize||d.size!==t.size||d.crc!==t.crc)throw B.Errors.DESCRIPTOR_FAULTY();if(B.crc32(i)!==d.crc)return!1}else if(B.crc32(i)!==t.localHeader.crc)return!1;return!0}function h(i,d,S){if(typeof d>"u"&&typeof i=="string"&&(S=i,i=void 0),o)return i&&d&&d(Buffer.alloc(0),B.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var b=_();if(b.length===0)return i&&d&&d(b),b;if(t.encrypted){if(typeof S!="string"&&!Buffer.isBuffer(S))throw B.Errors.INVALID_PASS_PARAM();b=Ur.ZipCrypto.decrypt(b,t,S)}var A=Buffer.alloc(t.size);switch(t.method){case B.Constants.STORED:if(b.copy(A),f(A))return i&&d&&d(A),A;throw i&&d&&d(A,B.Errors.BAD_CRC()),B.Errors.BAD_CRC();case B.Constants.DEFLATED:var I=new Ur.Inflater(b,t.size);if(i)I.inflateAsync(function(O){O.copy(O,0),d&&(f(O)?d(O):d(O,B.Errors.BAD_CRC()))});else{if(I.inflate(A).copy(A,0),!f(A))throw B.Errors.BAD_CRC(`"${g.decode(n)}"`);return A}break;default:throw i&&d&&d(Buffer.alloc(0),B.Errors.UNKNOWN_METHOD()),B.Errors.UNKNOWN_METHOD()}}function E(i,d){if((!l||!l.length)&&Buffer.isBuffer(e))return i&&d&&d(_()),_();if(l.length&&!o){var S;switch(t.method){case B.Constants.STORED:return t.compressedSize=t.size,S=Buffer.alloc(l.length),l.copy(S),i&&d&&d(S),S;default:case B.Constants.DEFLATED:var b=new Ur.Deflater(l);if(i)b.deflateAsync(function(I){S=Buffer.alloc(I.length),t.compressedSize=I.length,I.copy(S),d&&d(S)});else{var A=b.deflate();return t.compressedSize=A.length,A}b=null;break}}else if(i&&d)d(Buffer.alloc(0));else return Buffer.alloc(0)}function y(i,d){return(i.readUInt32LE(d+4)<<4)+i.readUInt32LE(d)}function C(i){try{for(var d=0,S,b,A;d+4<i.length;)S=i.readUInt16LE(d),d+=2,b=i.readUInt16LE(d),d+=2,A=i.slice(d,d+b),d+=b,Y.ID_ZIP64===S&&m(A)}catch{throw B.Errors.EXTRA_FIELD_PARSE_ERROR()}}function m(i){var d,S,b,A;i.length>=Y.EF_ZIP64_SCOMP&&(d=y(i,Y.EF_ZIP64_SUNCOMP),t.size===Y.EF_ZIP64_OR_32&&(t.size=d)),i.length>=Y.EF_ZIP64_RHO&&(S=y(i,Y.EF_ZIP64_SCOMP),t.compressedSize===Y.EF_ZIP64_OR_32&&(t.compressedSize=S)),i.length>=Y.EF_ZIP64_DSN&&(b=y(i,Y.EF_ZIP64_RHO),t.offset===Y.EF_ZIP64_OR_32&&(t.offset=b)),i.length>=Y.EF_ZIP64_DSN+4&&(A=i.readUInt32LE(Y.EF_ZIP64_DSN),t.diskNumStart===Y.EF_ZIP64_OR_16&&(t.diskNumStart=A))}return{get entryName(){return g.decode(n)},get rawEntryName(){return n},set entryName(i){n=B.toBuffer(i,g.encode);var d=n[n.length-1];o=d===47||d===92,t.fileNameLength=n.length},get efs(){return typeof a=="function"?a(this.entryName):a},get extra(){return c},set extra(i){c=i,t.extraLength=i.length,C(i)},get comment(){return g.decode(s)},set comment(i){if(s=B.toBuffer(i,g.encode),t.commentLength=s.length,s.length>65535)throw B.Errors.COMMENT_TOO_LONG()},get name(){var i=g.decode(n);return o?i.substr(i.length-1).split("/").pop():i.split("/").pop()},get isDirectory(){return o},getCompressedData:function(){return E(!1,null)},getCompressedDataAsync:function(i){E(!0,i)},setData:function(i){l=B.toBuffer(i,B.decoder.encode),!o&&l.length?(t.size=l.length,t.method=B.Constants.DEFLATED,t.crc=B.crc32(i),t.changed=!0):t.method=B.Constants.STORED},getData:function(i){return t.changed?l:h(!1,null,i)},getDataAsync:function(i,d){t.changed?i(l):h(!0,i,d)},set attr(i){t.attr=i},get attr(){return t.attr},set header(i){t.loadFromBinary(i)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=c.length;var i=t.centralHeaderToBinary(),d=B.Constants.CENHDR;return n.copy(i,d),d+=n.length,c.copy(i,d),d+=t.extraLength,s.copy(i,d),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=u.length;let d=t.localHeaderToBinary(),S=Buffer.alloc(d.length+n.length+t.extraLocalLength);return d.copy(S,i),i+=d.length,n.copy(S,i),i+=n.length,u.copy(S,i),i+=u.length,S},toJSON:function(){let i=function(d){return"<"+(d&&d.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:i(e),data:i(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Is=Z((Pc,As)=>{"use strict";var bs=Hr(),Gi=Mr(),de=ct();As.exports=function(r,e){var t=[],n={},s=Buffer.alloc(0),o=new Gi.MainHeader,l=!1,c=null;let u=new Set,a=e,{noSort:p,decoder:g}=a;r?h(a.readEntries):l=!0;function _(){let y=new Set;for(let C of Object.keys(n)){let m=C.split("/");if(m.pop(),!!m.length)for(let i=0;i<m.length;i++){let d=m.slice(0,i+1).join("/")+"/";y.add(d)}}for(let C of y)if(!(C in n)){let m=new bs(a);m.entryName=C,m.attr=16,m.temporary=!0,t.push(m),n[m.entryName]=m,u.add(m)}}function f(){if(l=!0,n={},o.diskEntries>(r.length-o.offset)/de.Constants.CENHDR)throw de.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(o.diskEntries);for(var y=o.offset,C=0;C<t.length;C++){var m=y,i=new bs(a,r);i.header=r.slice(m,m+=de.Constants.CENHDR),i.entryName=r.slice(m,m+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(m,m+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(m,m+i.header.commentLength)),y+=i.header.centralHeaderSize,t[C]=i,n[i.entryName]=i}u.clear(),_()}function h(y){var C=r.length-de.Constants.ENDHDR,m=Math.max(0,C-65535),i=m,d=r.length,S=-1,b=0;for(typeof a.trailingSpace=="boolean"&&a.trailingSpace&&(m=0),C;C>=i;C--)if(r[C]===80){if(r.readUInt32LE(C)===de.Constants.ENDSIG){S=C,b=C,d=C+de.Constants.ENDHDR,i=C-de.Constants.END64HDR;continue}if(r.readUInt32LE(C)===de.Constants.END64SIG){i=m;continue}if(r.readUInt32LE(C)===de.Constants.ZIP64SIG){S=C,d=C+de.readBigUInt64LE(r,C+de.Constants.ZIP64SIZE)+de.Constants.ZIP64LEAD;break}}if(S==-1)throw de.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(S,d)),o.commentLength&&(s=r.slice(b+de.Constants.ENDHDR)),y&&f()}function E(){t.length>1&&!p&&t.sort((y,C)=>y.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return l||f(),t.filter(y=>!u.has(y))},get comment(){return g.decode(s)},set comment(y){s=de.toBuffer(y,g.encode),o.commentLength=s.length},getEntryCount:function(){return l?t.length:o.diskEntries},forEach:function(y){this.entries.forEach(y)},getEntry:function(y){return l||f(),n[y]||null},setEntry:function(y){l||f(),t.push(y),n[y.entryName]=y,o.totalEntries=t.length},deleteFile:function(y,C=!0){l||f();let m=n[y];this.getEntryChildren(m,C).map(d=>d.entryName).forEach(this.deleteEntry)},deleteEntry:function(y){l||f();let C=n[y],m=t.indexOf(C);m>=0&&(t.splice(m,1),delete n[y],o.totalEntries=t.length)},getEntryChildren:function(y,C=!0){if(l||f(),typeof y=="object")if(y.isDirectory&&C){let m=[],i=y.entryName;for(let d of t)d.entryName.startsWith(i)&&m.push(d);return m}else return[y];return[]},getChildCount:function(y){if(y&&y.isDirectory){let C=this.getEntryChildren(y);return C.includes(y)?C.length-1:C.length}return 0},compressToBuffer:function(){l||f(),E();let y=[],C=[],m=0,i=0;o.size=0,o.offset=0;let d=0;for(let A of this.entries){let I=A.getCompressedData();A.header.offset=i;let O=A.packLocalHeader(),k=O.length+I.length;i+=k,y.push(O),y.push(I);let v=A.packCentralHeader();C.push(v),o.size+=v.length,m+=k+v.length,d++}m+=o.mainHeaderSize,o.offset=i,o.totalEntries=d,i=0;let S=Buffer.alloc(m);for(let A of y)A.copy(S,i),i+=A.length;for(let A of C)A.copy(S,i),i+=A.length;let b=o.toBinary();return s&&s.copy(b,de.Constants.ENDHDR),b.copy(S,i),r=S,l=!1,S},toAsyncBuffer:function(y,C,m,i){try{l||f(),E();let d=[],S=[],b=0,A=0,I=0;o.size=0,o.offset=0;let O=function(k){if(k.length>0){let v=k.shift(),P=v.entryName+v.extra.toString();m&&m(P),v.getCompressedDataAsync(function(j){i&&i(P),v.header.offset=A;let U=v.packLocalHeader(),W=U.length+j.length;A+=W,d.push(U),d.push(j);let ee=v.packCentralHeader();S.push(ee),o.size+=ee.length,b+=W+ee.length,I++,O(k)})}else{b+=o.mainHeaderSize,o.offset=A,o.totalEntries=I,A=0;let v=Buffer.alloc(b);d.forEach(function(j){j.copy(v,A),A+=j.length}),S.forEach(function(j){j.copy(v,A),A+=j.length});let P=o.toBinary();s&&s.copy(P,de.Constants.ENDHDR),P.copy(v,A),r=v,l=!1,y(v)}};O(Array.from(this.entries))}catch(d){C(d)}}}}});var Os=Z((jc,xs)=>{"use strict";var K=ct(),Q=require("path"),zi=Hr(),Zi=Is(),Xe=(...r)=>K.findLast(r,e=>typeof e=="boolean"),_s=(...r)=>K.findLast(r,e=>typeof e=="string"),Ji=(...r)=>K.findLast(r,e=>typeof e=="function"),Ki={noSort:!1,readEntries:!1,method:K.Constants.NONE,fs:null};xs.exports=function(r,e){let t=null,n=Object.assign(Object.create(null),Ki);r&&typeof r=="object"&&(r instanceof Uint8Array||(Object.assign(n,r),r=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(r)&&(t=r,n.method=K.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new K(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=K.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=K.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw K.Errors.INVALID_FILENAME();let o=new Zi(t,n),{canonical:l,sanitize:c,zipnamefix:u}=K;function a(f){if(f&&o){var h;if(typeof f=="string"&&(h=o.getEntry(Q.posix.normalize(f))),typeof f=="object"&&typeof f.entryName<"u"&&typeof f.header<"u"&&(h=o.getEntry(f.entryName)),h)return h}return null}function p(f){let{join:h,normalize:E,sep:y}=Q.posix;return h(".",E(y+f.split("\\").join(y)+y))}function g(f){return f instanceof RegExp?(function(h){return function(E){return h.test(E)}})(f):typeof f!="function"?()=>!0:f}let _=(f,h)=>{let E=h.slice(-1);return E=E===s.sep?s.sep:"",Q.relative(f,h)+E};return{readFile:function(f,h){var E=a(f);return E&&E.getData(h)||null},childCount:function(f){let h=a(f);if(h)return o.getChildCount(h)},readFileAsync:function(f,h){var E=a(f);E?E.getDataAsync(h):h(null,"getEntry failed for:"+f)},readAsText:function(f,h){var E=a(f);if(E){var y=E.getData();if(y&&y.length)return y.toString(h||"utf8")}return""},readAsTextAsync:function(f,h,E){var y=a(f);y?y.getDataAsync(function(C,m){if(m){h(C,m);return}C&&C.length?h(C.toString(E||"utf8")):h("")}):h("")},deleteFile:function(f,h=!0){var E=a(f);E&&o.deleteFile(E.entryName,h)},deleteEntry:function(f){var h=a(f);h&&o.deleteEntry(h.entryName)},addZipComment:function(f){o.comment=f},getZipComment:function(){return o.comment||""},addZipEntryComment:function(f,h){var E=a(f);E&&(E.comment=h)},getZipEntryComment:function(f){var h=a(f);return h&&h.comment||""},updateFile:function(f,h){var E=a(f);E&&E.setData(h)},addLocalFile:function(f,h,E,y){if(s.fs.existsSync(f)){h=h?p(h):"";let C=Q.win32.basename(Q.win32.normalize(f));h+=E||C;let m=s.fs.statSync(f),i=m.isFile()?s.fs.readFileSync(f):Buffer.alloc(0);m.isDirectory()&&(h+=s.sep),this.addFile(h,i,y,m)}else throw K.Errors.FILE_NOT_FOUND(f)},addLocalFileAsync:function(f,h){f=typeof f=="object"?f:{localPath:f};let E=Q.resolve(f.localPath),{comment:y}=f,{zipPath:C,zipName:m}=f,i=this;s.fs.stat(E,function(d,S){if(d)return h(d,!1);C=C?p(C):"";let b=Q.win32.basename(Q.win32.normalize(E));if(C+=m||b,S.isFile())s.fs.readFile(E,function(A,I){return A?h(A,!1):(i.addFile(C,I,y,S),setImmediate(h,void 0,!0))});else if(S.isDirectory())return C+=s.sep,i.addFile(C,Buffer.alloc(0),y,S),setImmediate(h,void 0,!0)})},addLocalFolder:function(f,h,E){if(E=g(E),h=h?p(h):"",f=Q.normalize(f),s.fs.existsSync(f)){let y=s.findFiles(f),C=this;if(y.length)for(let m of y){let i=Q.join(h,_(f,m));E(i)&&C.addLocalFile(m,Q.dirname(i))}}else throw K.Errors.FILE_NOT_FOUND(f)},addLocalFolderAsync:function(f,h,E,y){y=g(y),E=E?p(E):"",f=Q.normalize(f);var C=this;s.fs.open(f,"r",function(m){if(m&&m.code==="ENOENT")h(void 0,K.Errors.FILE_NOT_FOUND(f));else if(m)h(void 0,m);else{var i=s.findFiles(f),d=-1,S=function(){if(d+=1,d<i.length){var b=i[d],A=_(f,b).split("\\").join("/");A=A.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),y(A)?s.fs.stat(b,function(I,O){I&&h(void 0,I),O.isFile()?s.fs.readFile(b,function(k,v){k?h(void 0,k):(C.addFile(E+A,v,"",O),S())}):(C.addFile(E+A+"/",Buffer.alloc(0),"",O),S())}):process.nextTick(()=>{S()})}else h(!0,void 0)};S()}})},addLocalFolderAsync2:function(f,h){let E=this;f=typeof f=="object"?f:{localPath:f},localPath=Q.resolve(p(f.localPath));let{zipPath:y,filter:C,namefix:m}=f;C instanceof RegExp?C=(function(S){return function(b){return S.test(b)}})(C):typeof C!="function"&&(C=function(){return!0}),y=y?p(y):"",m=="latin1"&&(m=S=>S.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof m!="function"&&(m=S=>S);let i=S=>Q.join(y,m(_(localPath,S))),d=S=>Q.win32.basename(Q.win32.normalize(m(S)));s.fs.open(localPath,"r",function(S){S&&S.code==="ENOENT"?h(void 0,K.Errors.FILE_NOT_FOUND(localPath)):S?h(void 0,S):s.findFilesAsync(localPath,function(b,A){if(b)return h(b);A=A.filter(I=>C(i(I))),A.length||h(void 0,!1),setImmediate(A.reverse().reduce(function(I,O){return function(k,v){if(k||v===!1)return setImmediate(I,k,!1);E.addLocalFileAsync({localPath:O,zipPath:Q.dirname(i(O)),zipName:d(O)},I)}},h))})})},addLocalFolderPromise:function(f,h){return new Promise((E,y)=>{this.addLocalFolderAsync2(Object.assign({localPath:f},h),(C,m)=>{C&&y(C),m&&E(this)})})},addFile:function(f,h,E,y){f=u(f);let C=a(f),m=C!=null;m||(C=new zi(n),C.entryName=f),C.comment=E||"";let i=typeof y=="object"&&y instanceof s.fs.Stats;i&&(C.header.time=y.mtime);var d=C.isDirectory?16:0;let S=C.isDirectory?16384:32768;return i?S|=4095&y.mode:typeof y=="number"?S|=4095&y:S|=C.isDirectory?493:420,d=(d|S<<16)>>>0,C.attr=d,C.setData(h),m||o.setEntry(C),C},getEntries:function(f){return o.password=f,o?o.entries:[]},getEntry:function(f){return a(f)},getEntryCount:function(){return o.getEntryCount()},forEach:function(f){return o.forEach(f)},extractEntryTo:function(f,h,E,y,C,m){y=Xe(!1,y),C=Xe(!1,C),E=Xe(!0,E),m=_s(C,m);var i=a(f);if(!i)throw K.Errors.NO_ENTRY();var d=l(i.entryName),S=c(h,m&&!i.isDirectory?m:E?d:Q.basename(d));if(i.isDirectory){var b=o.getEntryChildren(i);return b.forEach(function(O){if(O.isDirectory)return;var k=O.getData();if(!k)throw K.Errors.CANT_EXTRACT_FILE();var v=l(O.entryName),P=c(h,E?v:Q.basename(v));let j=C?O.header.fileAttr:void 0;s.writeFileTo(P,k,y,j)}),!0}var A=i.getData(o.password);if(!A)throw K.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(S)&&!y)throw K.Errors.CANT_OVERRIDE();let I=C?f.header.fileAttr:void 0;return s.writeFileTo(S,A,y,I),!0},test:function(f){if(!o)return!1;for(var h in o.entries)try{if(h.isDirectory)continue;var E=o.entries[h].getData(f);if(!E)return!1}catch{return!1}return!0},extractAllTo:function(f,h,E,y){if(E=Xe(!1,E),y=_s(E,y),h=Xe(!1,h),!o)throw K.Errors.NO_ZIP();o.entries.forEach(function(C){var m=c(f,l(C.entryName));if(C.isDirectory){s.makeDir(m);return}var i=C.getData(y);if(!i)throw K.Errors.CANT_EXTRACT_FILE();let d=E?C.header.fileAttr:void 0;s.writeFileTo(m,i,h,d);try{s.fs.utimesSync(m,C.header.time,C.header.time)}catch{throw K.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(f,h,E,y){if(y=Ji(h,E,y),E=Xe(!1,E),h=Xe(!1,h),!y)return new Promise((S,b)=>{this.extractAllToAsync(f,h,E,function(A){A?b(A):S(this)})});if(!o){y(K.Errors.NO_ZIP());return}f=Q.resolve(f);let C=S=>c(f,Q.normalize(l(S.entryName))),m=(S,b)=>new Error(S+': "'+b+'"'),i=[],d=[];o.entries.forEach(S=>{S.isDirectory?i.push(S):d.push(S)});for(let S of i){let b=C(S),A=E?S.header.fileAttr:void 0;try{s.makeDir(b),A&&s.fs.chmodSync(b,A),s.fs.utimesSync(b,S.header.time,S.header.time)}catch{y(m("Unable to create folder",b))}}d.reverse().reduce(function(S,b){return function(A){if(A)S(A);else{let I=Q.normalize(l(b.entryName)),O=c(f,I);b.getDataAsync(function(k,v){if(v)S(v);else if(!k)S(K.Errors.CANT_EXTRACT_FILE());else{let P=E?b.header.fileAttr:void 0;s.writeFileToAsync(O,k,h,P,function(j){j||S(m("Unable to write file",O)),s.fs.utimes(O,b.header.time,b.header.time,function(U){U?S(m("Unable to set times",O)):S()})})}})}}},y)()},writeZip:function(f,h){if(arguments.length===1&&typeof f=="function"&&(h=f,f=""),!f&&n.filename&&(f=n.filename),!!f){var E=o.compressToBuffer();if(E){var y=s.writeFileTo(f,E,!0);typeof h=="function"&&h(y?null:new Error("failed"),"")}}},writeZipPromise:function(f,h){let{overwrite:E,perm:y}=Object.assign({overwrite:!0},h);return new Promise((C,m)=>{!f&&n.filename&&(f=n.filename),f||m("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let d=S=>S?C(S):m("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(f,i,E,y,d)},m)})},toBufferPromise:function(){return new Promise((f,h)=>{o.toAsyncBuffer(f,h)})},toBuffer:function(f,h,E,y){return typeof f=="function"?(o.toAsyncBuffer(f,h,E,y),null):o.compressToBuffer()}}}});var Gs={};gt(Gs,{enableTelemetryHook:()=>qs,registerConfig:()=>Jr});function Zr(){let r=process.env.SC_PROFILE;return r?(0,De.join)((0,pt.homedir)(),".config","shared-context","profiles",r):(0,De.join)((0,pt.homedir)(),".config","shared-context")}function qs(){try{let r=(0,De.join)((0,pt.homedir)(),".claude","settings.json"),{readFileSync:e,writeFileSync:t}=require("fs"),n={};try{(0,Be.existsSync)(r)&&(n=JSON.parse(e(r,"utf8")))}catch{}n.hooks||(n.hooks={});let s=n.hooks;if(s.PostToolUse||(s.PostToolUse=[]),s.PostToolUse.some(p=>p._sc===Vs))return;let l=(0,De.join)(Zr(),"manifest.json"),c="";try{let g=(JSON.parse(e(l,"utf8")).installations||[]).find(_=>_.slug==="telemetry"||_.installPath?.includes("hooks/telemetry"));g?.installPath&&(c=(0,De.join)((0,pt.homedir)(),".config","shared-context",g.installPath,"scripts","telemetry.js"))}catch{}if((!c||!(0,Be.existsSync)(c))&&(c=(0,De.join)(Zr(),"hooks","telemetry","scripts","telemetry.js")),!(0,Be.existsSync)(c))return;s.PostToolUse.push({hooks:[{type:"command",command:`node ${c}`}],_sc:Vs}),s.SessionStart||(s.SessionStart=[]);let u="platform/telemetry-push";s.SessionStart.some(p=>p._sc===u)||s.SessionStart.push({hooks:[{type:"command",command:"npx shared-context-ai telemetry push --quiet 2>/dev/null || true"}],_sc:u}),t(r,JSON.stringify(n,null,2)+`
30
- `,"utf8")}catch{}}function Sa(){vt({telemetry:!1});let r=(0,De.join)(Zr(),"usage.jsonl");try{(0,Be.existsSync)(r)&&(0,Be.unlinkSync)(r)}catch{}try{let e=(0,De.join)((0,pt.homedir)(),".claude","settings.json");if((0,Be.existsSync)(e)){let{readFileSync:t,writeFileSync:n}=require("fs"),s=JSON.parse(t(e,"utf8"));if(s.hooks){let o=!1,l=new Set(["hooks/shared-context/telemetry","platform/telemetry-push"]);for(let[c,u]of Object.entries(s.hooks))if(Array.isArray(u)){let a=u.filter(p=>!l.has(p._sc));a.length!==u.length&&(s.hooks[c]=a,o=!0)}for(let[c,u]of Object.entries(s.hooks))Array.isArray(u)&&u.length===0&&delete s.hooks[c];o&&n(e,JSON.stringify(s,null,2)+`
31
- `,"utf8")}}}catch{}}function Jr(r){let e=r.command("config").description("Manage CLI configuration");e.command("set <key> <value>").description("Set a configuration value (e.g., telemetry on/off)").action((t,n)=>{if(t==="telemetry"){let s=n==="on"||n==="true"||n==="1",o=n==="off"||n==="false"||n==="0";if(!s&&!o){x()?D("config","INVALID_VALUE","Telemetry value must be on or off"):T("Usage: shared-context-ai config set telemetry on|off");return}o?(Sa(),x()?N("config",{key:"telemetry",value:!1}):w("Telemetry disabled. Usage data and hooks removed.")):(vt({telemetry:!0}),qs(),x()?N("config",{key:"telemetry",value:!0}):w("Telemetry enabled. Usage data will be collected and uploaded."));return}x()?D("config","UNKNOWN_KEY",`Unknown config key: ${t}`):T(`Unknown config key: ${t}. Available: telemetry`)}),e.command("get [key]").description("Show configuration values").action(t=>{let n=Ie();if(t==="telemetry"){let s=n.telemetry??!1;x()?N("config",{key:"telemetry",value:s}):w(`telemetry: ${s?"on":"off"}`);return}if(t){x()?D("config","UNKNOWN_KEY",`Unknown config key: ${t}`):T(`Unknown config key: ${t}`);return}x()?N("config",{telemetry:n.telemetry??!1}):w(`telemetry: ${n.telemetry?"on":"off"}`)})}var Be,De,pt,Vs,Kr=pe(()=>{"use strict";Be=require("fs"),De=require("path"),pt=require("os");ce();re();Vs="hooks/shared-context/telemetry"});function Aa(){try{return Yr.default.statSync("/.dockerenv"),!0}catch{return!1}}function Ia(){try{return Yr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Qr(){return Xr===void 0&&(Xr=Aa()||Ia()),Xr}var Yr,Xr,Xs=pe(()=>{"use strict";Yr=me(require("fs"),1)});function nt(){return en===void 0&&(en=_a()||Qr()),en}var Ys,en,_a,tn=pe(()=>{"use strict";Ys=me(require("fs"),1);Xs();_a=()=>{try{return Ys.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var rn,eo,Qt,Qs,qe,nn=pe(()=>{"use strict";rn=me(require("process"),1),eo=me(require("os"),1),Qt=me(require("fs"),1);tn();Qs=()=>{if(rn.default.platform!=="linux")return!1;if(eo.default.release().toLowerCase().includes("microsoft"))return!nt();try{if(Qt.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!nt()}catch{}return Qt.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Qt.default.existsSync("/run/WSL")?!nt():!1},qe=rn.default.env.__IS_WSL_TEST__?Qs:Qs()});var sn,It,xa,Oa,on,to=pe(()=>{"use strict";sn=me(require("process"),1),It=me(require("fs/promises"),1);nn();nn();xa=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await It.default.access(t,It.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await It.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Oa=async()=>`${await xa()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,on=async()=>qe?Oa():`${sn.default.env.SYSTEMROOT||sn.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Ge(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var ro=pe(()=>{"use strict"});async function an(){if(so.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await ka("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var no,so,oo,ka,io=pe(()=>{"use strict";no=require("util"),so=me(require("process"),1),oo=require("child_process"),ka=(0,no.promisify)(oo.execFile)});async function lo(r,{humanReadableOutput:e=!0,signal:t}={}){if(ao.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await va("osascript",["-e",r,n],s);return o.trim()}var ao,co,cn,va,uo=pe(()=>{"use strict";ao=me(require("process"),1),co=require("util"),cn=require("child_process"),va=(0,co.promisify)(cn.execFile)});async function ln(r){return lo(`tell application "Finder" to set app_path to application file id "${r}" as string
32
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var fo=pe(()=>{"use strict";uo()});async function fn(r=Ta){let{stdout:e}=await r("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new un(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),o=n.lastIndexOf("-"),l=s===-1?void 0:n.slice(0,s),c=o===-1?void 0:n.slice(0,o);return er[n]??er[l]??er[c]??{name:n,id:n}}var po,mo,Ta,er,Ql,un,ho=pe(()=>{"use strict";po=require("util"),mo=require("child_process"),Ta=(0,po.promisify)(mo.execFile),er={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"}},Ql=new Map(Object.entries(er)),un=class extends Error{}});async function dn(){if(tr.default.platform==="darwin"){let r=await an();return{name:await ln(r),id:r}}if(tr.default.platform==="linux"){let{stdout:r}=await Ra("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Pa(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(tr.default.platform==="win32")return fn();throw new Error("Only macOS, Linux, and Windows are supported")}var go,tr,yo,Ra,Pa,So=pe(()=>{"use strict";go=require("util"),tr=me(require("process"),1),yo=require("child_process");io();fo();ho();Ra=(0,go.promisify)(yo.execFile),Pa=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var _o={};gt(_o,{apps:()=>ze,default:()=>La,openApp:()=>$a});async function Da(){let r=await on(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=hn.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await ja(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function bo(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Co]:e}=r;if(!e)throw new Error(`${Co} is not supported`);return e}function nr({[mt]:r},{wsl:e}){if(e&&qe)return bo(e);if(!r)throw new Error(`${mt} is not supported`);return bo(r)}var mn,hn,gn,Ao,Io,yn,rr,Fa,ja,pn,Eo,mt,Co,wo,_t,Na,$a,ze,La,xo=pe(()=>{"use strict";mn=me(require("process"),1),hn=require("buffer"),gn=me(require("path"),1),Ao=require("url"),Io=require("util"),yn=me(require("child_process"),1),rr=me(require("fs/promises"),1);to();ro();So();tn();Fa={},ja=(0,Io.promisify)(yn.default.execFile),pn=gn.default.dirname((0,Ao.fileURLToPath)(Fa.url)),Eo=gn.default.join(pn,"xdg-open"),{platform:mt,arch:Co}=mn.default;wo=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},_t=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return wo(r.app,c=>_t({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return wo(e,c=>_t({...r,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},a=qe?await Da():await dn();if(a.id in c){let p=c[a.id];return e==="browserPrivate"&&t.push(u[p]),_t({...r,app:{name:ze[p],arguments:t}})}throw new Error(`${a.name} is not supported as a default browser`)}let n,s=[],o={};if(mt==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(mt==="win32"||qe&&!nt()&&!e){n=await on(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),qe||(o.windowsVerbatimArguments=!0);let c=["Start"];r.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&c.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),c.push("-ArgumentList",t.join(","))),r.target=hn.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let c=!pn||pn==="/",u=!1;try{await rr.default.access(Eo,rr.constants.X_OK),u=!0}catch{}n=mn.default.versions.electron??(mt==="android"||c||!u)?"xdg-open":Eo}t.length>0&&s.push(...t),r.wait||(o.stdio="ignore",o.detached=!0)}mt==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let l=yn.default.spawn(n,s,o);return r.wait?new Promise((c,u)=>{l.once("error",u),l.once("close",a=>{if(!r.allowNonzeroExitCode&&a>0){u(new Error(`Exited with code ${a}`));return}c(l)})}):(l.unref(),l)},Na=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return _t({...e,target:r})},$a=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return _t({...e,app:{name:r,arguments:t}})};ze={};Ge(ze,"chrome",()=>nr({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"]}}));Ge(ze,"brave",()=>nr({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"]}}));Ge(ze,"firefox",()=>nr({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Ge(ze,"edge",()=>nr({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Ge(ze,"browser",()=>"browser");Ge(ze,"browserPrivate",()=>"browserPrivate");La=Na});var Jo={};gt(Jo,{pushTelemetry:()=>Zo,registerTelemetry:()=>En});function Wa(){let r=process.env.SC_PROFILE;return r?(0,ir.join)((0,Sn.homedir)(),".config","shared-context","profiles",r):(0,ir.join)((0,Sn.homedir)(),".config","shared-context")}function zo(){return(0,ir.join)(Wa(),"usage.jsonl")}function Va(){let r=zo();if(!(0,Ze.existsSync)(r))return[];try{let e=(0,Ze.readFileSync)(r,"utf8").trim().split(`
33
- `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function qa(r){let e=zo();if((0,Ze.existsSync)(e))try{let t=(0,Ze.readFileSync)(e,"utf8").trim().split(`
34
- `).filter(Boolean);if(t.length<=r)return;let n=t.slice(-r);(0,Ze.writeFileSync)(e,n.join(`
24
+ `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in H.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()}`,H.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ki(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=c=>{let a=c.attributeName(),u=this.getOptionValue(a),l=this.options.find(y=>y.negate&&a===y.attributeName()),p=this.options.find(y=>!y.negate&&a===y.attributeName());return l&&(l.presetArg===void 0&&u===!1||l.presetArg!==void 0&&u===l.presetArg)?l:p||c},s=c=>{let a=n(c),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let c=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);s=s.concat(c),o=o.parent}while(o&&!o._enablePositionalOptions);t=Ln(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=Ln(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
25
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>_i(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=$e.basename(e,$e.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=t.formatHelp(this,t);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,n,s,o;return t?(n=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(c=>c.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(c=>c.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(H.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let c;typeof t=="function"?c=t({error:o.error,command:o.command}):c=t,c&&o.write(`${c}
27
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Fn(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}function kr(){if(H.env.NO_COLOR||H.env.FORCE_COLOR==="0"||H.env.FORCE_COLOR==="false")return!1;if(H.env.FORCE_COLOR||H.env.CLICOLOR_FORCE!==void 0)return!0}Tr.Command=vr;Tr.useColor=kr});var Wn=K(xe=>{"use strict";var{Argument:Un}=Rt(),{Command:Rr}=Mn(),{CommanderError:Ti,InvalidArgumentError:Hn}=Et(),{Help:Ri}=wr(),{Option:Bn}=xr();xe.program=new Rr;xe.createCommand=r=>new Rr(r);xe.createOption=(r,e)=>new Bn(r,e);xe.createArgument=(r,e)=>new Un(r,e);xe.Command=Rr;xe.Option=Bn;xe.Argument=Un;xe.Help=Ri;xe.CommanderError=Ti;xe.InvalidArgumentError=Hn;xe.InvalidOptionArgumentError=Hn});function Zn(r,e){Gn=r,zn=e}function I(){return Gn?!0:zn?!1:!process.stdout.isTTY}function N(r,e){console.log(JSON.stringify({ok:!0,command:r,data:e}))}function D(r,e,t){console.log(JSON.stringify({ok:!1,command:r,errors:[{code:e,message:t}]}))}function w(r){console.log(r)}function T(r){console.error(r)}function ye(r,e=2){if(r.length===0)return"";let t=[];for(let n of r)for(let s=0;s<n.length;s++)t[s]=Math.max(t[s]||0,n[s].length);return r.map(n=>n.map((s,o)=>o<n.length-1?s.padEnd(t[o]+e):s).join("")).join(`
28
+ `)}var Gn,zn,se=he(()=>{"use strict";Gn=!1,zn=!1});var Nt={};St(Nt,{addToManifest:()=>le,clearAuth:()=>Nr,clearLastSyncAt:()=>He,getAuth:()=>_e,getConfig:()=>Oe,getManifest:()=>q,getSyncState:()=>Li,removeFromManifest:()=>At,saveAuth:()=>Dr,saveConfig:()=>Yn,saveManifest:()=>Ue,saveSyncState:()=>Fi,shouldSync:()=>Lr,updateConfig:()=>jt,updateManifestMeta:()=>Dt});function Ct(){let r=process.env.SC_PROFILE;return r?(0,Qe.join)(Jn,"profiles",r):Jn}function jr(){return(0,Qe.join)(Ct(),"auth.json")}function Xn(){return(0,Qe.join)(Ct(),"config.json")}function Pr(){return(0,Qe.join)(Ct(),"manifest.json")}function Pi(){(0,be.mkdirSync)(Ct(),{recursive:!0})}function wt(r,e){try{return(0,be.existsSync)(r)?JSON.parse((0,be.readFileSync)(r,"utf-8")):e}catch{return e}}function bt(r,e,t=!1){if(Pi(),(0,be.writeFileSync)(r,JSON.stringify(e,null,2)+`
29
+ `,"utf-8"),t)try{(0,be.chmodSync)(r,384)}catch{}}function _e(){return wt(jr(),null)}function Dr(r){bt(jr(),r,!0)}function Nr(){try{(0,be.writeFileSync)(jr(),"{}","utf-8")}catch{}}function Oe(){return wt(Xn(),ji)}function Yn(r){bt(Xn(),r)}function jt(r){let e=Oe();Yn({...e,...r})}function Ni(r){if(r.version&&r.version>=2)return r;let e={version:2,installations:r.installations.map(s=>({...s,serverSynced:!1}))},t=$r(),n=wt(t,null);n?.lastSyncAt&&(e.lastSyncAt=n.lastSyncAt);try{(0,be.unlinkSync)(t)}catch{}return e}function q(){let r=wt(Pr(),Di),e=Ni(r);return(!r.version||r.version<2)&&bt(Pr(),e),e}function Ue(r){bt(Pr(),r)}function le(r){let e=q(),t=e.installations.findIndex(n=>n.resourceId===r.resourceId&&n.agent===r.agent);t>=0?e.installations[t]=r:e.installations.push(r),Ue(e)}function At(r,e){let t=q();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),Ue(t)}function He(){let r=q();delete r.lastSyncAt,Ue(r)}function Dt(r){let e=q();r.lastSyncAt!==void 0&&(e.lastSyncAt=r.lastSyncAt),Ue(e)}function $r(){return(0,Qe.join)(Ct(),"last-sync.json")}function Li(){return wt($r(),null)}function Fi(r){bt($r(),r)}function Lr(){let r=parseInt(process.env.SC_SYNC_COOLDOWN||"",10),e=r>=0?r:$i,t=q();return t.lastSyncAt?Date.now()-new Date(t.lastSyncAt).getTime()>=e:!0}var be,Qe,Kn,Jn,ji,Di,$i,ue=he(()=>{"use strict";be=require("fs"),Qe=require("path"),Kn=require("os"),Jn=(0,Qe.join)((0,Kn.homedir)(),".config","shared-context");ji={apiBase:"https://sharedcontext.ai"};Di={version:2,installations:[]};$i=720*60*1e3});var ts={};St(ts,{del:()=>It,fetchRaw:()=>Fr,get:()=>Z,isAuthenticated:()=>U,patch:()=>Mi,post:()=>F});function Qn(){return Oe().apiBase||"https://sharedcontext.ai"}function es(){let r={"Content-Type":"application/json"},e=_e();return e?.token&&(r.Authorization=`Bearer ${e.token}`),r}function U(){return!!_e()?.token}async function $t(r,e,t,n){let s=`${Qn()}${e}`;try{let o={method:r,headers:es(),body:t?JSON.stringify(t):void 0};n&&(o.signal=AbortSignal.timeout(n));let c=await fetch(s,o),a=c.headers.get("content-type")||"";if(!a.includes("application/json"))return c.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${a||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${c.status}`,message:c.statusText}};let u=await c.json();return c.ok?{ok:!0,data:u.data??u}:{ok:!1,error:{code:u?.error?.code||`HTTP_${c.status}`,message:u?.error?.message||u?.message||c.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function Z(r){return $t("GET",r)}function F(r,e,t){return $t("POST",r,e,t)}function Mi(r,e){return $t("PATCH",r,e)}function It(r,e){return $t("DELETE",r,e)}async function Fr(r){let e=`${Qn()}${r}`,t=await fetch(e,{headers:es()});if(!t.ok)throw new Error(`Download failed: ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}var oe=he(()=>{"use strict";ue()});var Ur=K((Oc,rs)=>{"use strict";rs.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Lt=K(ss=>{"use strict";var ns={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Ui(r){return function(...e){return e.length&&(r=r.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+r)}}for(let r of Object.keys(ns))ss[r]=Ui(ns[r])});var ls=K((kc,cs)=>{"use strict";var Hi=require("fs"),ae=require("path"),os=Ur(),Bi=Lt(),Wi=typeof process=="object"&&process.platform==="win32",is=r=>typeof r=="object"&&r!==null,as=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Q(r){this.sep=ae.sep,this.fs=Hi,is(r)&&is(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}cs.exports=Q;Q.prototype.makeDir=function(r){let e=this;function t(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(o){if(!(!o||o.substr(-1,1)===":")){s+=e.sep+o;var c;try{c=e.fs.statSync(s)}catch{e.fs.mkdirSync(s)}if(c&&c.isFile())throw Bi.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};Q.prototype.writeFileTo=function(r,e,t,n){let s=this;if(s.fs.existsSync(r)){if(!t)return!1;var o=s.fs.statSync(r);if(o.isDirectory())return!1}var c=ae.dirname(r);s.fs.existsSync(c)||s.makeDir(c);var a;try{a=s.fs.openSync(r,"w",438)}catch{s.fs.chmodSync(r,438),a=s.fs.openSync(r,"w",438)}if(a)try{s.fs.writeSync(a,e,0,e.length,0)}finally{s.fs.closeSync(a)}return s.fs.chmodSync(r,n||438),!0};Q.prototype.writeFileToAsync=function(r,e,t,n,s){typeof n=="function"&&(s=n,n=void 0);let o=this;o.fs.exists(r,function(c){if(c&&!t)return s(!1);o.fs.stat(r,function(a,u){if(c&&u.isDirectory())return s(!1);var l=ae.dirname(r);o.fs.exists(l,function(p){p||o.makeDir(l),o.fs.open(r,"w",438,function(y,b){y?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(f,m){o.fs.write(m,e,0,e.length,0,function(){o.fs.close(m,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):b?o.fs.write(b,e,0,e.length,0,function(){o.fs.close(b,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};Q.prototype.findFiles=function(r){let e=this;function t(n,s,o){typeof s=="boolean"&&(o=s,s=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(a){let u=ae.join(n,a),l=e.fs.statSync(u);(!s||s.test(u))&&c.push(ae.normalize(u)+(l.isDirectory()?e.sep:"")),l.isDirectory()&&o&&(c=c.concat(t(u,s,o)))}),c}return t(r,void 0,!0)};Q.prototype.findFilesAsync=function(r,e){let t=this,n=[];t.fs.readdir(r,function(s,o){if(s)return e(s);let c=o.length;if(!c)return e(null,n);o.forEach(function(a){a=ae.join(r,a),t.fs.stat(a,function(u,l){if(u)return e(u);l&&(n.push(ae.normalize(a)+(l.isDirectory()?t.sep:"")),l.isDirectory()?t.findFilesAsync(a,function(p,y){if(p)return e(p);n=n.concat(y),--c||e(null,n)}):--c||e(null,n))})})})};Q.prototype.getAttributes=function(){};Q.prototype.setAttributes=function(){};Q.crc32update=function(r,e){return as[(r^e)&255]^r>>>8};Q.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=Q.crc32update(t,r[n++]);return~t>>>0};Q.methodToString=function(r){switch(r){case os.STORED:return"STORED ("+r+")";case os.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};Q.canonical=function(r){if(!r)return"";let e=ae.posix.normalize("/"+r.split("\\").join("/"));return ae.join(".",e)};Q.zipnamefix=function(r){if(!r)return"";let e=ae.posix.normalize("/"+r.split("\\").join("/"));return ae.posix.join(".",e)};Q.findLast=function(r,e){if(!Array.isArray(r))throw new TypeError("arr is not array");let t=r.length>>>0;for(let n=t-1;n>=0;n--)if(e(r[n],n,r))return r[n]};Q.sanitize=function(r,e){r=ae.resolve(ae.normalize(r));for(var t=e.split("/"),n=0,s=t.length;n<s;n++){var o=ae.normalize(ae.join(r,t.slice(n,s).join(ae.sep)));if(o.indexOf(r)===0)return o}return ae.normalize(ae.join(r,ae.basename(e)))};Q.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};Q.readBigUInt64LE=function(r,e){var t=Buffer.from(r.slice(e,e+8));return t.swap64(),parseInt(`0x${t.toString("hex")}`)};Q.fromDOS2Date=function(r){return new Date((r>>25&127)+1980,Math.max((r>>21&15)-1,0),Math.max(r>>16&31,1),r>>11&31,r>>5&63,(r&31)<<1)};Q.fromDate2DOS=function(r){let e=0,t=0;return r.getFullYear()>1979&&(e=(r.getFullYear()-1980&127)<<9|r.getMonth()+1<<5|r.getDate(),t=r.getHours()<<11|r.getMinutes()<<5|r.getSeconds()>>1),e<<16|t};Q.isWin=Wi;Q.crcTable=as});var fs=K((Tc,us)=>{"use strict";var Vi=require("path");us.exports=function(r,{fs:e}){var t=r||"",n=o(),s=null;function o(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(s=e.statSync(t),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=Vi.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ps=K((Rc,ds)=>{"use strict";ds.exports={efs:!0,encode:r=>Buffer.from(r,"utf8"),decode:r=>r.toString("utf8")}});var ut=K((Pc,lt)=>{"use strict";lt.exports=ls();lt.exports.Constants=Ur();lt.exports.Errors=Lt();lt.exports.FileAttr=fs();lt.exports.decoder=ps()});var hs=K((jc,ms)=>{"use strict";var qe=ut(),j=qe.Constants;ms.exports=function(){var r=20,e=10,t=0,n=0,s=0,o=0,c=0,a=0,u=0,l=0,p=0,y=0,b=0,f=0,m=0;r|=qe.isWin?2560:768,t|=j.FLG_EFS;let S={extraLen:0},h=i=>Math.max(0,i)>>>0,E=i=>Math.max(0,i)&65535,d=i=>Math.max(0,i)&255;return s=qe.fromDate2DOS(new Date),{get made(){return r},set made(i){r=i},get version(){return e},set version(i){e=i},get flags(){return t},set flags(i){t=i},get flags_efs(){return(t&j.FLG_EFS)>0},set flags_efs(i){i?t|=j.FLG_EFS:t&=~j.FLG_EFS},get flags_desc(){return(t&j.FLG_DESC)>0},set flags_desc(i){i?t|=j.FLG_DESC:t&=~j.FLG_DESC},get method(){return n},set method(i){switch(i){case j.STORED:this.version=10;case j.DEFLATED:default:this.version=20}n=i},get time(){return qe.fromDOS2Date(this.timeval)},set time(i){this.timeval=qe.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=h(i)},get timeHighByte(){return d(s>>>8)},get crc(){return o},set crc(i){o=h(i)},get compressedSize(){return c},set compressedSize(i){c=h(i)},get size(){return a},set size(i){a=h(i)},get fileNameLength(){return u},set fileNameLength(i){u=i},get extraLength(){return l},set extraLength(i){l=i},get extraLocalLength(){return S.extraLen},set extraLocalLength(i){S.extraLen=i},get commentLength(){return p},set commentLength(i){p=i},get diskNumStart(){return y},set diskNumStart(i){y=h(i)},get inAttr(){return b},set inAttr(i){b=h(i)},get attr(){return f},set attr(i){f=h(i)},get fileAttr(){return(f||0)>>16&4095},get offset(){return m},set offset(i){m=h(i)},get encrypted(){return(t&j.FLG_ENC)===j.FLG_ENC},get centralHeaderSize(){return j.CENHDR+u+l+p},get realDataOffset(){return m+j.LOCHDR+S.fnameLen+S.extraLen},get localHeader(){return S},loadLocalHeaderFromBinary:function(i){var g=i.slice(m,m+j.LOCHDR);if(g.readUInt32LE(0)!==j.LOCSIG)throw qe.Errors.INVALID_LOC();S.version=g.readUInt16LE(j.LOCVER),S.flags=g.readUInt16LE(j.LOCFLG),S.method=g.readUInt16LE(j.LOCHOW),S.time=g.readUInt32LE(j.LOCTIM),S.crc=g.readUInt32LE(j.LOCCRC),S.compressedSize=g.readUInt32LE(j.LOCSIZ),S.size=g.readUInt32LE(j.LOCLEN),S.fnameLen=g.readUInt16LE(j.LOCNAM),S.extraLen=g.readUInt16LE(j.LOCEXT);let C=m+j.LOCHDR+S.fnameLen,O=C+S.extraLen;return i.slice(C,O)},loadFromBinary:function(i){if(i.length!==j.CENHDR||i.readUInt32LE(0)!==j.CENSIG)throw qe.Errors.INVALID_CEN();r=i.readUInt16LE(j.CENVEM),e=i.readUInt16LE(j.CENVER),t=i.readUInt16LE(j.CENFLG),n=i.readUInt16LE(j.CENHOW),s=i.readUInt32LE(j.CENTIM),o=i.readUInt32LE(j.CENCRC),c=i.readUInt32LE(j.CENSIZ),a=i.readUInt32LE(j.CENLEN),u=i.readUInt16LE(j.CENNAM),l=i.readUInt16LE(j.CENEXT),p=i.readUInt16LE(j.CENCOM),y=i.readUInt16LE(j.CENDSK),b=i.readUInt16LE(j.CENATT),f=i.readUInt32LE(j.CENATX),m=i.readUInt32LE(j.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(j.LOCHDR);return i.writeUInt32LE(j.LOCSIG,0),i.writeUInt16LE(e,j.LOCVER),i.writeUInt16LE(t,j.LOCFLG),i.writeUInt16LE(n,j.LOCHOW),i.writeUInt32LE(s,j.LOCTIM),i.writeUInt32LE(o,j.LOCCRC),i.writeUInt32LE(c,j.LOCSIZ),i.writeUInt32LE(a,j.LOCLEN),i.writeUInt16LE(u,j.LOCNAM),i.writeUInt16LE(S.extraLen,j.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(j.CENHDR+u+l+p);return i.writeUInt32LE(j.CENSIG,0),i.writeUInt16LE(r,j.CENVEM),i.writeUInt16LE(e,j.CENVER),i.writeUInt16LE(t,j.CENFLG),i.writeUInt16LE(n,j.CENHOW),i.writeUInt32LE(s,j.CENTIM),i.writeUInt32LE(o,j.CENCRC),i.writeUInt32LE(c,j.CENSIZ),i.writeUInt32LE(a,j.CENLEN),i.writeUInt16LE(u,j.CENNAM),i.writeUInt16LE(l,j.CENEXT),i.writeUInt16LE(p,j.CENCOM),i.writeUInt16LE(y,j.CENDSK),i.writeUInt16LE(b,j.CENATT),i.writeUInt32LE(f,j.CENATX),i.writeUInt32LE(m,j.CENOFF),i},toJSON:function(){let i=function(g){return g+" bytes"};return{made:r,version:e,flags:t,method:qe.methodToString(n),time:this.time,crc:"0x"+o.toString(16).toUpperCase(),compressedSize:i(c),size:i(a),fileNameLength:i(u),extraLength:i(l),commentLength:i(p),diskNumStart:y,inAttr:b,attr:f,offset:m,centralHeaderSize:i(j.CENHDR+u+l+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ys=K((Dc,gs)=>{"use strict";var ft=ut(),X=ft.Constants;gs.exports=function(){var r=0,e=0,t=0,n=0,s=0;return{get diskEntries(){return r},set diskEntries(o){r=e=o},get totalEntries(){return e},set totalEntries(o){e=r=o},get size(){return t},set size(o){t=o},get offset(){return n},set offset(o){n=o},get commentLength(){return s},set commentLength(o){s=o},get mainHeaderSize(){return X.ENDHDR+s},loadFromBinary:function(o){if((o.length!==X.ENDHDR||o.readUInt32LE(0)!==X.ENDSIG)&&(o.length<X.ZIP64HDR||o.readUInt32LE(0)!==X.ZIP64SIG))throw ft.Errors.INVALID_END();o.readUInt32LE(0)===X.ENDSIG?(r=o.readUInt16LE(X.ENDSUB),e=o.readUInt16LE(X.ENDTOT),t=o.readUInt32LE(X.ENDSIZ),n=o.readUInt32LE(X.ENDOFF),s=o.readUInt16LE(X.ENDCOM)):(r=ft.readBigUInt64LE(o,X.ZIP64SUB),e=ft.readBigUInt64LE(o,X.ZIP64TOT),t=ft.readBigUInt64LE(o,X.ZIP64SIZE),n=ft.readBigUInt64LE(o,X.ZIP64OFF),s=0)},toBinary:function(){var o=Buffer.alloc(X.ENDHDR+s);return o.writeUInt32LE(X.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(r,X.ENDSUB),o.writeUInt16LE(e,X.ENDTOT),o.writeUInt32LE(t,X.ENDSIZ),o.writeUInt32LE(n,X.ENDOFF),o.writeUInt16LE(s,X.ENDCOM),o.fill(" ",X.ENDHDR),o},toJSON:function(){let o=function(c,a){let u=c.toString(16).toUpperCase();for(;u.length<a;)u="0"+u;return"0x"+u};return{diskEntries:r,totalEntries:e,size:t+" bytes",offset:o(n,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Br=K(Hr=>{"use strict";Hr.EntryHeader=hs();Hr.MainHeader=ys()});var Es=K(($c,Ss)=>{"use strict";Ss.exports=function(r){var e=require("zlib"),t={chunkSize:(parseInt(r.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(r,t)},deflateAsync:function(n){var s=e.createDeflateRaw(t),o=[],c=0;s.on("data",function(a){o.push(a),c+=a.length}),s.on("end",function(){var a=Buffer.alloc(c),u=0;a.fill(0);for(var l=0;l<o.length;l++){var p=o[l];p.copy(a,u),u+=p.length}n&&n(a)}),s.end(r)}}}});var ws=K((Lc,Cs)=>{"use strict";var qi=+(process.versions?process.versions.node:"").split(".")[0]||0;Cs.exports=function(r,e){var t=require("zlib");let n=qi>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(r,n)},inflateAsync:function(s){var o=t.createInflateRaw(n),c=[],a=0;o.on("data",function(u){c.push(u),a+=u.length}),o.on("end",function(){var u=Buffer.alloc(a),l=0;u.fill(0);for(var p=0;p<c.length;p++){var y=c[p];y.copy(u,l),l+=y.length}s&&s(u)}),o.end(r)}}}});var _s=K((Fc,xs)=>{"use strict";var{randomFillSync:bs}=require("crypto"),Gi=Lt(),zi=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Is=(r,e)=>Math.imul(r,e)>>>0,As=(r,e)=>zi[(r^e)&255]^r>>>8,xt=()=>typeof bs=="function"?bs(Buffer.alloc(12)):xt.node();xt.node=()=>{let r=Buffer.alloc(12),e=r.length;for(let t=0;t<e;t++)r[t]=Math.random()*256&255;return r};var Ft={genSalt:xt};function Mt(r){let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}Mt.prototype.updateKeys=function(r){let e=this.keys;return e[0]=As(e[0],r),e[1]+=e[0]&255,e[1]=Is(e[1],134775813)+1,e[2]=As(e[2],e[1]>>>24),r};Mt.prototype.next=function(){let r=(this.keys[2]|2)>>>0;return Is(r,r^1)>>8&255};function Zi(r){let e=new Mt(r);return function(t){let n=Buffer.alloc(t.length),s=0;for(let o of t)n[s++]=e.updateKeys(o^e.next());return n}}function Ji(r){let e=new Mt(r);return function(t,n,s=0){n||(n=Buffer.alloc(t.length));for(let o of t){let c=e.next();n[s++]=o^c,e.updateKeys(o)}return n}}function Ki(r,e,t){if(!r||!Buffer.isBuffer(r)||r.length<12)return Buffer.alloc(0);let n=Zi(t),s=n(r.slice(0,12)),o=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==o)throw Gi.WRONG_PASSWORD();return n(r.slice(12))}function Xi(r){Buffer.isBuffer(r)&&r.length>=12?Ft.genSalt=function(){return r.slice(0,12)}:r==="node"?Ft.genSalt=xt.node:Ft.genSalt=xt}function Yi(r,e,t,n=!1){r==null&&(r=Buffer.alloc(0)),Buffer.isBuffer(r)||(r=Buffer.from(r.toString()));let s=Ji(t),o=Ft.genSalt();o[11]=e.crc>>>24&255,n&&(o[10]=e.crc>>>16&255);let c=Buffer.alloc(r.length+12);return s(o,c),s(r,c,12)}xs.exports={decrypt:Ki,encrypt:Yi,_salter:Xi}});var Os=K(Ut=>{"use strict";Ut.Deflater=Es();Ut.Inflater=ws();Ut.ZipCrypto=_s()});var Vr=K((Uc,vs)=>{"use strict";var V=ut(),Qi=Br(),ee=V.Constants,Wr=Os();vs.exports=function(r,e){var t=new Qi.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),o=!1,c=null,a=Buffer.alloc(0),u=Buffer.alloc(0),l=!0;let p=r,y=typeof p.decoder=="object"?p.decoder:V.decoder;l=y.hasOwnProperty("efs")?y.efs:!1;function b(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function f(i){if(t.flags_desc){let g={},C=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(C)==ee.LOCSIG||e.readUInt32LE(C)==ee.CENSIG)throw V.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(C)==ee.EXTSIG)g.crc=e.readUInt32LE(C+ee.EXTCRC),g.compressedSize=e.readUInt32LE(C+ee.EXTSIZ),g.size=e.readUInt32LE(C+ee.EXTLEN);else if(e.readUInt16LE(C+12)===19280)g.crc=e.readUInt32LE(C+ee.EXTCRC-4),g.compressedSize=e.readUInt32LE(C+ee.EXTSIZ-4),g.size=e.readUInt32LE(C+ee.EXTLEN-4);else throw V.Errors.DESCRIPTOR_UNKNOWN();if(g.compressedSize!==t.compressedSize||g.size!==t.size||g.crc!==t.crc)throw V.Errors.DESCRIPTOR_FAULTY();if(V.crc32(i)!==g.crc)return!1}else if(V.crc32(i)!==t.localHeader.crc)return!1;return!0}function m(i,g,C){if(typeof g>"u"&&typeof i=="string"&&(C=i,i=void 0),o)return i&&g&&g(Buffer.alloc(0),V.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var O=b();if(O.length===0)return i&&g&&g(O),O;if(t.encrypted){if(typeof C!="string"&&!Buffer.isBuffer(C))throw V.Errors.INVALID_PASS_PARAM();O=Wr.ZipCrypto.decrypt(O,t,C)}var x=Buffer.alloc(t.size);switch(t.method){case V.Constants.STORED:if(O.copy(x),f(x))return i&&g&&g(x),x;throw i&&g&&g(x,V.Errors.BAD_CRC()),V.Errors.BAD_CRC();case V.Constants.DEFLATED:var A=new Wr.Inflater(O,t.size);if(i)A.inflateAsync(function(v){v.copy(v,0),g&&(f(v)?g(v):g(v,V.Errors.BAD_CRC()))});else{if(A.inflate(x).copy(x,0),!f(x))throw V.Errors.BAD_CRC(`"${y.decode(n)}"`);return x}break;default:throw i&&g&&g(Buffer.alloc(0),V.Errors.UNKNOWN_METHOD()),V.Errors.UNKNOWN_METHOD()}}function S(i,g){if((!c||!c.length)&&Buffer.isBuffer(e))return i&&g&&g(b()),b();if(c.length&&!o){var C;switch(t.method){case V.Constants.STORED:return t.compressedSize=t.size,C=Buffer.alloc(c.length),c.copy(C),i&&g&&g(C),C;default:case V.Constants.DEFLATED:var O=new Wr.Deflater(c);if(i)O.deflateAsync(function(A){C=Buffer.alloc(A.length),t.compressedSize=A.length,A.copy(C),g&&g(C)});else{var x=O.deflate();return t.compressedSize=x.length,x}O=null;break}}else if(i&&g)g(Buffer.alloc(0));else return Buffer.alloc(0)}function h(i,g){return(i.readUInt32LE(g+4)<<4)+i.readUInt32LE(g)}function E(i){try{for(var g=0,C,O,x;g+4<i.length;)C=i.readUInt16LE(g),g+=2,O=i.readUInt16LE(g),g+=2,x=i.slice(g,g+O),g+=O,ee.ID_ZIP64===C&&d(x)}catch{throw V.Errors.EXTRA_FIELD_PARSE_ERROR()}}function d(i){var g,C,O,x;i.length>=ee.EF_ZIP64_SCOMP&&(g=h(i,ee.EF_ZIP64_SUNCOMP),t.size===ee.EF_ZIP64_OR_32&&(t.size=g)),i.length>=ee.EF_ZIP64_RHO&&(C=h(i,ee.EF_ZIP64_SCOMP),t.compressedSize===ee.EF_ZIP64_OR_32&&(t.compressedSize=C)),i.length>=ee.EF_ZIP64_DSN&&(O=h(i,ee.EF_ZIP64_RHO),t.offset===ee.EF_ZIP64_OR_32&&(t.offset=O)),i.length>=ee.EF_ZIP64_DSN+4&&(x=i.readUInt32LE(ee.EF_ZIP64_DSN),t.diskNumStart===ee.EF_ZIP64_OR_16&&(t.diskNumStart=x))}return{get entryName(){return y.decode(n)},get rawEntryName(){return n},set entryName(i){n=V.toBuffer(i,y.encode);var g=n[n.length-1];o=g===47||g===92,t.fileNameLength=n.length},get efs(){return typeof l=="function"?l(this.entryName):l},get extra(){return a},set extra(i){a=i,t.extraLength=i.length,E(i)},get comment(){return y.decode(s)},set comment(i){if(s=V.toBuffer(i,y.encode),t.commentLength=s.length,s.length>65535)throw V.Errors.COMMENT_TOO_LONG()},get name(){var i=y.decode(n);return o?i.substr(i.length-1).split("/").pop():i.split("/").pop()},get isDirectory(){return o},getCompressedData:function(){return S(!1,null)},getCompressedDataAsync:function(i){S(!0,i)},setData:function(i){c=V.toBuffer(i,V.decoder.encode),!o&&c.length?(t.size=c.length,t.method=V.Constants.DEFLATED,t.crc=V.crc32(i),t.changed=!0):t.method=V.Constants.STORED},getData:function(i){return t.changed?c:m(!1,null,i)},getDataAsync:function(i,g){t.changed?i(c):m(!0,i,g)},set attr(i){t.attr=i},get attr(){return t.attr},set header(i){t.loadFromBinary(i)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=a.length;var i=t.centralHeaderToBinary(),g=V.Constants.CENHDR;return n.copy(i,g),g+=n.length,a.copy(i,g),g+=t.extraLength,s.copy(i,g),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=u.length;let g=t.localHeaderToBinary(),C=Buffer.alloc(g.length+n.length+t.extraLocalLength);return g.copy(C,i),i+=g.length,n.copy(C,i),i+=n.length,u.copy(C,i),i+=u.length,C},toJSON:function(){let i=function(g){return"<"+(g&&g.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:i(e),data:i(c)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Rs=K((Hc,Ts)=>{"use strict";var ks=Vr(),ea=Br(),me=ut();Ts.exports=function(r,e){var t=[],n={},s=Buffer.alloc(0),o=new ea.MainHeader,c=!1,a=null;let u=new Set,l=e,{noSort:p,decoder:y}=l;r?m(l.readEntries):c=!0;function b(){let h=new Set;for(let E of Object.keys(n)){let d=E.split("/");if(d.pop(),!!d.length)for(let i=0;i<d.length;i++){let g=d.slice(0,i+1).join("/")+"/";h.add(g)}}for(let E of h)if(!(E in n)){let d=new ks(l);d.entryName=E,d.attr=16,d.temporary=!0,t.push(d),n[d.entryName]=d,u.add(d)}}function f(){if(c=!0,n={},o.diskEntries>(r.length-o.offset)/me.Constants.CENHDR)throw me.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(o.diskEntries);for(var h=o.offset,E=0;E<t.length;E++){var d=h,i=new ks(l,r);i.header=r.slice(d,d+=me.Constants.CENHDR),i.entryName=r.slice(d,d+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(d,d+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(d,d+i.header.commentLength)),h+=i.header.centralHeaderSize,t[E]=i,n[i.entryName]=i}u.clear(),b()}function m(h){var E=r.length-me.Constants.ENDHDR,d=Math.max(0,E-65535),i=d,g=r.length,C=-1,O=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(d=0),E;E>=i;E--)if(r[E]===80){if(r.readUInt32LE(E)===me.Constants.ENDSIG){C=E,O=E,g=E+me.Constants.ENDHDR,i=E-me.Constants.END64HDR;continue}if(r.readUInt32LE(E)===me.Constants.END64SIG){i=d;continue}if(r.readUInt32LE(E)===me.Constants.ZIP64SIG){C=E,g=E+me.readBigUInt64LE(r,E+me.Constants.ZIP64SIZE)+me.Constants.ZIP64LEAD;break}}if(C==-1)throw me.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(C,g)),o.commentLength&&(s=r.slice(O+me.Constants.ENDHDR)),h&&f()}function S(){t.length>1&&!p&&t.sort((h,E)=>h.entryName.toLowerCase().localeCompare(E.entryName.toLowerCase()))}return{get entries(){return c||f(),t.filter(h=>!u.has(h))},get comment(){return y.decode(s)},set comment(h){s=me.toBuffer(h,y.encode),o.commentLength=s.length},getEntryCount:function(){return c?t.length:o.diskEntries},forEach:function(h){this.entries.forEach(h)},getEntry:function(h){return c||f(),n[h]||null},setEntry:function(h){c||f(),t.push(h),n[h.entryName]=h,o.totalEntries=t.length},deleteFile:function(h,E=!0){c||f();let d=n[h];this.getEntryChildren(d,E).map(g=>g.entryName).forEach(this.deleteEntry)},deleteEntry:function(h){c||f();let E=n[h],d=t.indexOf(E);d>=0&&(t.splice(d,1),delete n[h],o.totalEntries=t.length)},getEntryChildren:function(h,E=!0){if(c||f(),typeof h=="object")if(h.isDirectory&&E){let d=[],i=h.entryName;for(let g of t)g.entryName.startsWith(i)&&d.push(g);return d}else return[h];return[]},getChildCount:function(h){if(h&&h.isDirectory){let E=this.getEntryChildren(h);return E.includes(h)?E.length-1:E.length}return 0},compressToBuffer:function(){c||f(),S();let h=[],E=[],d=0,i=0;o.size=0,o.offset=0;let g=0;for(let x of this.entries){let A=x.getCompressedData();x.header.offset=i;let v=x.packLocalHeader(),k=v.length+A.length;i+=k,h.push(v),h.push(A);let R=x.packCentralHeader();E.push(R),o.size+=R.length,d+=k+R.length,g++}d+=o.mainHeaderSize,o.offset=i,o.totalEntries=g,i=0;let C=Buffer.alloc(d);for(let x of h)x.copy(C,i),i+=x.length;for(let x of E)x.copy(C,i),i+=x.length;let O=o.toBinary();return s&&s.copy(O,me.Constants.ENDHDR),O.copy(C,i),r=C,c=!1,C},toAsyncBuffer:function(h,E,d,i){try{c||f(),S();let g=[],C=[],O=0,x=0,A=0;o.size=0,o.offset=0;let v=function(k){if(k.length>0){let R=k.shift(),_=R.entryName+R.extra.toString();d&&d(_),R.getCompressedDataAsync(function(P){i&&i(_),R.header.offset=x;let L=R.packLocalHeader(),$=L.length+P.length;x+=$,g.push(L),g.push(P);let M=R.packCentralHeader();C.push(M),o.size+=M.length,O+=$+M.length,A++,v(k)})}else{O+=o.mainHeaderSize,o.offset=x,o.totalEntries=A,x=0;let R=Buffer.alloc(O);g.forEach(function(P){P.copy(R,x),x+=P.length}),C.forEach(function(P){P.copy(R,x),x+=P.length});let _=o.toBinary();s&&s.copy(_,me.Constants.ENDHDR),_.copy(R,x),r=R,c=!1,h(R)}};v(Array.from(this.entries))}catch(g){E(g)}}}}});var Ds=K((Bc,js)=>{"use strict";var Y=ut(),te=require("path"),ta=Vr(),ra=Rs(),et=(...r)=>Y.findLast(r,e=>typeof e=="boolean"),Ps=(...r)=>Y.findLast(r,e=>typeof e=="string"),na=(...r)=>Y.findLast(r,e=>typeof e=="function"),sa={noSort:!1,readEntries:!1,method:Y.Constants.NONE,fs:null};js.exports=function(r,e){let t=null,n=Object.assign(Object.create(null),sa);r&&typeof r=="object"&&(r instanceof Uint8Array||(Object.assign(n,r),r=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(r)&&(t=r,n.method=Y.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new Y(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=Y.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=Y.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw Y.Errors.INVALID_FILENAME();let o=new ra(t,n),{canonical:c,sanitize:a,zipnamefix:u}=Y;function l(f){if(f&&o){var m;if(typeof f=="string"&&(m=o.getEntry(te.posix.normalize(f))),typeof f=="object"&&typeof f.entryName<"u"&&typeof f.header<"u"&&(m=o.getEntry(f.entryName)),m)return m}return null}function p(f){let{join:m,normalize:S,sep:h}=te.posix;return m(".",S(h+f.split("\\").join(h)+h))}function y(f){return f instanceof RegExp?(function(m){return function(S){return m.test(S)}})(f):typeof f!="function"?()=>!0:f}let b=(f,m)=>{let S=m.slice(-1);return S=S===s.sep?s.sep:"",te.relative(f,m)+S};return{readFile:function(f,m){var S=l(f);return S&&S.getData(m)||null},childCount:function(f){let m=l(f);if(m)return o.getChildCount(m)},readFileAsync:function(f,m){var S=l(f);S?S.getDataAsync(m):m(null,"getEntry failed for:"+f)},readAsText:function(f,m){var S=l(f);if(S){var h=S.getData();if(h&&h.length)return h.toString(m||"utf8")}return""},readAsTextAsync:function(f,m,S){var h=l(f);h?h.getDataAsync(function(E,d){if(d){m(E,d);return}E&&E.length?m(E.toString(S||"utf8")):m("")}):m("")},deleteFile:function(f,m=!0){var S=l(f);S&&o.deleteFile(S.entryName,m)},deleteEntry:function(f){var m=l(f);m&&o.deleteEntry(m.entryName)},addZipComment:function(f){o.comment=f},getZipComment:function(){return o.comment||""},addZipEntryComment:function(f,m){var S=l(f);S&&(S.comment=m)},getZipEntryComment:function(f){var m=l(f);return m&&m.comment||""},updateFile:function(f,m){var S=l(f);S&&S.setData(m)},addLocalFile:function(f,m,S,h){if(s.fs.existsSync(f)){m=m?p(m):"";let E=te.win32.basename(te.win32.normalize(f));m+=S||E;let d=s.fs.statSync(f),i=d.isFile()?s.fs.readFileSync(f):Buffer.alloc(0);d.isDirectory()&&(m+=s.sep),this.addFile(m,i,h,d)}else throw Y.Errors.FILE_NOT_FOUND(f)},addLocalFileAsync:function(f,m){f=typeof f=="object"?f:{localPath:f};let S=te.resolve(f.localPath),{comment:h}=f,{zipPath:E,zipName:d}=f,i=this;s.fs.stat(S,function(g,C){if(g)return m(g,!1);E=E?p(E):"";let O=te.win32.basename(te.win32.normalize(S));if(E+=d||O,C.isFile())s.fs.readFile(S,function(x,A){return x?m(x,!1):(i.addFile(E,A,h,C),setImmediate(m,void 0,!0))});else if(C.isDirectory())return E+=s.sep,i.addFile(E,Buffer.alloc(0),h,C),setImmediate(m,void 0,!0)})},addLocalFolder:function(f,m,S){if(S=y(S),m=m?p(m):"",f=te.normalize(f),s.fs.existsSync(f)){let h=s.findFiles(f),E=this;if(h.length)for(let d of h){let i=te.join(m,b(f,d));S(i)&&E.addLocalFile(d,te.dirname(i))}}else throw Y.Errors.FILE_NOT_FOUND(f)},addLocalFolderAsync:function(f,m,S,h){h=y(h),S=S?p(S):"",f=te.normalize(f);var E=this;s.fs.open(f,"r",function(d){if(d&&d.code==="ENOENT")m(void 0,Y.Errors.FILE_NOT_FOUND(f));else if(d)m(void 0,d);else{var i=s.findFiles(f),g=-1,C=function(){if(g+=1,g<i.length){var O=i[g],x=b(f,O).split("\\").join("/");x=x.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),h(x)?s.fs.stat(O,function(A,v){A&&m(void 0,A),v.isFile()?s.fs.readFile(O,function(k,R){k?m(void 0,k):(E.addFile(S+x,R,"",v),C())}):(E.addFile(S+x+"/",Buffer.alloc(0),"",v),C())}):process.nextTick(()=>{C()})}else m(!0,void 0)};C()}})},addLocalFolderAsync2:function(f,m){let S=this;f=typeof f=="object"?f:{localPath:f},localPath=te.resolve(p(f.localPath));let{zipPath:h,filter:E,namefix:d}=f;E instanceof RegExp?E=(function(C){return function(O){return C.test(O)}})(E):typeof E!="function"&&(E=function(){return!0}),h=h?p(h):"",d=="latin1"&&(d=C=>C.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof d!="function"&&(d=C=>C);let i=C=>te.join(h,d(b(localPath,C))),g=C=>te.win32.basename(te.win32.normalize(d(C)));s.fs.open(localPath,"r",function(C){C&&C.code==="ENOENT"?m(void 0,Y.Errors.FILE_NOT_FOUND(localPath)):C?m(void 0,C):s.findFilesAsync(localPath,function(O,x){if(O)return m(O);x=x.filter(A=>E(i(A))),x.length||m(void 0,!1),setImmediate(x.reverse().reduce(function(A,v){return function(k,R){if(k||R===!1)return setImmediate(A,k,!1);S.addLocalFileAsync({localPath:v,zipPath:te.dirname(i(v)),zipName:g(v)},A)}},m))})})},addLocalFolderPromise:function(f,m){return new Promise((S,h)=>{this.addLocalFolderAsync2(Object.assign({localPath:f},m),(E,d)=>{E&&h(E),d&&S(this)})})},addFile:function(f,m,S,h){f=u(f);let E=l(f),d=E!=null;d||(E=new ta(n),E.entryName=f),E.comment=S||"";let i=typeof h=="object"&&h instanceof s.fs.Stats;i&&(E.header.time=h.mtime);var g=E.isDirectory?16:0;let C=E.isDirectory?16384:32768;return i?C|=4095&h.mode:typeof h=="number"?C|=4095&h:C|=E.isDirectory?493:420,g=(g|C<<16)>>>0,E.attr=g,E.setData(m),d||o.setEntry(E),E},getEntries:function(f){return o.password=f,o?o.entries:[]},getEntry:function(f){return l(f)},getEntryCount:function(){return o.getEntryCount()},forEach:function(f){return o.forEach(f)},extractEntryTo:function(f,m,S,h,E,d){h=et(!1,h),E=et(!1,E),S=et(!0,S),d=Ps(E,d);var i=l(f);if(!i)throw Y.Errors.NO_ENTRY();var g=c(i.entryName),C=a(m,d&&!i.isDirectory?d:S?g:te.basename(g));if(i.isDirectory){var O=o.getEntryChildren(i);return O.forEach(function(v){if(v.isDirectory)return;var k=v.getData();if(!k)throw Y.Errors.CANT_EXTRACT_FILE();var R=c(v.entryName),_=a(m,S?R:te.basename(R));let P=E?v.header.fileAttr:void 0;s.writeFileTo(_,k,h,P)}),!0}var x=i.getData(o.password);if(!x)throw Y.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(C)&&!h)throw Y.Errors.CANT_OVERRIDE();let A=E?f.header.fileAttr:void 0;return s.writeFileTo(C,x,h,A),!0},test:function(f){if(!o)return!1;for(var m in o.entries)try{if(m.isDirectory)continue;var S=o.entries[m].getData(f);if(!S)return!1}catch{return!1}return!0},extractAllTo:function(f,m,S,h){if(S=et(!1,S),h=Ps(S,h),m=et(!1,m),!o)throw Y.Errors.NO_ZIP();o.entries.forEach(function(E){var d=a(f,c(E.entryName));if(E.isDirectory){s.makeDir(d);return}var i=E.getData(h);if(!i)throw Y.Errors.CANT_EXTRACT_FILE();let g=S?E.header.fileAttr:void 0;s.writeFileTo(d,i,m,g);try{s.fs.utimesSync(d,E.header.time,E.header.time)}catch{throw Y.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(f,m,S,h){if(h=na(m,S,h),S=et(!1,S),m=et(!1,m),!h)return new Promise((C,O)=>{this.extractAllToAsync(f,m,S,function(x){x?O(x):C(this)})});if(!o){h(Y.Errors.NO_ZIP());return}f=te.resolve(f);let E=C=>a(f,te.normalize(c(C.entryName))),d=(C,O)=>new Error(C+': "'+O+'"'),i=[],g=[];o.entries.forEach(C=>{C.isDirectory?i.push(C):g.push(C)});for(let C of i){let O=E(C),x=S?C.header.fileAttr:void 0;try{s.makeDir(O),x&&s.fs.chmodSync(O,x),s.fs.utimesSync(O,C.header.time,C.header.time)}catch{h(d("Unable to create folder",O))}}g.reverse().reduce(function(C,O){return function(x){if(x)C(x);else{let A=te.normalize(c(O.entryName)),v=a(f,A);O.getDataAsync(function(k,R){if(R)C(R);else if(!k)C(Y.Errors.CANT_EXTRACT_FILE());else{let _=S?O.header.fileAttr:void 0;s.writeFileToAsync(v,k,m,_,function(P){P||C(d("Unable to write file",v)),s.fs.utimes(v,O.header.time,O.header.time,function(L){L?C(d("Unable to set times",v)):C()})})}})}}},h)()},writeZip:function(f,m){if(arguments.length===1&&typeof f=="function"&&(m=f,f=""),!f&&n.filename&&(f=n.filename),!!f){var S=o.compressToBuffer();if(S){var h=s.writeFileTo(f,S,!0);typeof m=="function"&&m(h?null:new Error("failed"),"")}}},writeZipPromise:function(f,m){let{overwrite:S,perm:h}=Object.assign({overwrite:!0},m);return new Promise((E,d)=>{!f&&n.filename&&(f=n.filename),f||d("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let g=C=>C?E(C):d("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(f,i,S,h,g)},d)})},toBufferPromise:function(){return new Promise((f,m)=>{o.toAsyncBuffer(f,m)})},toBuffer:function(f,m,S,h){return typeof f=="function"?(o.toAsyncBuffer(f,m,S,h),null):o.compressToBuffer()}}}});var Ys={};St(Ys,{enableTelemetryHook:()=>Xs,registerConfig:()=>rn});function tn(){let r=process.env.SC_PROFILE;return r?(0,Me.join)((0,ht.homedir)(),".config","shared-context","profiles",r):(0,Me.join)((0,ht.homedir)(),".config","shared-context")}function Xs(){try{let r=(0,Me.join)((0,ht.homedir)(),".claude","settings.json"),{readFileSync:e,writeFileSync:t}=require("fs"),n={};try{(0,Ge.existsSync)(r)&&(n=JSON.parse(e(r,"utf8")))}catch{}n.hooks||(n.hooks={});let s=n.hooks;if(s.PostToolUse||(s.PostToolUse=[]),s.PostToolUse.some(p=>p._sc===Ks))return;let c=(0,Me.join)(tn(),"manifest.json"),a="";try{let y=(JSON.parse(e(c,"utf8")).installations||[]).find(b=>b.slug==="telemetry"||b.installPath?.includes("hooks/telemetry"));y?.installPath&&(a=(0,Me.join)((0,ht.homedir)(),".config","shared-context",y.installPath,"scripts","telemetry.js"))}catch{}if((!a||!(0,Ge.existsSync)(a))&&(a=(0,Me.join)(tn(),"hooks","telemetry","scripts","telemetry.js")),!(0,Ge.existsSync)(a))return;s.PostToolUse.push({hooks:[{type:"command",command:`node ${a}`}],_sc:Ks}),s.SessionStart||(s.SessionStart=[]);let u="platform/telemetry-push";s.SessionStart.some(p=>p._sc===u)||s.SessionStart.push({hooks:[{type:"command",command:"npx shared-context-ai telemetry push --quiet 2>/dev/null || true"}],_sc:u}),t(r,JSON.stringify(n,null,2)+`
30
+ `,"utf8")}catch{}}function Oa(){jt({telemetry:!1});let r=(0,Me.join)(tn(),"usage.jsonl");try{(0,Ge.existsSync)(r)&&(0,Ge.unlinkSync)(r)}catch{}try{let e=(0,Me.join)((0,ht.homedir)(),".claude","settings.json");if((0,Ge.existsSync)(e)){let{readFileSync:t,writeFileSync:n}=require("fs"),s=JSON.parse(t(e,"utf8"));if(s.hooks){let o=!1,c=new Set(["hooks/shared-context/telemetry","platform/telemetry-push"]);for(let[a,u]of Object.entries(s.hooks))if(Array.isArray(u)){let l=u.filter(p=>!c.has(p._sc));l.length!==u.length&&(s.hooks[a]=l,o=!0)}for(let[a,u]of Object.entries(s.hooks))Array.isArray(u)&&u.length===0&&delete s.hooks[a];o&&n(e,JSON.stringify(s,null,2)+`
31
+ `,"utf8")}}}catch{}}function rn(r){let e=r.command("config").description("Manage CLI configuration");e.command("set <key> <value>").description("Set a configuration value (e.g., telemetry on/off)").action((t,n)=>{if(t==="telemetry"){let s=n==="on"||n==="true"||n==="1",o=n==="off"||n==="false"||n==="0";if(!s&&!o){I()?D("config","INVALID_VALUE","Telemetry value must be on or off"):T("Usage: shared-context-ai config set telemetry on|off");return}o?(Oa(),I()?N("config",{key:"telemetry",value:!1}):w("Telemetry disabled. Usage data and hooks removed.")):(jt({telemetry:!0}),Xs(),I()?N("config",{key:"telemetry",value:!0}):w("Telemetry enabled. Usage data will be collected and uploaded."));return}I()?D("config","UNKNOWN_KEY",`Unknown config key: ${t}`):T(`Unknown config key: ${t}. Available: telemetry`)}),e.command("get [key]").description("Show configuration values").action(t=>{let n=Oe();if(t==="telemetry"){let s=n.telemetry??!1;I()?N("config",{key:"telemetry",value:s}):w(`telemetry: ${s?"on":"off"}`);return}if(t){I()?D("config","UNKNOWN_KEY",`Unknown config key: ${t}`):T(`Unknown config key: ${t}`);return}I()?N("config",{telemetry:n.telemetry??!1}):w(`telemetry: ${n.telemetry?"on":"off"}`)})}var Ge,Me,ht,Ks,nn=he(()=>{"use strict";Ge=require("fs"),Me=require("path"),ht=require("os");ue();se();Ks="hooks/shared-context/telemetry"});function Pa(){try{return on.default.statSync("/.dockerenv"),!0}catch{return!1}}function ja(){try{return on.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function an(){return sn===void 0&&(sn=Pa()||ja()),sn}var on,sn,no=he(()=>{"use strict";on=ge(require("fs"),1)});function it(){return cn===void 0&&(cn=Da()||an()),cn}var so,cn,Da,ln=he(()=>{"use strict";so=ge(require("fs"),1);no();Da=()=>{try{return so.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var un,io,nr,oo,Je,fn=he(()=>{"use strict";un=ge(require("process"),1),io=ge(require("os"),1),nr=ge(require("fs"),1);ln();oo=()=>{if(un.default.platform!=="linux")return!1;if(io.default.release().toLowerCase().includes("microsoft"))return!it();try{if(nr.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!it()}catch{}return nr.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||nr.default.existsSync("/run/WSL")?!it():!1},Je=un.default.env.__IS_WSL_TEST__?oo:oo()});var dn,vt,Na,$a,pn,ao=he(()=>{"use strict";dn=ge(require("process"),1),vt=ge(require("fs/promises"),1);fn();fn();Na=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await vt.default.access(t,vt.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await vt.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),$a=async()=>`${await Na()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,pn=async()=>Je?$a():`${dn.default.env.SYSTEMROOT||dn.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Ke(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var co=he(()=>{"use strict"});async function mn(){if(uo.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await La("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var lo,uo,fo,La,po=he(()=>{"use strict";lo=require("util"),uo=ge(require("process"),1),fo=require("child_process"),La=(0,lo.promisify)(fo.execFile)});async function go(r,{humanReadableOutput:e=!0,signal:t}={}){if(mo.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await Fa("osascript",["-e",r,n],s);return o.trim()}var mo,ho,hn,Fa,yo=he(()=>{"use strict";mo=ge(require("process"),1),ho=require("util"),hn=require("child_process"),Fa=(0,ho.promisify)(hn.execFile)});async function gn(r){return go(`tell application "Finder" to set app_path to application file id "${r}" as string
32
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var So=he(()=>{"use strict";yo()});async function Sn(r=Ma){let{stdout:e}=await r("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new yn(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),o=n.lastIndexOf("-"),c=s===-1?void 0:n.slice(0,s),a=o===-1?void 0:n.slice(0,o);return sr[n]??sr[c]??sr[a]??{name:n,id:n}}var Eo,Co,Ma,sr,cu,yn,wo=he(()=>{"use strict";Eo=require("util"),Co=require("child_process"),Ma=(0,Eo.promisify)(Co.execFile),sr={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"}},cu=new Map(Object.entries(sr)),yn=class extends Error{}});async function En(){if(or.default.platform==="darwin"){let r=await mn();return{name:await gn(r),id:r}}if(or.default.platform==="linux"){let{stdout:r}=await Ua("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Ha(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(or.default.platform==="win32")return Sn();throw new Error("Only macOS, Linux, and Windows are supported")}var bo,or,Ao,Ua,Ha,Io=he(()=>{"use strict";bo=require("util"),or=ge(require("process"),1),Ao=require("child_process");po();So();wo();Ua=(0,bo.promisify)(Ao.execFile),Ha=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Ro={};St(Ro,{apps:()=>Xe,default:()=>Ga,openApp:()=>qa});async function Wa(){let r=await pn(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=bn.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await Ba(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function vo(r){if(typeof r=="string"||Array.isArray(r))return r;let{[_o]:e}=r;if(!e)throw new Error(`${_o} is not supported`);return e}function ar({[gt]:r},{wsl:e}){if(e&&Je)return vo(e);if(!r)throw new Error(`${gt} is not supported`);return vo(r)}var wn,bn,An,ko,To,In,ir,za,Ba,Cn,xo,gt,_o,Oo,kt,Va,qa,Xe,Ga,Po=he(()=>{"use strict";wn=ge(require("process"),1),bn=require("buffer"),An=ge(require("path"),1),ko=require("url"),To=require("util"),In=ge(require("child_process"),1),ir=ge(require("fs/promises"),1);ao();co();Io();ln();za={},Ba=(0,To.promisify)(In.default.execFile),Cn=An.default.dirname((0,ko.fileURLToPath)(za.url)),xo=An.default.join(Cn,"xdg-open"),{platform:gt,arch:_o}=wn.default;Oo=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},kt=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return Oo(r.app,a=>kt({...r,app:a}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return Oo(e,a=>kt({...r,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"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=Je?await Wa():await En();if(l.id in a){let p=a[l.id];return e==="browserPrivate"&&t.push(u[p]),kt({...r,app:{name:Xe[p],arguments:t}})}throw new Error(`${l.name} is not supported as a default browser`)}let n,s=[],o={};if(gt==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(gt==="win32"||Je&&!it()&&!e){n=await pn(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Je||(o.windowsVerbatimArguments=!0);let a=["Start"];r.wait&&a.push("-Wait"),e?(a.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&a.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),a.push("-ArgumentList",t.join(","))),r.target=bn.Buffer.from(a.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let a=!Cn||Cn==="/",u=!1;try{await ir.default.access(xo,ir.constants.X_OK),u=!0}catch{}n=wn.default.versions.electron??(gt==="android"||a||!u)?"xdg-open":xo}t.length>0&&s.push(...t),r.wait||(o.stdio="ignore",o.detached=!0)}gt==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let c=In.default.spawn(n,s,o);return r.wait?new Promise((a,u)=>{c.once("error",u),c.once("close",l=>{if(!r.allowNonzeroExitCode&&l>0){u(new Error(`Exited with code ${l}`));return}a(c)})}):(c.unref(),c)},Va=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return kt({...e,target:r})},qa=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return kt({...e,app:{name:r,arguments:t}})};Xe={};Ke(Xe,"chrome",()=>ar({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Ke(Xe,"brave",()=>ar({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Ke(Xe,"firefox",()=>ar({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Ke(Xe,"edge",()=>ar({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Ke(Xe,"browser",()=>"browser");Ke(Xe,"browserPrivate",()=>"browserPrivate");Ga=Va});var ti={};St(ti,{pushTelemetry:()=>ei,registerTelemetry:()=>_n});function Ya(){let r=process.env.SC_PROFILE;return r?(0,ur.join)((0,xn.homedir)(),".config","shared-context","profiles",r):(0,ur.join)((0,xn.homedir)(),".config","shared-context")}function Qo(){return(0,ur.join)(Ya(),"usage.jsonl")}function Qa(){let r=Qo();if(!(0,Ye.existsSync)(r))return[];try{let e=(0,Ye.readFileSync)(r,"utf8").trim().split(`
33
+ `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function ec(r){let e=Qo();if((0,Ye.existsSync)(e))try{let t=(0,Ye.readFileSync)(e,"utf8").trim().split(`
34
+ `).filter(Boolean);if(t.length<=r)return;let n=t.slice(-r);(0,Ye.writeFileSync)(e,n.join(`
35
35
  `)+`
36
- `,"utf8")}catch{}}async function Zo(r=!1){if(!Ie().telemetry)return{uploaded:0};if(!L())return{uploaded:0};let e=Va();if(e.length===0)return{uploaded:0};let t=e.slice(0,Ha),n=await $("/api/cli/telemetry",{events:t},1e4);if(n.ok){if(qa(Ba),!r){let s=n.data?.accepted??0;x()?N("telemetry",{uploaded:s}):s>0&&w(`Uploaded ${s} usage event${s===1?"":"s"}`)}return{uploaded:n.data?.accepted??0}}return!r&&!x()&&T("Telemetry upload failed \u2014 will retry next session"),{uploaded:0}}function En(r){r.command("telemetry").description("Manage usage telemetry").command("push").description("Upload local usage data to Shared Context").option("--quiet","Suppress output").action(async t=>{await Zo(t.quiet)})}var Ze,ir,Sn,Ha,Ba,Cn=pe(()=>{"use strict";Ze=require("fs"),ir=require("path"),Sn=require("os");ne();ce();re();Ha=1e3,Ba=100});var Ln=me($n(),1),{program:sc,createCommand:oc,createArgument:ic,createOption:ac,CommanderError:cc,InvalidArgumentError:lc,InvalidOptionArgumentError:uc,Command:Fn,Argument:fc,Option:dc,Help:pc}=Ln.default;re();var rt=require("fs"),Ve=require("path"),Zs=require("os");ce();ne();re();var $r=require("fs"),Ce=require("path"),Le=require("os"),it=[{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 ve(r){if(r){let n=it.find(o=>o.id===r);if(n)return n;let s=it.find(o=>o.dir===`.${r}`||o.dir===r);return s||null}for(let n of it)if(n.envVars.some(s=>process.env[s]))return n;let e=(0,Le.homedir)(),t=[];for(let n of it)(0,$r.existsSync)((0,Ce.join)(e,n.dir))&&t.push(n);return t.length===1?t[0]:null}function Fe(){let r=[],e=(0,Le.homedir)();for(let t of it)(t.envVars.some(n=>process.env[n])||(0,$r.existsSync)((0,Ce.join)(e,t.dir)))&&r.push(t);return r}function Me(){let r=Fe();return r.length>1?`Multiple AI agents detected (${r.map(e=>e.label).join(", ")}). Use --agent to specify: ${r.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${it.map(e=>e.id).join(", ")})`}function H(r,e){return e?(0,Ce.join)(process.cwd(),r.dir,r.skillsSubdir):(0,Ce.join)((0,Le.homedir)(),r.dir,r.skillsSubdir)}function te(r,e){return e?(0,Ce.join)(process.cwd(),r.dir,"agents"):(0,Ce.join)((0,Le.homedir)(),r.dir,"agents")}function fe(r,e){return e?(0,Ce.join)(process.cwd(),".mcp.json"):r.id==="claude-code"?(0,Ce.join)((0,Le.homedir)(),".claude.json"):r.id==="cursor"?(0,Ce.join)((0,Le.homedir)(),".cursor","mcp.json"):(0,Ce.join)(process.cwd(),".mcp.json")}function we(r,e){return e?(0,Ce.join)(process.cwd(),r.dir,"settings.json"):(0,Ce.join)((0,Le.homedir)(),r.dir,"settings.json")}var le=require("fs"),Qe=require("path");var Oe=require("fs"),xe=require("path"),$s=require("child_process");ne();var ks=require("child_process"),vs=require("fs"),Ts=require("path"),Rs=require("os"),Ps=me(Os());ne();function ut(r){let t={"claude-code":"claude",cursor:"cursor","gemini-cli":"gemini"}[r];if(!t)return null;try{return(0,ks.execSync)(`which ${t}`,{stdio:"pipe"}),t}catch{return null}}async function Lt(r,e){let t=await Nr(r),n=(0,Ts.join)((0,Rs.tmpdir)(),`sc-plugin-${e}-${Date.now()}`);return(0,vs.mkdirSync)(n,{recursive:!0}),new Ps.default(t).extractAllTo(n,!0),n}function Ft(r){return{"claude-code":"claude","gemini-cli":"gemini",cursor:"cursor"}[r]||"claude"}ce();re();var He=require("fs"),Mt=require("path"),js=".shared-context",Ds="project.json";function Se(){let r=(0,Mt.join)(process.cwd(),js,Ds);if(!(0,He.existsSync)(r))return null;try{let e=JSON.parse((0,He.readFileSync)(r,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function Ye(r){let e=(0,Mt.join)(process.cwd(),js);(0,He.mkdirSync)(e,{recursive:!0}),(0,He.writeFileSync)((0,Mt.join)(e,Ds),JSON.stringify(r,null,2)+`
37
- `,"utf-8")}var Ls={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function q(r,e){let t=(0,xe.resolve)(r);for(let n of e){let s=(0,xe.resolve)((0,xe.join)(r,n.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${n.path}`);(0,Oe.mkdirSync)((0,xe.dirname)(s),{recursive:!0}),(0,Oe.writeFileSync)(s,n.content,"utf-8")}}function Br(r){let e=r.resource.slug||r.resource.id;return`${Ls[r.resource.resourceType]||r.resource.resourceType+"s"}/${e}`}function Ns(r,e,t,n){let s=(0,xe.join)(r,e);if(!(0,Oe.existsSync)(s))return{slug:e,renamed:!1};if(!V().installations.find(u=>{let a=u.installPath.split("/");return a[a.length-1]===e&&u.resourceId!==t}))return{slug:e,renamed:!1};let c=n.resource.orgSlug||n.resource.githubOwner||n.resource.id.slice(0,8);return{slug:`${e}-${c}`,renamed:!0}}function Ut(r,e,t){let n=t.files.find(a=>a.path.endsWith(".json")&&!a.path.includes("/"))||t.files.find(a=>a.path.endsWith(".json")&&a.path.includes("resources/"));if(!n)throw new Error("MCP package does not contain a config file");let s=JSON.parse(n.content),o=fe(r,e),l=t.resource.slug||t.resource.id,c={};if((0,Oe.existsSync)(o))try{c=JSON.parse((0,Oe.readFileSync)(o,"utf-8"))}catch{c={}}let u=typeof c.mcpServers=="object"&&c.mcpServers&&!Array.isArray(c.mcpServers)?c.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(u,s.mcpServers):u[l]=s,c.mcpServers=u,(0,Oe.mkdirSync)((0,xe.dirname)(o),{recursive:!0}),(0,Oe.writeFileSync)(o,JSON.stringify(c,null,2)+`
38
- `,"utf-8")}function Xi(r,e,t,n){let s=t.files.find(a=>a.path.endsWith(".json")&&!a.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),l=we(r,e),c={},u=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:o;for(let[a,p]of Object.entries(u))if(!(a==="name"||a==="description")&&Array.isArray(p)){c[a]||(c[a]=[]);for(let g of p)c[a].push(g)}if(Object.keys(c).length===0)throw new Error("Hook package does not contain any hook event handlers");return Wr(l,c,n),l}function Fs(r){r.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=ve(s.agent);if(!o){let i=Me();x()?D("install","NO_AGENTS",i):T(i),process.exit(1)}let l=L(),u=await G(`${l?"/api/cli/resource":"/api/public/resource"}/${e}`);u.ok||(x()?D("install",u.error.code,u.error.message):T(`Install failed: ${u.error.message}`),process.exit(1));let a=u.data,p=a.resource.slug||a.resource.id,g=Br(a),_,f="decomposed",h;if(a.resource.resourceType==="agent"){let i=te(o,!!s.project),d=Ns(i,p,a.resource.id,a);d.renamed&&(p=d.slug,g=Br({...a,resource:{...a.resource,slug:p}}),x()||w(`Note: Renamed to "${p}" (collision with existing resource)`)),_=(0,xe.join)(i,p);try{q(_,a.files)}catch(S){x()?D("install","WRITE_FAILED",`Failed to write files: ${S}`):T(`Failed to write files: ${S}`),process.exit(1)}}else if(a.resource.resourceType==="mcp"){_="";try{Ut(o,!!s.project,a)}catch(i){x()?D("install","WRITE_FAILED",`Failed to install MCP config: ${i}`):T(`Failed to install MCP config: ${i}`),process.exit(1)}}else if(a.resource.resourceType==="hook"){_="";try{Xi(o,!!s.project,a,g)}catch(i){x()?D("install","WRITE_FAILED",`Failed to install hook config: ${i}`):T(`Failed to install hook config: ${i}`),process.exit(1)}}else{let i=H(o,!!s.project);if(a.resource.resourceType!=="collection"){let d=Ns(i,p,a.resource.id,a);d.renamed&&(p=d.slug,g=Br({...a,resource:{...a.resource,slug:p}}),x()||w(`Note: Renamed to "${p}" (collision with existing resource)`))}_=(0,xe.join)(i,p);try{if(a.resource.resourceType==="collection"){let d=ut(o.id);if(d)try{let S=a.resource.slug||a.resource.id,b=a.resource.orgSlug||"",A=Ft(o.id),I=l?`/api/cli/resource/collections/${b}/${S}?format=plugin&platform=${A}`:`/api/public/resource/collections/${b}/${S}?format=plugin&platform=${A}`,O=await Lt(I,S);(0,$s.execSync)(`${d} plugin install "${O}"`,{stdio:"pipe"}),_=O,f="plugin",h=O,x()||w(`Installed as native ${d} plugin`)}catch(S){x()||T(`Native plugin install failed, falling back to decomposed: ${S}`);let A=await Te(o).install(a,s.project?"project":"user",o);_=A.installDir;for(let I of A.warnings)x()||T(`Warning: ${I}`)}else{let b=await Te(o).install(a,s.project?"project":"user",o);if(_=b.installDir,!x())for(let A of b.warnings)T(`Warning: ${A}`)}}else q(_,a.files)}catch(d){x()?D("install","WRITE_FAILED",`Failed to write files: ${d}`):T(`Failed to write files: ${d}`),process.exit(1)}}let E;if(l&&a.resource.latestSha){let i=await $("/api/cli/install",{resourceId:a.resource.id,agentPlatform:o.platform,installedSha:a.resource.latestSha});i.ok||(E=`Could not record install on server: ${i.error.message}`,x()||T(`Warning: ${E}`))}let y=s.project?Se():null;y&&l&&await $(`/api/cli/projects/${y.projectId}/resources`,{resourceId:a.resource.id}).catch(()=>{});let C={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},m=a.resource.resourceType==="collection";if(ae({resourceId:a.resource.id,slug:p,installPath:g,title:a.resource.title,sha:a.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),latestSha:a.resource.latestSha||void 0,resourceType:a.resource.resourceType,serverSynced:!0,...m?{pluginFormat:C[o.id]||"directory",memberCount:a.memberResources?.length,installMode:f,pluginDir:h}:{},...y?{projectId:y.projectId}:{}}),a.memberResources&&a.resource.resourceType==="collection"){if(f==="decomposed")for(let i of a.memberResources){let d=i.slug||i.id,S=Ls[i.resourceType]||i.resourceType+"s",b=a.resource.orgSlug?`${a.resource.orgSlug}/`:"",A=`${S}/${b}${d}`;ae({resourceId:i.id,slug:d,installPath:A,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:a.resource.id,resourceType:i.resourceType,serverSynced:!0})}for(let i of a.memberResources)l&&i.latestSha&&await $("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{})}if($e(),x())N("install",{installPath:g,title:a.resource.title,path:_||void 0,files:a.files.length,...a.resource.resourceType==="mcp"?{mcpConfigPath:fe(o,!!s.project)}:{},...a.resource.resourceType==="hook"?{settingsPath:we(o,!!s.project)}:{},...a.memberResources?{memberResources:a.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...E&&{warning:E}});else{if(a.resource.resourceType==="mcp"?w(`Installed MCP "${a.resource.title}" to ${fe(o,!!s.project)}`):a.resource.resourceType==="hook"?w(`Installed hook "${a.resource.title}" to ${we(o,!!s.project)}`):a.memberResources&&a.memberResources.length>0?w(`Installed "${a.resource.title}" (${a.memberResources.length} resources)`):w(`Installed "${a.resource.title}" to ${_}`),a.resource.resourceType!=="mcp"&&a.resource.resourceType!=="hook"&&!(a.memberResources&&a.memberResources.length>0)&&w(` ${a.files.length} file${a.files.length===1?"":"s"} written`),a.memberResources&&a.memberResources.length>0){let i={};for(let S of a.memberResources){let b=S.resourceType||"other";i[b]||(i[b]=[]),i[b].push(S.title)}let d={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};w("");for(let[S,b]of Object.entries(i)){let A=d[S]||S;w(` ${A}: ${b.join(", ")}`)}}l||(w(""),w("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var Ht=class{buildFiles(e){let t=[],n=[],s=[],o={},l={};for(let c of e.files){let u=c.path.split("/"),a=u[0];if(a==="agents")s.push({path:c.path.slice(7),content:c.content});else if(a==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let g=u.indexOf("resources"),_=g>0?u[g-1]:u[1];o[_]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(a==="hooks"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content),g=c.path.replace(/\/[^/]+$/,"");Yi(p,l,g)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else a==="skills"||a==="commands"||a==="files"?n.push({path:c.path.slice(a.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:l,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=e.resource.slug||e.resource.id,c=H(n,o),u=ta(e),a=(0,Qe.join)(c,...u),p=0;if(s.mainFiles.length>0){let g=s.mainFiles.filter(f=>!f.path.includes("/")),_=s.mainFiles.filter(f=>f.path.includes("/"));if(g.length>0){let f=g.find(h=>h.path==="README.md");f&&g.push({path:"SKILL.md",content:ea(e,f.content)}),q(a,g),p+=g.length}_.length>0&&(q(c,_),p+=_.length)}if(s.agentFiles.length>0){let g=te(n,o);q(g,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Qi(fe(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Wr(we(n,o),s.hookEntries),{installDir:a,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n,s){let o=[],c=H(n,t==="project"),u=(0,Qe.join)(c,e),a=!1;return(0,le.existsSync)(u)&&((0,le.rmSync)(u,{recursive:!0,force:!0}),a=!0),a||o.push(`Collection directory not found at ${u}`),{removed:a,warnings:o}}describeLocation(e,t,n){let s=H(n,t==="project");return(0,Qe.join)(s,e)}};function Yi(r,e,t){if(!r||typeof r!="object")return;let n=r,s=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:n;for(let[o,l]of Object.entries(s))if(!(o==="name"||o==="description")&&Array.isArray(l)){e[o]||(e[o]=[]);for(let c of l){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c;e[o].push(u)}}}function Wr(r,e,t){let n={};if((0,le.existsSync)(r))try{n=JSON.parse((0,le.readFileSync)(r,"utf-8"))}catch{n={}}let s=typeof n.hooks=="object"&&n.hooks&&!Array.isArray(n.hooks)?n.hooks:{};if(t)for(let[o,l]of Object.entries(s))Array.isArray(l)&&(s[o]=l.filter(c=>!c||typeof c!="object"||c._sc!==t),s[o].length===0&&delete s[o]);for(let[o,l]of Object.entries(e)){Array.isArray(s[o])||(s[o]=[]);for(let c of l){let u=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c,a=JSON.stringify(u);s[o].some(g=>JSON.stringify(g)===a)||s[o].push(u)}}n.hooks=s,(0,le.mkdirSync)((0,Qe.dirname)(r),{recursive:!0}),(0,le.writeFileSync)(r,JSON.stringify(n,null,2)+`
39
- `,"utf-8")}function Vr(r,e){if(!(0,le.existsSync)(r))return!1;let t;try{t=JSON.parse((0,le.readFileSync)(r,"utf-8"))}catch{return!1}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!n)return!1;let s=!1;for(let[o,l]of Object.entries(n)){if(!Array.isArray(l))continue;let c=l.filter(u=>!u||typeof u!="object"||u._sc!==e);c.length!==l.length&&(s=!0,c.length===0?delete n[o]:n[o]=c)}return s&&(t.hooks=n,(0,le.writeFileSync)(r,JSON.stringify(t,null,2)+`
40
- `,"utf-8")),s}function Qi(r,e){let t={};if((0,le.existsSync)(r))try{t=JSON.parse((0,le.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,le.mkdirSync)((0,Qe.dirname)(r),{recursive:!0}),(0,le.writeFileSync)(r,JSON.stringify(t,null,2)+`
41
- `,"utf-8")}function ea(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
42
- `)}function ta(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var ge=require("fs"),et=require("path");var ra={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},Bt=class{buildFiles(e){let t=[],n=[],s=[],o={},l={};for(let c of e.files){let u=c.path.split("/"),a=u[0];if(a==="agents")s.push({path:c.path.slice(7),content:c.content});else if(a==="mcps"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(c.path.includes("resources/")){let g=u.indexOf("resources"),_=g>0?u[g-1]:u[1];o[_]=p}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(a==="hooks"){if(c.path.endsWith(".json"))try{let p=JSON.parse(c.content);na(p,l)}catch{t.push(`Failed to parse hook config: ${c.path}`)}}else a==="skills"||a==="commands"||a==="files"?n.push({path:c.path.slice(a.length+1),content:c.content}):n.push(c)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:l,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=e.resource.slug||e.resource.id,c=H(n,o),u=aa(e),a=(0,et.join)(c,...u),p=0;if(s.mainFiles.length>0){let g=s.mainFiles.filter(f=>!f.path.includes("/")),_=s.mainFiles.filter(f=>f.path.includes("/"));if(g.length>0){let f=g.find(h=>h.path==="README.md");f&&g.push({path:"SKILL.md",content:ia(e,f.content)}),q(a,g),p+=g.length}_.length>0&&(q(c,_),p+=_.length)}if(s.agentFiles.length>0){let g=te(n,o);q(g,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&oa(fe(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&sa(we(n,o),s.hookEntries),{installDir:a,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=H(n,t==="project"),c=(0,et.join)(l,e),u=!1;return(0,ge.existsSync)(c)&&((0,ge.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=H(n,t==="project");return(0,et.join)(s,e)}};function na(r,e){if(!r||typeof r!="object")return;let t=r,n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(n)){if(s==="name"||s==="description"||!Array.isArray(o))continue;let l=ra[s]||s;e[l]||(e[l]=[]);for(let c of o)e[l].push(c)}}function sa(r,e){let t={};if((0,ge.existsSync)(r))try{t=JSON.parse((0,ge.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,o]of Object.entries(e)){Array.isArray(n[s])||(n[s]=[]);for(let l of o){let c=JSON.stringify(l);n[s].some(a=>JSON.stringify(a)===c)||n[s].push(l)}}t.hooks=n,(0,ge.mkdirSync)((0,et.dirname)(r),{recursive:!0}),(0,ge.writeFileSync)(r,JSON.stringify(t,null,2)+`
43
- `,"utf-8")}function oa(r,e){let t={};if((0,ge.existsSync)(r))try{t=JSON.parse((0,ge.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,ge.mkdirSync)((0,et.dirname)(r),{recursive:!0}),(0,ge.writeFileSync)(r,JSON.stringify(t,null,2)+`
44
- `,"utf-8")}function ia(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
45
- `)}function aa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var ue=require("fs"),Pe=require("path");var Wt=class{buildFiles(e){let t=[],n=[],s=[],o={},l=[],c=e.resource.slug||e.resource.id;for(let u of e.files){let a=u.path.split("/"),p=a[0];if(p==="agents")s.push({path:u.path.slice(7),content:u.content});else if(p==="mcps"){if(u.path.endsWith(".json"))try{let g=JSON.parse(u.content);if(g.mcpServers&&typeof g.mcpServers=="object")Object.assign(o,g.mcpServers);else if(u.path.includes("resources/")){let _=a.indexOf("resources"),f=_>0?a[_-1]:a[1];o[f]=g}}catch{t.push(`Failed to parse MCP config: ${u.path}`)}}else p==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${u.path})`):p==="skills"||p==="commands"||p==="files"?n.push({path:u.path.slice(p.length+1),content:u.content}):n.push(u)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:l,warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=H(n,o),c=ua(e),u=(0,Pe.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(_=>!_.path.includes("/")),g=s.mainFiles.filter(_=>_.path.includes("/"));if(p.length>0){let _=p.find(f=>f.path==="README.md");_&&p.push({path:"SKILL.md",content:la(e,_.content)}),q(u,p),a+=p.length}g.length>0&&(q(l,g),a+=g.length)}if(s.agentFiles.length>0){let p=te(n,o);q(p,s.agentFiles),a+=s.agentFiles.length}for(let p of s.customFiles)(0,ue.mkdirSync)((0,Pe.dirname)(p.absolutePath),{recursive:!0}),(0,ue.writeFileSync)(p.absolutePath,p.content,"utf-8"),a++;return Object.keys(s.mcpEntries).length>0&&ca(fe(n,o),s.mcpEntries),{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=H(n,t==="project"),c=(0,Pe.join)(l,e),u=!1;(0,ue.existsSync)(c)&&((0,ue.rmSync)(c,{recursive:!0,force:!0}),u=!0);let a=(0,Pe.join)(homedir(),".cursor","rules");if((0,ue.existsSync)(a))try{let p=(0,ue.readdirSync)(a);for(let g of p)g.startsWith(`${e}-`)&&g.endsWith(".mdc")&&((0,ue.unlinkSync)((0,Pe.join)(a,g)),u=!0)}catch{s.push("Could not clean up Cursor rules")}return u||s.push(`Collection not found for Cursor at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=H(n,t==="project");return(0,Pe.join)(s,e)}};function ca(r,e){let t={};if((0,ue.existsSync)(r))try{t=JSON.parse((0,ue.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,ue.mkdirSync)((0,Pe.dirname)(r),{recursive:!0}),(0,ue.writeFileSync)(r,JSON.stringify(t,null,2)+`
36
+ `,"utf8")}catch{}}async function ei(r=!1){if(!Oe().telemetry)return{uploaded:0};if(!U())return{uploaded:0};let e=Qa();if(e.length===0)return{uploaded:0};let t=e.slice(0,Ka),n=await F("/api/cli/telemetry",{events:t},1e4);if(n.ok){if(ec(Xa),!r){let s=n.data?.accepted??0;I()?N("telemetry",{uploaded:s}):s>0&&w(`Uploaded ${s} usage event${s===1?"":"s"}`)}return{uploaded:n.data?.accepted??0}}return!r&&!I()&&T("Telemetry upload failed \u2014 will retry next session"),{uploaded:0}}function _n(r){r.command("telemetry").description("Manage usage telemetry").command("push").description("Upload local usage data to Shared Context").option("--quiet","Suppress output").action(async t=>{await ei(t.quiet)})}var Ye,ur,xn,Ka,Xa,On=he(()=>{"use strict";Ye=require("fs"),ur=require("path"),xn=require("os");oe();ue();se();Ka=1e3,Xa=100});var Vn=ge(Wn(),1),{program:pc,createCommand:mc,createArgument:hc,createOption:gc,CommanderError:yc,InvalidArgumentError:Sc,InvalidOptionArgumentError:Ec,Command:qn,Argument:Cc,Option:wc,Help:bc}=Vn.default;se();var ot=require("fs"),Ze=require("path"),eo=require("os");ue();oe();se();var Mr=require("fs"),Ae=require("path"),Be=require("os"),ct=[{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 je(r){if(r){let n=ct.find(o=>o.id===r);if(n)return n;let s=ct.find(o=>o.dir===`.${r}`||o.dir===r);return s||null}for(let n of ct)if(n.envVars.some(s=>process.env[s]))return n;let e=(0,Be.homedir)(),t=[];for(let n of ct)(0,Mr.existsSync)((0,Ae.join)(e,n.dir))&&t.push(n);return t.length===1?t[0]:null}function We(){let r=[],e=(0,Be.homedir)();for(let t of ct)(t.envVars.some(n=>process.env[n])||(0,Mr.existsSync)((0,Ae.join)(e,t.dir)))&&r.push(t);return r}function Ve(){let r=We();return r.length>1?`Multiple AI agents detected (${r.map(e=>e.label).join(", ")}). Use --agent to specify: ${r.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${ct.map(e=>e.id).join(", ")})`}function W(r,e){return e?(0,Ae.join)(process.cwd(),r.dir,r.skillsSubdir):(0,Ae.join)((0,Be.homedir)(),r.dir,r.skillsSubdir)}function re(r,e){return e?(0,Ae.join)(process.cwd(),r.dir,"agents"):(0,Ae.join)((0,Be.homedir)(),r.dir,"agents")}function pe(r,e){return e?(0,Ae.join)(process.cwd(),".mcp.json"):r.id==="claude-code"?(0,Ae.join)((0,Be.homedir)(),".claude.json"):r.id==="cursor"?(0,Ae.join)((0,Be.homedir)(),".cursor","mcp.json"):(0,Ae.join)(process.cwd(),".mcp.json")}function Ie(r,e){return e?(0,Ae.join)(process.cwd(),r.dir,"settings.json"):(0,Ae.join)((0,Be.homedir)(),r.dir,"settings.json")}var fe=require("fs"),rt=require("path");var Re=require("fs"),Te=require("path"),Bs=require("child_process");oe();var Ns=require("child_process"),$s=require("fs"),Ls=require("path"),Fs=require("os"),Ms=ge(Ds());oe();var oa={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};function Ht(r){return oa[r]||"directory"}function dt(r){let t={"claude-code":"claude",cursor:"cursor","gemini-cli":"gemini"}[r];if(!t)return null;try{return(0,Ns.execSync)(`which ${t}`,{stdio:"pipe"}),t}catch{return null}}async function Bt(r,e){let t=await Fr(r),n=(0,Ls.join)((0,Fs.tmpdir)(),`sc-plugin-${e}-${Date.now()}`);return(0,$s.mkdirSync)(n,{recursive:!0}),new Ms.default(t).extractAllTo(n,!0),n}function Wt(r){return{"claude-code":"claude","gemini-cli":"gemini",cursor:"cursor"}[r]||"claude"}ue();se();var ke=require("fs"),_t=require("path"),qr=".shared-context",Gr="project.json";function Ee(){let r=(0,_t.join)(process.cwd(),qr,Gr);if(!(0,ke.existsSync)(r))return null;try{let e=JSON.parse((0,ke.readFileSync)(r,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function tt(r){let e=(0,_t.join)(process.cwd(),qr);(0,ke.mkdirSync)(e,{recursive:!0}),(0,ke.writeFileSync)((0,_t.join)(e,Gr),JSON.stringify(r,null,2)+`
37
+ `,"utf-8")}function Us(){let r=(0,_t.join)(process.cwd(),qr,Gr);return(0,ke.existsSync)(r)?((0,ke.unlinkSync)(r),!0):!1}var Ws={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function G(r,e){let t=(0,Te.resolve)(r);for(let n of e){let s=(0,Te.resolve)((0,Te.join)(r,n.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${n.path}`);(0,Re.mkdirSync)((0,Te.dirname)(s),{recursive:!0}),(0,Re.writeFileSync)(s,n.content,"utf-8")}}function zr(r){let e=r.resource.slug||r.resource.id;return`${Ws[r.resource.resourceType]||r.resource.resourceType+"s"}/${e}`}function Hs(r,e,t,n,s){let o=(0,Te.join)(r,e);if(!(0,Re.existsSync)(o))return{slug:e,renamed:!1};if(!s.installations.find(u=>{let l=u.installPath.split("/");return l[l.length-1]===e&&u.resourceId!==t}))return{slug:e,renamed:!1};let a=n.resource.orgSlug||n.resource.githubOwner||n.resource.id.slice(0,8);return{slug:`${e}-${a}`,renamed:!0}}function Vt(r,e,t){let n=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"))||t.files.find(l=>l.path.endsWith(".json")&&l.path.includes("resources/"));if(!n)throw new Error("MCP package does not contain a config file");let s=JSON.parse(n.content),o=pe(r,e),c=t.resource.slug||t.resource.id,a={};if((0,Re.existsSync)(o))try{a=JSON.parse((0,Re.readFileSync)(o,"utf-8"))}catch{a={}}let u=typeof a.mcpServers=="object"&&a.mcpServers&&!Array.isArray(a.mcpServers)?a.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(u,s.mcpServers):u[c]=s,a.mcpServers=u,(0,Re.mkdirSync)((0,Te.dirname)(o),{recursive:!0}),(0,Re.writeFileSync)(o,JSON.stringify(a,null,2)+`
38
+ `,"utf-8")}function ia(r,e,t,n){let s=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),c=Ie(r,e),a={},u=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:o;for(let[l,p]of Object.entries(u))if(!(l==="name"||l==="description")&&Array.isArray(p)){a[l]||(a[l]=[]);for(let y of p)a[l].push(y)}if(Object.keys(a).length===0)throw new Error("Hook package does not contain any hook event handlers");return Kr(c,a,n),c}function Zr(r,e,t,n={}){let s=r.slug||r.id,o=Ws[r.resourceType]||r.resourceType+"s",c=e.orgSlug?`${e.orgSlug}/`:"";return{resourceId:r.id,slug:s,installPath:`${o}/${c}${s}`,title:r.title,sha:r.latestSha||"",scope:n.projectId?"project":"global",agent:t,installedAt:new Date().toISOString(),collectionId:e.id,resourceType:r.resourceType,latestSha:r.latestSha||void 0,serverSynced:!0,...n.projectId?{projectId:n.projectId}:{}}}async function Jr(r,e,t){let n=[],s=[],o=r.resource.slug||r.resource.id,c=zr(r),a,u="decomposed",l,p=!1;if(r.resource.resourceType==="agent"){let y=re(e,t.project),b=Hs(y,o,r.resource.id,r,t.manifest);b.renamed&&(o=b.slug,c=zr({...r,resource:{...r.resource,slug:o}}),p=!0),a=(0,Te.join)(y,o),G(a,r.files)}else if(r.resource.resourceType==="mcp")a="",Vt(e,t.project,r);else if(r.resource.resourceType==="hook")a="",ia(e,t.project,r,c);else{let y=W(e,t.project);if(r.resource.resourceType!=="collection"){let b=Hs(y,o,r.resource.id,r,t.manifest);b.renamed&&(o=b.slug,c=zr({...r,resource:{...r.resource,slug:o}}),p=!0)}if(a=(0,Te.join)(y,o),r.resource.resourceType==="collection"){let b=dt(e.id);if(b)try{let f=r.resource.slug||r.resource.id,m=r.resource.orgSlug||"",S=Wt(e.id),h=t.authed?`/api/cli/resource/collections/${m}/${f}?format=plugin&platform=${S}`:`/api/public/resource/collections/${m}/${f}?format=plugin&platform=${S}`,E=await Bt(h,f);(0,Bs.execSync)(`${b} plugin install "${E}"`,{stdio:"pipe"}),a=E,u="plugin",l=E,s.push(`Installed as native ${b} plugin`)}catch(f){n.push(`Native plugin install failed, falling back to decomposed: ${f}`);let S=await De(e).install(r,t.project?"project":"user",e);a=S.installDir;for(let h of S.warnings)n.push(h)}else{let m=await De(e).install(r,t.project?"project":"user",e);a=m.installDir;for(let S of m.warnings)n.push(S)}}else G(a,r.files)}return{installDir:a,installPath:c,installMode:u,pluginDir:l,slug:o,renamed:p,warnings:n,notes:s}}function Vs(r){r.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=je(s.agent);if(!o){let i=Ve();I()?D("install","NO_AGENTS",i):T(i),process.exit(1)}let c=U(),u=await Z(`${c?"/api/cli/resource":"/api/public/resource"}/${e}`);u.ok||(I()?D("install",u.error.code,u.error.message):T(`Install failed: ${u.error.message}`),process.exit(1));let l=u.data,p;try{p=await Jr(l,o,{project:!!s.project,manifest:q(),authed:c})}catch(i){I()?D("install","WRITE_FAILED",`Failed to install: ${i}`):T(`Failed to install: ${i}`),process.exit(1)}if(p.renamed&&!I()&&w(`Note: Renamed to "${p.slug}" (collision with existing resource)`),!I()){for(let i of p.notes)w(i);for(let i of p.warnings)T(`Warning: ${i}`)}let y=p.installDir,b=p.installPath,f=p.slug,m=p.installMode,S=p.pluginDir,h;if(c&&l.resource.latestSha){let i=await F("/api/cli/install",{resourceId:l.resource.id,agentPlatform:o.platform,installedSha:l.resource.latestSha});i.ok||(h=`Could not record install on server: ${i.error.message}`,I()||T(`Warning: ${h}`))}let E=s.project?Ee():null;E&&c&&await F(`/api/cli/projects/${E.projectId}/resources`,{resourceId:l.resource.id}).catch(()=>{});let d=l.resource.resourceType==="collection";if(le({resourceId:l.resource.id,slug:f,installPath:b,title:l.resource.title,sha:l.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),latestSha:l.resource.latestSha||void 0,resourceType:l.resource.resourceType,serverSynced:!0,...d?{pluginFormat:Ht(o.id),memberCount:l.memberResources?.length,installMode:m,pluginDir:S}:{},...E?{projectId:E.projectId}:{}}),l.memberResources&&l.resource.resourceType==="collection"){if(m==="decomposed")for(let i of l.memberResources)le(Zr(i,l.resource,o.id,{projectId:E?.projectId}));for(let i of l.memberResources)c&&i.latestSha&&await F("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{})}if(He(),I())N("install",{installPath:b,title:l.resource.title,path:y||void 0,files:l.files.length,...l.resource.resourceType==="mcp"?{mcpConfigPath:pe(o,!!s.project)}:{},...l.resource.resourceType==="hook"?{settingsPath:Ie(o,!!s.project)}:{},...l.memberResources?{memberResources:l.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...h&&{warning:h}});else{if(l.resource.resourceType==="mcp"?w(`Installed MCP "${l.resource.title}" to ${pe(o,!!s.project)}`):l.resource.resourceType==="hook"?w(`Installed hook "${l.resource.title}" to ${Ie(o,!!s.project)}`):l.memberResources&&l.memberResources.length>0?w(`Installed "${l.resource.title}" (${l.memberResources.length} resources)`):w(`Installed "${l.resource.title}" to ${y}`),l.resource.resourceType!=="mcp"&&l.resource.resourceType!=="hook"&&!(l.memberResources&&l.memberResources.length>0)&&w(` ${l.files.length} file${l.files.length===1?"":"s"} written`),l.memberResources&&l.memberResources.length>0){let i={};for(let C of l.memberResources){let O=C.resourceType||"other";i[O]||(i[O]=[]),i[O].push(C.title)}let g={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};w("");for(let[C,O]of Object.entries(i)){let x=g[C]||C;w(` ${x}: ${O.join(", ")}`)}}c||(w(""),w("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var qt=class{buildFiles(e){let t=[],n=[],s=[],o={},c={};for(let a of e.files){let u=a.path.split("/"),l=u[0];if(l==="agents")s.push({path:a.path.slice(7),content:a.content});else if(l==="mcps"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(a.path.includes("resources/")){let y=u.indexOf("resources"),b=y>0?u[y-1]:u[1];o[b]=p}}catch{t.push(`Failed to parse MCP config: ${a.path}`)}}else if(l==="hooks"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content),y=a.path.replace(/\/[^/]+$/,"");aa(p,c,y)}catch{t.push(`Failed to parse hook config: ${a.path}`)}}else l==="skills"||l==="commands"||l==="files"?n.push({path:a.path.slice(l.length+1),content:a.content}):n.push(a)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:c,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=e.resource.slug||e.resource.id,a=W(n,o),u=ua(e),l=(0,rt.join)(a,...u),p=0;if(s.mainFiles.length>0){let y=s.mainFiles.filter(f=>!f.path.includes("/")),b=s.mainFiles.filter(f=>f.path.includes("/"));if(y.length>0){let f=y.find(m=>m.path==="README.md");f&&y.push({path:"SKILL.md",content:la(e,f.content)}),G(l,y),p+=y.length}b.length>0&&(G(a,b),p+=b.length)}if(s.agentFiles.length>0){let y=re(n,o);G(y,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&ca(pe(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Kr(Ie(n,o),s.hookEntries),{installDir:l,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n,s){let o=[],a=W(n,t==="project"),u=(0,rt.join)(a,e),l=!1;return(0,fe.existsSync)(u)&&((0,fe.rmSync)(u,{recursive:!0,force:!0}),l=!0),l||o.push(`Collection directory not found at ${u}`),{removed:l,warnings:o}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,rt.join)(s,e)}};function aa(r,e,t){if(!r||typeof r!="object")return;let n=r,s=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:n;for(let[o,c]of Object.entries(s))if(!(o==="name"||o==="description")&&Array.isArray(c)){e[o]||(e[o]=[]);for(let a of c){let u=t&&typeof a=="object"&&a!==null?{...a,_sc:t}:a;e[o].push(u)}}}function Kr(r,e,t){let n={};if((0,fe.existsSync)(r))try{n=JSON.parse((0,fe.readFileSync)(r,"utf-8"))}catch{n={}}let s=typeof n.hooks=="object"&&n.hooks&&!Array.isArray(n.hooks)?n.hooks:{};if(t)for(let[o,c]of Object.entries(s))Array.isArray(c)&&(s[o]=c.filter(a=>!a||typeof a!="object"||a._sc!==t),s[o].length===0&&delete s[o]);for(let[o,c]of Object.entries(e)){Array.isArray(s[o])||(s[o]=[]);for(let a of c){let u=t&&typeof a=="object"&&a!==null?{...a,_sc:t}:a,l=JSON.stringify(u);s[o].some(y=>JSON.stringify(y)===l)||s[o].push(u)}}n.hooks=s,(0,fe.mkdirSync)((0,rt.dirname)(r),{recursive:!0}),(0,fe.writeFileSync)(r,JSON.stringify(n,null,2)+`
39
+ `,"utf-8")}function Xr(r,e){if(!(0,fe.existsSync)(r))return!1;let t;try{t=JSON.parse((0,fe.readFileSync)(r,"utf-8"))}catch{return!1}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!n)return!1;let s=!1;for(let[o,c]of Object.entries(n)){if(!Array.isArray(c))continue;let a=c.filter(u=>!u||typeof u!="object"||u._sc!==e);a.length!==c.length&&(s=!0,a.length===0?delete n[o]:n[o]=a)}return s&&(t.hooks=n,(0,fe.writeFileSync)(r,JSON.stringify(t,null,2)+`
40
+ `,"utf-8")),s}function ca(r,e){let t={};if((0,fe.existsSync)(r))try{t=JSON.parse((0,fe.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,fe.mkdirSync)((0,rt.dirname)(r),{recursive:!0}),(0,fe.writeFileSync)(r,JSON.stringify(t,null,2)+`
46
41
  `,"utf-8")}function la(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
47
- `)}function ua(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Gt=require("fs"),Vt=require("path");var qt=class{buildFiles(e){let t=[],n=[],s=[];for(let o of e.files){let c=o.path.split("/")[0];c==="agents"?s.push({path:o.path.slice(7),content:o.content}):c==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):c==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):c==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):c==="skills"||c==="files"?n.push({path:o.path.slice(c.length+1),content:o.content}):n.push(o)}return{mainFiles:n,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=H(n,o),c=da(e),u=(0,Vt.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(_=>!_.path.includes("/")),g=s.mainFiles.filter(_=>_.path.includes("/"));if(p.length>0){let _=p.find(f=>f.path==="README.md");_&&p.push({path:"SKILL.md",content:fa(e,_.content)}),q(u,p),a+=p.length}g.length>0&&(q(l,g),a+=g.length)}if(s.agentFiles.length>0){let p=te(n,o);q(p,s.agentFiles),a+=s.agentFiles.length}return{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let s=[],l=H(n,t==="project"),c=(0,Vt.join)(l,e),u=!1;return(0,Gt.existsSync)(c)&&((0,Gt.rmSync)(c,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${c}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=H(n,t==="project");return(0,Vt.join)(s,e)}};function fa(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
48
- `)}function da(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var ke=require("fs"),ft=require("path");var zt=class{buildFiles(e){let t=[],n=[],s={};for(let o of e.files){let l=o.path.split("/"),c=l[0];if(c==="agents")n.push({path:o.path.slice(7),content:o.content});else if(c==="mcps"){if(o.path.endsWith(".json"))try{let u=JSON.parse(o.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(s,u.mcpServers);else if(o.path.includes("resources/")){let a=l.indexOf("resources"),p=a>0?l[a-1]:l[1];s[p]=u}}catch{}}else c==="skills"||c==="commands"||c==="hooks"||c==="files"?t.push({path:o.path.slice(c.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:n,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",l=H(n,o),c=ma(e),u=(0,ft.join)(l,...c),a=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(_=>!_.path.includes("/")),g=s.mainFiles.filter(_=>_.path.includes("/"));p.length>0&&(q(u,p),a+=p.length),g.length>0&&(q(l,g),a+=g.length)}if(s.agentFiles.length>0){let p=te(n,o);q(p,s.agentFiles),a+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&pa(fe(n,o),s.mcpEntries),{installDir:u,filesWritten:a,warnings:s.warnings}}async uninstall(e,t,n){let o=H(n,t==="project"),l=(0,ft.join)(o,e),c=!1;return(0,ke.existsSync)(l)&&((0,ke.rmSync)(l,{recursive:!0,force:!0}),c=!0),{removed:c,warnings:[]}}describeLocation(e,t,n){let s=H(n,t==="project");return(0,ft.join)(s,e)}};function pa(r,e){let t={};if((0,ke.existsSync)(r))try{t=JSON.parse((0,ke.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,ke.mkdirSync)((0,ft.dirname)(r),{recursive:!0}),(0,ke.writeFileSync)(r,JSON.stringify(t,null,2)+`
49
- `,"utf-8")}function ma(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}function Te(r){switch(r.id){case"claude-code":return new Ht;case"gemini-cli":case"antigravity":return new Bt;case"cursor":return new Wt;case"codex":return new qt;default:return new zt}}var Ms=`---
42
+ `)}function ua(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Ce=require("fs"),nt=require("path");var fa={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},Gt=class{buildFiles(e){let t=[],n=[],s=[],o={},c={};for(let a of e.files){let u=a.path.split("/"),l=u[0];if(l==="agents")s.push({path:a.path.slice(7),content:a.content});else if(l==="mcps"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(o,p.mcpServers);else if(a.path.includes("resources/")){let y=u.indexOf("resources"),b=y>0?u[y-1]:u[1];o[b]=p}}catch{t.push(`Failed to parse MCP config: ${a.path}`)}}else if(l==="hooks"){if(a.path.endsWith(".json"))try{let p=JSON.parse(a.content);da(p,c)}catch{t.push(`Failed to parse hook config: ${a.path}`)}}else l==="skills"||l==="commands"||l==="files"?n.push({path:a.path.slice(l.length+1),content:a.content}):n.push(a)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:c,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=e.resource.slug||e.resource.id,a=W(n,o),u=ga(e),l=(0,nt.join)(a,...u),p=0;if(s.mainFiles.length>0){let y=s.mainFiles.filter(f=>!f.path.includes("/")),b=s.mainFiles.filter(f=>f.path.includes("/"));if(y.length>0){let f=y.find(m=>m.path==="README.md");f&&y.push({path:"SKILL.md",content:ha(e,f.content)}),G(l,y),p+=y.length}b.length>0&&(G(a,b),p+=b.length)}if(s.agentFiles.length>0){let y=re(n,o);G(y,s.agentFiles),p+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&ma(pe(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&pa(Ie(n,o),s.hookEntries),{installDir:l,filesWritten:p,warnings:s.warnings}}async uninstall(e,t,n){let s=[],c=W(n,t==="project"),a=(0,nt.join)(c,e),u=!1;return(0,Ce.existsSync)(a)&&((0,Ce.rmSync)(a,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${a}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,nt.join)(s,e)}};function da(r,e){if(!r||typeof r!="object")return;let t=r,n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(n)){if(s==="name"||s==="description"||!Array.isArray(o))continue;let c=fa[s]||s;e[c]||(e[c]=[]);for(let a of o)e[c].push(a)}}function pa(r,e){let t={};if((0,Ce.existsSync)(r))try{t=JSON.parse((0,Ce.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{};for(let[s,o]of Object.entries(e)){Array.isArray(n[s])||(n[s]=[]);for(let c of o){let a=JSON.stringify(c);n[s].some(l=>JSON.stringify(l)===a)||n[s].push(c)}}t.hooks=n,(0,Ce.mkdirSync)((0,nt.dirname)(r),{recursive:!0}),(0,Ce.writeFileSync)(r,JSON.stringify(t,null,2)+`
43
+ `,"utf-8")}function ma(r,e){let t={};if((0,Ce.existsSync)(r))try{t=JSON.parse((0,Ce.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Ce.mkdirSync)((0,nt.dirname)(r),{recursive:!0}),(0,Ce.writeFileSync)(r,JSON.stringify(t,null,2)+`
44
+ `,"utf-8")}function ha(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
45
+ `)}function ga(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var de=require("fs"),Le=require("path");var zt=class{buildFiles(e){let t=[],n=[],s=[],o={},c=[],a=e.resource.slug||e.resource.id;for(let u of e.files){let l=u.path.split("/"),p=l[0];if(p==="agents")s.push({path:u.path.slice(7),content:u.content});else if(p==="mcps"){if(u.path.endsWith(".json"))try{let y=JSON.parse(u.content);if(y.mcpServers&&typeof y.mcpServers=="object")Object.assign(o,y.mcpServers);else if(u.path.includes("resources/")){let b=l.indexOf("resources"),f=b>0?l[b-1]:l[1];o[f]=y}}catch{t.push(`Failed to parse MCP config: ${u.path}`)}}else p==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${u.path})`):p==="skills"||p==="commands"||p==="files"?n.push({path:u.path.slice(p.length+1),content:u.content}):n.push(u)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:c,warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=W(n,o),a=Ea(e),u=(0,Le.join)(c,...a),l=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(b=>!b.path.includes("/")),y=s.mainFiles.filter(b=>b.path.includes("/"));if(p.length>0){let b=p.find(f=>f.path==="README.md");b&&p.push({path:"SKILL.md",content:Sa(e,b.content)}),G(u,p),l+=p.length}y.length>0&&(G(c,y),l+=y.length)}if(s.agentFiles.length>0){let p=re(n,o);G(p,s.agentFiles),l+=s.agentFiles.length}for(let p of s.customFiles)(0,de.mkdirSync)((0,Le.dirname)(p.absolutePath),{recursive:!0}),(0,de.writeFileSync)(p.absolutePath,p.content,"utf-8"),l++;return Object.keys(s.mcpEntries).length>0&&ya(pe(n,o),s.mcpEntries),{installDir:u,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,n){let s=[],c=W(n,t==="project"),a=(0,Le.join)(c,e),u=!1;(0,de.existsSync)(a)&&((0,de.rmSync)(a,{recursive:!0,force:!0}),u=!0);let l=(0,Le.join)(homedir(),".cursor","rules");if((0,de.existsSync)(l))try{let p=(0,de.readdirSync)(l);for(let y of p)y.startsWith(`${e}-`)&&y.endsWith(".mdc")&&((0,de.unlinkSync)((0,Le.join)(l,y)),u=!0)}catch{s.push("Could not clean up Cursor rules")}return u||s.push(`Collection not found for Cursor at ${a}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Le.join)(s,e)}};function ya(r,e){let t={};if((0,de.existsSync)(r))try{t=JSON.parse((0,de.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,de.mkdirSync)((0,Le.dirname)(r),{recursive:!0}),(0,de.writeFileSync)(r,JSON.stringify(t,null,2)+`
46
+ `,"utf-8")}function Sa(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
47
+ `)}function Ea(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Kt=require("fs"),Zt=require("path");var Jt=class{buildFiles(e){let t=[],n=[],s=[];for(let o of e.files){let a=o.path.split("/")[0];a==="agents"?s.push({path:o.path.slice(7),content:o.content}):a==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):a==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):a==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):a==="skills"||a==="files"?n.push({path:o.path.slice(a.length+1),content:o.content}):n.push(o)}return{mainFiles:n,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=W(n,o),a=wa(e),u=(0,Zt.join)(c,...a),l=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(b=>!b.path.includes("/")),y=s.mainFiles.filter(b=>b.path.includes("/"));if(p.length>0){let b=p.find(f=>f.path==="README.md");b&&p.push({path:"SKILL.md",content:Ca(e,b.content)}),G(u,p),l+=p.length}y.length>0&&(G(c,y),l+=y.length)}if(s.agentFiles.length>0){let p=re(n,o);G(p,s.agentFiles),l+=s.agentFiles.length}return{installDir:u,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,n){let s=[],c=W(n,t==="project"),a=(0,Zt.join)(c,e),u=!1;return(0,Kt.existsSync)(a)&&((0,Kt.rmSync)(a,{recursive:!0,force:!0}),u=!0),u||s.push(`Collection directory not found at ${a}`),{removed:u,warnings:s}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,Zt.join)(s,e)}};function Ca(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
48
+ `)}function wa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Pe=require("fs"),pt=require("path");var Xt=class{buildFiles(e){let t=[],n=[],s={};for(let o of e.files){let c=o.path.split("/"),a=c[0];if(a==="agents")n.push({path:o.path.slice(7),content:o.content});else if(a==="mcps"){if(o.path.endsWith(".json"))try{let u=JSON.parse(o.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(s,u.mcpServers);else if(o.path.includes("resources/")){let l=c.indexOf("resources"),p=l>0?c[l-1]:c[1];s[p]=u}}catch{}}else a==="skills"||a==="commands"||a==="hooks"||a==="files"?t.push({path:o.path.slice(a.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:n,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=W(n,o),a=Aa(e),u=(0,pt.join)(c,...a),l=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(b=>!b.path.includes("/")),y=s.mainFiles.filter(b=>b.path.includes("/"));p.length>0&&(G(u,p),l+=p.length),y.length>0&&(G(c,y),l+=y.length)}if(s.agentFiles.length>0){let p=re(n,o);G(p,s.agentFiles),l+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&ba(pe(n,o),s.mcpEntries),{installDir:u,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,n){let o=W(n,t==="project"),c=(0,pt.join)(o,e),a=!1;return(0,Pe.existsSync)(c)&&((0,Pe.rmSync)(c,{recursive:!0,force:!0}),a=!0),{removed:a,warnings:[]}}describeLocation(e,t,n){let s=W(n,t==="project");return(0,pt.join)(s,e)}};function ba(r,e){let t={};if((0,Pe.existsSync)(r))try{t=JSON.parse((0,Pe.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Pe.mkdirSync)((0,pt.dirname)(r),{recursive:!0}),(0,Pe.writeFileSync)(r,JSON.stringify(t,null,2)+`
49
+ `,"utf-8")}function Aa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}function De(r){switch(r.id){case"claude-code":return new qt;case"gemini-cli":case"antigravity":return new Gt;case"cursor":return new zt;case"codex":return new Jt;default:return new Xt}}var qs=`---
50
50
  name: Context Manager
51
51
  description: "Your AI chief of staff \u2014 distills expert knowledge into resources, finds off-the-shelf solutions, and manages your working context"
52
52
  tools:
@@ -135,42 +135,43 @@ When building custom resources, follow these patterns:
135
135
  - **Specificity over comprehensiveness** \u2014 Only include instructions that meaningfully change Claude's output
136
136
  - **Filesystem as memory** \u2014 Design persistent storage so resources accumulate knowledge over time
137
137
  - **Search before building** \u2014 Check the Shared Context library before creating from scratch
138
- `;ne();ce();var M=require("fs"),z=require("path"),Ws=require("crypto");var Zt=".context-collection",Jt="manifest.json";function Us(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function ha(r,e){return{version:1,name:r.name||"Untitled Extension",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function ga(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}var qr=[{path:`${Zt}/${Jt}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:Us,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:Us,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:ha,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:ga,formatLabel:"Cursor Plugin"}];var Hs=[{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}],Bs=`${Zt}/${Jt}`;function tt(r){let e={name:"",description:"",body:r};if(!r.startsWith(`---
138
+ `;oe();ue();var B=require("fs"),J=require("path"),Js=require("crypto");var Yt=".context-collection",Qt="manifest.json";function Gs(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function Ia(r,e){return{version:1,name:r.name||"Untitled Extension",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function xa(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}var Yr=[{path:`${Yt}/${Qt}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:Gs,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:Gs,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:Ia,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:xa,formatLabel:"Cursor Plugin"}];var zs=[{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}],Zs=`${Yt}/${Qt}`;function st(r){let e={name:"",description:"",body:r};if(!r.startsWith(`---
139
139
  `)&&!r.startsWith(`---\r
140
140
  `))return e;let t=r.indexOf(`
141
- ---`,3);if(t===-1)return e;let n=r.slice(4,t),s=r.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let o={},l={},c=new Set(["requires","tools"]),u={},a=n.split(`
142
- `),p=null,g=!1;for(let _=0;_<a.length;_++){let f=a[_];if(p&&/^\s+-\s/.test(f)){let C=f.replace(/^\s+-\s/,"").trim();if(C){let m=dt(C);g?u[p].push(m):l[p].push(m)}continue}p=null,g=!1;let h=f.indexOf(":");if(h===-1)continue;let E=f.slice(0,h).trim(),y=f.slice(h+1).trim();if(!y&&E&&_+1<a.length&&/^\s+-\s/.test(a[_+1])){p=E,c.has(E)?(g=!0,u[E]=[]):(g=!1,l[E]=[]);continue}E==="name"||E==="title"?e.name=dt(y):E==="description"?e.description=dt(y):E==="skill_class"?e.skillClass=dt(y):E==="service"?e.service=dt(y):E&&y&&(o[E]=dt(y))}return u.requires?.length&&(e.requires=u.requires),u.tools?.length&&(e.tools=u.tools),Object.keys(o).length&&(e.fields=o),Object.keys(l).length&&(e.arrayFields=l),e}function dt(r){let e=r.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")){let t=e.slice(1,-1);return e.startsWith('"')?t.replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.replace(/''/g,"'")}return e}function ya(r){let{body:e}=tt(r);return e.replace(/\r\n/g,`
143
- `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function je(r){let e=ya(r);return`sha256:${(0,Ws.createHash)("sha256").update(e,"utf8").digest("hex")}`}function _e(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function At(r){try{return(0,M.statSync)(r).isDirectory()}catch{return!1}}function Gr(r){try{return(0,M.readdirSync)(r).filter(e=>!e.startsWith(".")&&At((0,z.join)(r,e)))}catch{return[]}}function zr(r){try{return(0,M.readdirSync)(r).filter(e=>!e.startsWith(".")&&!At((0,z.join)(r,e)))}catch{return[]}}function Kt(r,e){let t=[],n=[],s,o;function l(f,h){let E=[],y=[];for(let C of Hs){let m=(0,z.join)(f,C.folder);if(!(0,M.existsSync)(m)||!At(m))continue;let i=h?`${h}/${C.folder}`:C.folder;if(C.folder==="files"){for(let d of zr(m)){if(!d.endsWith(".md"))continue;let S=(0,z.join)(m,d),b=(0,M.readFileSync)(S,"utf-8"),A=tt(b),I=A.name||(0,z.basename)(d,".md"),O=`${i}/${(0,z.basename)(d,".md")}`;E.push({importPath:O,resourceType:"file",title:I,description:A.description||null,body:A.body,bodyHash:je(b),metadata:{}})}continue}if(C.mainFile===null)for(let d of zr(m)){if(!d.endsWith(".md"))continue;let S=(0,z.basename)(d,".md"),b=`${i}/${S}`;if(At((0,z.join)(m,S)))continue;let A=(0,M.readFileSync)((0,z.join)(m,d),"utf-8"),I=tt(A),O=I.name||_e(S),k={};I.skillClass&&(k.skillClass=I.skillClass),I.service&&(k.service=I.service),I.requires?.length&&(k.requires=I.requires),I.tools?.length&&(k.tools=I.tools),I.fields&&Object.keys(I.fields).length&&(k.fields=I.fields),C.folder==="commands"&&(k.fields||(k.fields={}),k.fields["user-invocable"]="true"),E.push({importPath:b,resourceType:C.resourceType,title:O,description:I.description||null,body:I.body,bodyHash:je(A),metadata:k})}for(let d of Gr(m)){let S=C.mainFile||`${d}.md`,b=(0,z.join)(m,d,S);if(!(0,M.existsSync)(b)){if(C.mainFile===null)for(let U of Gr((0,z.join)(m,d))){let W=`${U}.md`,ee=(0,z.join)(m,d,U,W);if(!(0,M.existsSync)(ee))continue;let Je=(0,M.readFileSync)(ee,"utf-8"),ye=tt(Je),ri=ye.name||_e(U),ot={};ye.skillClass&&(ot.skillClass=ye.skillClass),ye.service&&(ot.service=ye.service),ye.requires?.length&&(ot.requires=ye.requires),ye.tools?.length&&(ot.tools=ye.tools),ye.fields&&Object.keys(ye.fields).length&&(ot.fields=ye.fields),E.push({importPath:`${i}/${U}`,resourceType:C.resourceType,title:ri,description:ye.description||null,body:ye.body,bodyHash:je(Je),metadata:ot})}continue}let A=(0,M.readFileSync)(b,"utf-8"),I=`${i}/${d}`,O,k,v,P={},j=null;if(C.resourceType==="hook"||C.resourceType==="mcp"){try{let U=JSON.parse(A);O=U.name||_e(d),k=U.description||null}catch{O=_e(d),k=null}v=A}else if(C.resourceType==="collection"){let U=(0,z.join)(m,d,Zt,Jt);if((0,M.existsSync)(U))try{let W=JSON.parse((0,M.readFileSync)(U,"utf-8"));O=W.name||_e(d),k=W.description||null,v=A,W.resources&&Array.isArray(W.resources)&&y.push({collectionImportPath:I,memberImportPaths:W.resources.map(ee=>{let Je=ee.split("/");return Je.length>=3?`${Je[0]}/${Je[Je.length-1]}`:ee})})}catch{O=_e(d),k=null,v=A}else j=tt(A),O=j.name||_e(d),k=j.description||null,v=j.body,j.arrayFields?.resources&&y.push({collectionImportPath:I,memberImportPaths:j.arrayFields.resources.map(W=>{let ee=W.split("/");return ee.length>=3?`${ee[0]}/${ee[ee.length-1]}`:W})})}else j=tt(A),O=j.name||_e(d),k=j.description||null,v=j.body,j.skillClass&&(P.skillClass=j.skillClass),j.service&&(P.service=j.service),j.requires?.length&&(P.requires=j.requires),j.tools?.length&&(P.tools=j.tools),j.fields&&Object.keys(j.fields).length&&(P.fields=j.fields);C.folder==="commands"&&(P.fields||(P.fields={}),P.fields["user-invocable"]="true"),E.push({importPath:I,resourceType:C.resourceType,title:O,description:k,body:v,bodyHash:je(A),metadata:P})}}return{resources:E,memberships:y}}let c=l(r,"");t.push(...c.resources),n.push(...c.memberships);let u=new Set;e?.mcpConfigPath&&u.add(e.mcpConfigPath);let a=(0,z.join)(r,".mcp.json");(0,M.existsSync)(a)&&u.add(a);for(let f of u)if((0,M.existsSync)(f))try{let h=JSON.parse((0,M.readFileSync)(f,"utf-8"));if(h.mcpServers&&typeof h.mcpServers=="object")for(let[E,y]of Object.entries(h.mcpServers)){let C=`mcps/${E}`;if(t.some(d=>d.importPath===C))continue;let m=_e(E),i=JSON.stringify({name:m,description:`MCP server: ${E}`,mcpServers:{[E]:y}},null,2);t.push({importPath:C,resourceType:"mcp",title:m,description:`MCP server: ${E}`,body:i,bodyHash:je(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,M.existsSync)(e.settingsPath))try{let f=JSON.parse((0,M.readFileSync)(e.settingsPath,"utf-8"));if(f.hooks&&typeof f.hooks=="object"&&!Array.isArray(f.hooks)){let h={};for(let[E,y]of Object.entries(f.hooks))if(Array.isArray(y))for(let C of y){if(!C||typeof C!="object")continue;let m=C,i=m._sc;if(!i)continue;h[i]||(h[i]={}),h[i][E]||(h[i][E]=[]);let{_sc:d,...S}=m;h[i][E].push(S)}for(let[E,y]of Object.entries(h)){let C=E;if(t.some(S=>S.importPath===C))continue;let m=E.split("/").pop()||E,i=_e(m),d=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:y},null,2);t.push({importPath:C,resourceType:"hook",title:i,description:`Hook: ${i}`,body:d,bodyHash:je(d),metadata:{}})}}}catch{}for(let f of qr){if(f.path===Bs)continue;let h=(0,z.join)(r,f.path);if((0,M.existsSync)(h)){try{let E=JSON.parse((0,M.readFileSync)(h,"utf-8"));if(s=s||E.name||void 0,o=f.formatLabel,!t.some(y=>y.resourceType==="collection")){let y=t.filter(S=>S.resourceType!=="collection").map(S=>({resourceRef:S.importPath})),C=f.converter(E,y),m=(0,z.join)(r,"README.md"),i=(0,M.existsSync)(m)?(0,M.readFileSync)(m,"utf-8"):"",d="collections/_root";t.push({importPath:d,resourceType:"collection",title:_e(C.name),description:C.description||null,body:i,bodyHash:je(i),metadata:{},manifestMetadata:{...C.author?{author:C.author}:{},...C.homepage?{homepage:C.homepage}:{},...C.license?{license:C.license}:{}}}),C.resources.length>0&&n.push({collectionImportPath:d,memberImportPaths:C.resources})}}catch{}break}}{let y=function(C,m,i){if(!(i>4))for(let d of Gr(C)){if(E.has(d))continue;let S=(0,z.join)(C,d),b=m?`${m}/${d}`:d;for(let A of qr){if(A.path===Bs)continue;let I=(0,z.join)(S,A.path);if((0,M.existsSync)(I)){if(f.has(b))break;f.add(b);try{let O=JSON.parse((0,M.readFileSync)(I,"utf-8")),k=l(S,b);if(k.resources.length===0)break;t.push(...k.resources),n.push(...k.memberships);let v=k.resources.filter(ee=>ee.resourceType!=="collection").map(ee=>({resourceRef:ee.importPath})),P=A.converter(O,v),j=(0,z.join)(S,"README.md"),U=(0,M.existsSync)(j)?(0,M.readFileSync)(j,"utf-8"):"",W=`${b}/_collection`;t.push({importPath:W,resourceType:"collection",title:_e(P.name),description:P.description||null,body:U,bodyHash:je(U),metadata:{},manifestMetadata:{...P.author?{author:P.author}:{},...P.homepage?{homepage:P.homepage}:{},...P.license?{license:P.license}:{}}}),n.push({collectionImportPath:W,memberImportPaths:k.resources.map(ee=>ee.importPath)}),s||(s=O.name||void 0),o||(o=A.formatLabel)}catch{}break}}y(S,b,i+1)}};var _=y;let f=new Set,h=new Set(Hs.map(C=>C.folder)),E=new Set([...h,"worktrees","plugins","node_modules","todos"]);y(r,"",0)}let p=(0,z.join)(r,"files");if((0,M.existsSync)(p)&&At(p)&&!t.some(f=>f.resourceType==="file"))for(let f of zr(p)){if(!f.endsWith(".md"))continue;let h=(0,z.join)(p,f),E=(0,M.readFileSync)(h,"utf-8"),y=tt(E),C=y.name||(0,z.basename)(f,".md"),m=`files/${(0,z.basename)(f,".md")}`;t.some(i=>i.importPath===m)||t.push({importPath:m,resourceType:"file",title:C,description:y.description||null,body:y.body,bodyHash:je(E),metadata:{}})}return{resources:[...t.filter(f=>f.resourceType!=="collection"),...t.filter(f=>f.resourceType==="collection")],collectionMemberships:n,pluginName:s,formatLabel:o}}async function Xt(r){let{scanRoots:e,agentId:t,platformInternals:n=[".claude-plugin"],registerToProject:s=!1,skipImport:o=!1}=r,l=[],c=[],u=new Set;for(let{root:I,agent:O,isProject:k}of e){let v=Kt(I,{settingsPath:we(O,k),mcpConfigPath:fe(O,k)});for(let P of v.resources)u.has(P.importPath)||(u.add(P.importPath),l.push({...P,scope:k?"project":"global"}));for(let P of v.collectionMemberships)u.has(`cm:${P.collectionImportPath}`)||(u.add(`cm:${P.collectionImportPath}`),c.push(P))}let a=l.map(I=>I.importPath),p=V(),g=new Set(p.installations.map(I=>I.installPath)),_=new Map;for(let I of p.installations){let O=I.installPath.split("/"),k=O[0],v=O[O.length-1];_.has(k)||_.set(k,new Set),_.get(k).add(v)}let f=new Set(n),h=l.filter(I=>{if(g.has(I.importPath))return!1;let O=I.importPath.split("/"),k=O[0],v=O[O.length-1];return!((k==="mcps"||k==="hooks")&&_.get(k)?.has(v)||I.importPath.startsWith(".")||f.has(v)||I.importPath.startsWith("plugins/"))});for(let I of h)I.description&&I.description.length>1e3&&(I.description=I.description.slice(0,997)+"...");let E=h.length,y=h.map(I=>({importPath:I.importPath,resourceType:I.resourceType,title:I.title}));if(h.length===0||o)return{imported:[],errors:0,projectRegistered:0,untrackedCount:E,discoveredPaths:a,untracked:y};let C={dryRun:!1,onConflict:"auto",visibility:"org",resources:h,collectionMemberships:c.length>0?c:void 0},m=await $("/api/cli/import",C,12e4);if(!m.ok)return{imported:[],errors:h.length,projectRegistered:0,untrackedCount:E,discoveredPaths:a,untracked:y};let i=[...m.data.created,...m.data.updated,...m.data.installed],d=new Map;for(let I of l)d.set(I.importPath,I.scope);let S=Se();for(let I of i){if(!I.id)continue;let O=d.get(I.importPath)||"global";ae({resourceId:I.id,slug:I.slug||I.importPath.split("/").pop()||I.id,installPath:I.importPath,title:I.importPath.split("/").pop()||I.id,sha:I.commitSha||"",scope:O,agent:t,installedAt:new Date().toISOString(),resourceType:I.resourceType,serverSynced:!0,...O==="project"&&S?{projectId:S.projectId}:{}})}let b=0;if(s&&S){let I=[...i,...m.data.skipped];for(let O of I){let k=O.id||O.existingId;if(!k||d.get(O.importPath)!=="project")continue;let P=await $(`/api/cli/projects/${S.projectId}/resources`,{resourceId:k});P.ok&&P.data.added&&b++}}return{imported:i.map(I=>({resourceType:I.resourceType||I.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:I.slug||I.importPath.split("/").pop()||"",title:I.importPath.split("/").pop()||"",importPath:I.importPath,id:I.id})),errors:m.data.errors.length,projectRegistered:b,untrackedCount:E,discoveredPaths:a,untracked:[]}}var Js=require("readline");function Ea(){if(process.platform==="darwin")try{let{execSync:r}=require("child_process"),e=r("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var We="context-manager",zs="Context Manager",Yt="collections/shared-context/context-manager";function Ca(r,e){let t=te(r,e),n=(0,Ve.join)(t,We);return(0,rt.mkdirSync)(n,{recursive:!0}),(0,rt.writeFileSync)((0,Ve.join)(n,`${We}.md`),Ms,"utf-8"),(0,Ve.join)(n,`${We}.md`)}var wa={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ba(r){return V().installations.some(t=>t.installPath===Yt&&t.agent===r)}function Ks(r){r.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(n.code){let{post:m}=await Promise.resolve().then(()=>(ne(),Zn)),{saveAuth:i}=await Promise.resolve().then(()=>(ce(),Rt)),d=await m("/api/cli/auth",{code:n.code});d.ok?(i({token:d.data.token,email:d.data.user.email,orgId:d.data.org.id,orgSlug:d.data.org.slug,orgName:d.data.org.name,createdAt:new Date().toISOString()}),x()||w(`Authenticated as ${d.data.user.email}`)):L()?x()||w("Auth code already used, continuing with saved credentials."):(x()?D("init",d.error.code,d.error.message):T(`Auth failed: ${d.error.message}`),process.exit(1))}else L()||(x()?(D("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(T("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let m=ve(n.agent);if(!m){let i=`Unknown agent: ${n.agent}. Available: ${Fe().map(d=>d.id).join(", ")||"none detected"}`;x()?D("init","NO_AGENTS",i):T(i),process.exit(1)}s=[m]}else if(s=Fe(),s.length===0){let m=Me();x()?D("init","NO_AGENTS",m):T(m),process.exit(1)}let o=Ae(),l=Ea(),c;if(n.linkProject){if(!o?.token){let k="Authentication required for project linking. Run init with --code first.";x()?D("init","AUTH_REQUIRED",k):T(k),process.exit(1)}let m=s[0],i=await $("/api/cli/register-agent",{platform:m.platform,name:`CLI (${l})`});i.ok&&(c=i.data.connectionId);let d=await $(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});d.ok||(x()?D("init",d.error.code,d.error.message):T(`Failed to join project: ${d.error.message}`),process.exit(1));let{project:S,resources:b,members:A}=d.data;Ye({projectId:S.id,projectName:S.name,projectSlug:S.slug});let I=Te(m),O=[];for(let k of b)try{let v=k.installPath,P=await G(`/api/cli/resource/${v}`);if(!P.ok)continue;let j=P.data;await I.install(j,"project",m),ae({resourceId:k.id,slug:k.slug||k.id,installPath:v,title:k.title,sha:k.latestSha||"",scope:"project",agent:m.id,installedAt:new Date().toISOString(),projectId:S.id}),k.latestSha&&await $("/api/cli/install",{resourceId:k.id,agentPlatform:m.platform,installedSha:k.latestSha}).catch(()=>{}),O.push({title:k.title,resourceType:k.resourceType})}catch{}if(await $(`/api/cli/projects/${S.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Tt({lastSyncAt:new Date().toISOString()}),x())N("init",{project:{id:S.id,name:S.name,slug:S.slug},agent:m.id,resourcesInstalled:O.length,memberCount:A.length});else{if(w(""),w(`Joined project: ${S.name}`),S.description&&w(`"${S.description}"`),w(""),O.length>0){w(`Installed ${O.length} resource${O.length===1?"":"s"}:`);let k={};for(let P of O)k[P.resourceType]||(k[P.resourceType]=[]),k[P.resourceType].push(P.title);let v={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[P,j]of Object.entries(k))w(` ${v[P]||P}: ${j.join(", ")}`)}else w("No resources to install (project is empty)");A.length>0&&(w(""),w(`Team (${A.length}): ${A.map(k=>k.name).join(", ")}`)),w(""),w("Quick reference:"),w(" shared-context-ai status View project sync status"),w(" shared-context-ai sync Check for resource updates")}return}let u=!1,a,p=(0,Ve.basename)(process.cwd()),g=Se();if(o?.token&&!g&&p&&p!=="/")try{let m=await $("/api/cli/projects",{name:p});if(m.ok){let{id:i,name:d,slug:S}=m.data;Ye({projectId:i,projectName:d,projectSlug:S}),u=!0,x()||w(`Created project: ${d}`)}else a=m.error.message,x()||T(`Project creation failed: ${a}`)}catch(m){a=m instanceof Error?m.message:String(m),x()||T(`Project creation error: ${a}`)}else g?u=!1:o?.token||(a="not authenticated");let _=[],f={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let m of s){let i=!1,d=!1,S=[],b=[];if(o?.token){let A=await $("/api/cli/register-agent",{platform:m.platform,name:`CLI (${l})`});if(A.ok){if(!c){c=A.data.connectionId;let{saveAuth:I}=await Promise.resolve().then(()=>(ce(),Rt));I({...o,connectionId:c})}}else x()||T(`Warning: Could not register ${m.label} connection: ${A.error.message}`)}if(o?.token&&ba(m.id))d=!0,i=!0;else if(o?.token)try{let A=await G(`/api/cli/resource/${Yt}`);if(A.ok){let I=A.data,k=await Te(m).install(I,n.project?"project":"user",m);if(ae({resourceId:I.resource.id,slug:I.resource.slug||"context-manager",installPath:Yt,title:I.resource.title,sha:I.resource.latestSha||"",scope:n.project?"project":"global",agent:m.id,installedAt:new Date().toISOString(),pluginFormat:f[m.id]||"directory",memberCount:I.memberResources?.length}),I.resource.latestSha&&await $("/api/cli/install",{resourceId:I.resource.id,agentPlatform:m.platform,installedSha:I.resource.latestSha}).catch(()=>{}),I.memberResources)for(let v of I.memberResources){let P=v.slug||v.id,j=wa[v.resourceType]||v.resourceType+"s",U=v.orgSlug||I.resource.orgSlug,W=U?`${j}/${U}/${P}`:`${j}/${P}`;ae({resourceId:v.id,slug:P,installPath:W,title:v.title,sha:v.latestSha||"",scope:n.project?"project":"global",agent:m.id,installedAt:new Date().toISOString(),collectionId:I.resource.id}),S.push({title:v.title,resourceType:v.resourceType}),v.latestSha&&await $("/api/cli/install",{resourceId:v.id,agentPlatform:m.platform,installedSha:v.latestSha}).catch(()=>{})}if(i=!0,!x()&&k.warnings.length>0)for(let v of k.warnings)T(`Warning: ${v}`)}}catch{}if(!i&&(Ca(m,!!n.project),ae({resourceId:"context-manager",slug:We,installPath:`agents/${We}`,title:zs,sha:"",scope:n.project?"project":"global",agent:m.id,installedAt:new Date().toISOString()}),o?.token))try{let A=`agents/shared-context/${We}`,I=await G(`/api/cli/resource/${A}`);if(I.ok&&I.data.resource){let O=I.data.resource;O.latestSha&&await $("/api/cli/install",{resourceId:O.id,agentPlatform:m.platform,installedSha:O.latestSha}),ae({resourceId:O.id,slug:O.slug||We,installPath:`agents/shared-context/${O.slug||We}`,title:O.title||zs,sha:O.latestSha||"",scope:n.project?"project":"global",agent:m.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let A=[],I=(0,Ve.join)(process.cwd(),m.dir),O=(0,Ve.join)((0,Zs.homedir)(),m.dir);(0,rt.existsSync)(I)&&A.push({root:I,agent:m,isProject:!0}),I!==O&&(0,rt.existsSync)(O)&&A.push({root:O,agent:m,isProject:!1}),A.length>0&&(b=(await Xt({scanRoots:A,agentId:m.id,platformInternals:["context-manager",".claude-plugin"],registerToProject:!0})).imported.map(v=>({resourceType:v.resourceType,slug:v.slug,title:v.title})))}catch{}_.push({agent:m,collectionInstalled:i,installedMembers:S,importedResources:b,skippedEssentials:d})}if(Tt({lastSyncAt:new Date().toISOString()}),_.some(m=>!m.skippedEssentials)&&!x()&&process.stdin.isTTY){let{getConfig:m,updateConfig:i}=await Promise.resolve().then(()=>(ce(),Rt));if(m().telemetry===void 0)try{if(await new Promise(b=>{let A=(0,Js.createInterface)({input:process.stdin,output:process.stdout});A.question(`
141
+ ---`,3);if(t===-1)return e;let n=r.slice(4,t),s=r.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let o={},c={},a=new Set(["requires","tools"]),u={},l=n.split(`
142
+ `),p=null,y=!1;for(let b=0;b<l.length;b++){let f=l[b];if(p&&/^\s+-\s/.test(f)){let E=f.replace(/^\s+-\s/,"").trim();if(E){let d=mt(E);y?u[p].push(d):c[p].push(d)}continue}p=null,y=!1;let m=f.indexOf(":");if(m===-1)continue;let S=f.slice(0,m).trim(),h=f.slice(m+1).trim();if(!h&&S&&b+1<l.length&&/^\s+-\s/.test(l[b+1])){p=S,a.has(S)?(y=!0,u[S]=[]):(y=!1,c[S]=[]);continue}S==="name"||S==="title"?e.name=mt(h):S==="description"?e.description=mt(h):S==="skill_class"?e.skillClass=mt(h):S==="service"?e.service=mt(h):S&&h&&(o[S]=mt(h))}return u.requires?.length&&(e.requires=u.requires),u.tools?.length&&(e.tools=u.tools),Object.keys(o).length&&(e.fields=o),Object.keys(c).length&&(e.arrayFields=c),e}function mt(r){let e=r.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")){let t=e.slice(1,-1);return e.startsWith('"')?t.replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.replace(/''/g,"'")}return e}function _a(r){let{body:e}=st(r);return e.replace(/\r\n/g,`
143
+ `).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Fe(r){let e=_a(r);return`sha256:${(0,Js.createHash)("sha256").update(e,"utf8").digest("hex")}`}function ve(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Ot(r){try{return(0,B.statSync)(r).isDirectory()}catch{return!1}}function Qr(r){try{return(0,B.readdirSync)(r).filter(e=>!e.startsWith(".")&&Ot((0,J.join)(r,e)))}catch{return[]}}function en(r){try{return(0,B.readdirSync)(r).filter(e=>!e.startsWith(".")&&!Ot((0,J.join)(r,e)))}catch{return[]}}function er(r,e){let t=[],n=[],s,o;function c(f,m){let S=[],h=[];for(let E of zs){let d=(0,J.join)(f,E.folder);if(!(0,B.existsSync)(d)||!Ot(d))continue;let i=m?`${m}/${E.folder}`:E.folder;if(E.folder==="files"){for(let g of en(d)){if(!g.endsWith(".md"))continue;let C=(0,J.join)(d,g),O=(0,B.readFileSync)(C,"utf-8"),x=st(O),A=x.name||(0,J.basename)(g,".md"),v=`${i}/${(0,J.basename)(g,".md")}`;S.push({importPath:v,resourceType:"file",title:A,description:x.description||null,body:x.body,bodyHash:Fe(O),metadata:{}})}continue}if(E.mainFile===null)for(let g of en(d)){if(!g.endsWith(".md"))continue;let C=(0,J.basename)(g,".md"),O=`${i}/${C}`;if(Ot((0,J.join)(d,C)))continue;let x=(0,B.readFileSync)((0,J.join)(d,g),"utf-8"),A=st(x),v=A.name||ve(C),k={};A.skillClass&&(k.skillClass=A.skillClass),A.service&&(k.service=A.service),A.requires?.length&&(k.requires=A.requires),A.tools?.length&&(k.tools=A.tools),A.fields&&Object.keys(A.fields).length&&(k.fields=A.fields),E.folder==="commands"&&(k.fields||(k.fields={}),k.fields["user-invocable"]="true"),S.push({importPath:O,resourceType:E.resourceType,title:v,description:A.description||null,body:A.body,bodyHash:Fe(x),metadata:k})}for(let g of Qr(d)){let C=E.mainFile||`${g}.md`,O=(0,J.join)(d,g,C);if(!(0,B.existsSync)(O)){if(E.mainFile===null)for(let L of Qr((0,J.join)(d,g))){let $=`${L}.md`,M=(0,J.join)(d,g,L,$);if(!(0,B.existsSync)(M))continue;let Se=(0,B.readFileSync)(M,"utf-8"),z=st(Se),ne=z.name||ve(L),we={};z.skillClass&&(we.skillClass=z.skillClass),z.service&&(we.service=z.service),z.requires?.length&&(we.requires=z.requires),z.tools?.length&&(we.tools=z.tools),z.fields&&Object.keys(z.fields).length&&(we.fields=z.fields),S.push({importPath:`${i}/${L}`,resourceType:E.resourceType,title:ne,description:z.description||null,body:z.body,bodyHash:Fe(Se),metadata:we})}continue}let x=(0,B.readFileSync)(O,"utf-8"),A=`${i}/${g}`,v,k,R,_={},P=null;if(E.resourceType==="hook"||E.resourceType==="mcp"){try{let L=JSON.parse(x);v=L.name||ve(g),k=L.description||null}catch{v=ve(g),k=null}R=x}else if(E.resourceType==="collection"){let L=(0,J.join)(d,g,Yt,Qt);if((0,B.existsSync)(L))try{let $=JSON.parse((0,B.readFileSync)(L,"utf-8"));v=$.name||ve(g),k=$.description||null,R=x,$.resources&&Array.isArray($.resources)&&h.push({collectionImportPath:A,memberImportPaths:$.resources.map(M=>{let Se=M.split("/");return Se.length>=3?`${Se[0]}/${Se[Se.length-1]}`:M})})}catch{v=ve(g),k=null,R=x}else P=st(x),v=P.name||ve(g),k=P.description||null,R=P.body,P.arrayFields?.resources&&h.push({collectionImportPath:A,memberImportPaths:P.arrayFields.resources.map($=>{let M=$.split("/");return M.length>=3?`${M[0]}/${M[M.length-1]}`:$})})}else P=st(x),v=P.name||ve(g),k=P.description||null,R=P.body,P.skillClass&&(_.skillClass=P.skillClass),P.service&&(_.service=P.service),P.requires?.length&&(_.requires=P.requires),P.tools?.length&&(_.tools=P.tools),P.fields&&Object.keys(P.fields).length&&(_.fields=P.fields);E.folder==="commands"&&(_.fields||(_.fields={}),_.fields["user-invocable"]="true"),S.push({importPath:A,resourceType:E.resourceType,title:v,description:k,body:R,bodyHash:Fe(x),metadata:_})}}return{resources:S,memberships:h}}let a=c(r,"");t.push(...a.resources),n.push(...a.memberships);let u=new Set;e?.mcpConfigPath&&u.add(e.mcpConfigPath);let l=(0,J.join)(r,".mcp.json");(0,B.existsSync)(l)&&u.add(l);for(let f of u)if((0,B.existsSync)(f))try{let m=JSON.parse((0,B.readFileSync)(f,"utf-8"));if(m.mcpServers&&typeof m.mcpServers=="object")for(let[S,h]of Object.entries(m.mcpServers)){let E=`mcps/${S}`;if(t.some(g=>g.importPath===E))continue;let d=ve(S),i=JSON.stringify({name:d,description:`MCP server: ${S}`,mcpServers:{[S]:h}},null,2);t.push({importPath:E,resourceType:"mcp",title:d,description:`MCP server: ${S}`,body:i,bodyHash:Fe(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,B.existsSync)(e.settingsPath))try{let f=JSON.parse((0,B.readFileSync)(e.settingsPath,"utf-8"));if(f.hooks&&typeof f.hooks=="object"&&!Array.isArray(f.hooks)){let m={};for(let[S,h]of Object.entries(f.hooks))if(Array.isArray(h))for(let E of h){if(!E||typeof E!="object")continue;let d=E,i=d._sc;if(!i)continue;m[i]||(m[i]={}),m[i][S]||(m[i][S]=[]);let{_sc:g,...C}=d;m[i][S].push(C)}for(let[S,h]of Object.entries(m)){let E=S;if(t.some(C=>C.importPath===E))continue;let d=S.split("/").pop()||S,i=ve(d),g=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:h},null,2);t.push({importPath:E,resourceType:"hook",title:i,description:`Hook: ${i}`,body:g,bodyHash:Fe(g),metadata:{}})}}}catch{}for(let f of Yr){if(f.path===Zs)continue;let m=(0,J.join)(r,f.path);if((0,B.existsSync)(m)){try{let S=JSON.parse((0,B.readFileSync)(m,"utf-8"));if(s=s||S.name||void 0,o=f.formatLabel,!t.some(h=>h.resourceType==="collection")){let h=t.filter(C=>C.resourceType!=="collection").map(C=>({resourceRef:C.importPath})),E=f.converter(S,h),d=(0,J.join)(r,"README.md"),i=(0,B.existsSync)(d)?(0,B.readFileSync)(d,"utf-8"):"",g="collections/_root";t.push({importPath:g,resourceType:"collection",title:ve(E.name),description:E.description||null,body:i,bodyHash:Fe(i),metadata:{},manifestMetadata:{...E.author?{author:E.author}:{},...E.homepage?{homepage:E.homepage}:{},...E.license?{license:E.license}:{}}}),E.resources.length>0&&n.push({collectionImportPath:g,memberImportPaths:E.resources})}}catch{}break}}{let h=function(E,d,i){if(!(i>4))for(let g of Qr(E)){if(S.has(g))continue;let C=(0,J.join)(E,g),O=d?`${d}/${g}`:g;for(let x of Yr){if(x.path===Zs)continue;let A=(0,J.join)(C,x.path);if((0,B.existsSync)(A)){if(f.has(O))break;f.add(O);try{let v=JSON.parse((0,B.readFileSync)(A,"utf-8")),k=c(C,O);if(k.resources.length===0)break;t.push(...k.resources),n.push(...k.memberships);let R=k.resources.filter(M=>M.resourceType!=="collection").map(M=>({resourceRef:M.importPath})),_=x.converter(v,R),P=(0,J.join)(C,"README.md"),L=(0,B.existsSync)(P)?(0,B.readFileSync)(P,"utf-8"):"",$=`${O}/_collection`;t.push({importPath:$,resourceType:"collection",title:ve(_.name),description:_.description||null,body:L,bodyHash:Fe(L),metadata:{},manifestMetadata:{..._.author?{author:_.author}:{},..._.homepage?{homepage:_.homepage}:{},..._.license?{license:_.license}:{}}}),n.push({collectionImportPath:$,memberImportPaths:k.resources.map(M=>M.importPath)}),s||(s=v.name||void 0),o||(o=x.formatLabel)}catch{}break}}h(C,O,i+1)}};var b=h;let f=new Set,m=new Set(zs.map(E=>E.folder)),S=new Set([...m,"worktrees","plugins","node_modules","todos"]);h(r,"",0)}let p=(0,J.join)(r,"files");if((0,B.existsSync)(p)&&Ot(p)&&!t.some(f=>f.resourceType==="file"))for(let f of en(p)){if(!f.endsWith(".md"))continue;let m=(0,J.join)(p,f),S=(0,B.readFileSync)(m,"utf-8"),h=st(S),E=h.name||(0,J.basename)(f,".md"),d=`files/${(0,J.basename)(f,".md")}`;t.some(i=>i.importPath===d)||t.push({importPath:d,resourceType:"file",title:E,description:h.description||null,body:h.body,bodyHash:Fe(S),metadata:{}})}return{resources:[...t.filter(f=>f.resourceType!=="collection"),...t.filter(f=>f.resourceType==="collection")],collectionMemberships:n,pluginName:s,formatLabel:o}}async function tr(r){let{scanRoots:e,agentId:t,platformInternals:n=[".claude-plugin"],registerToProject:s=!1,skipImport:o=!1}=r,c=[],a=[],u=new Set;for(let{root:A,agent:v,isProject:k}of e){let R=er(A,{settingsPath:Ie(v,k),mcpConfigPath:pe(v,k)});for(let _ of R.resources)u.has(_.importPath)||(u.add(_.importPath),c.push({..._,scope:k?"project":"global"}));for(let _ of R.collectionMemberships)u.has(`cm:${_.collectionImportPath}`)||(u.add(`cm:${_.collectionImportPath}`),a.push(_))}let l=c.map(A=>A.importPath),p=q(),y=new Set(p.installations.map(A=>A.installPath)),b=new Map;for(let A of p.installations){let v=A.installPath.split("/"),k=v[0],R=v[v.length-1];b.has(k)||b.set(k,new Set),b.get(k).add(R)}let f=new Set(n),m=c.filter(A=>{if(y.has(A.importPath))return!1;let v=A.importPath.split("/"),k=v[0],R=v[v.length-1];return!((k==="mcps"||k==="hooks")&&b.get(k)?.has(R)||A.importPath.startsWith(".")||f.has(R)||A.importPath.startsWith("plugins/"))});for(let A of m)A.description&&A.description.length>1e3&&(A.description=A.description.slice(0,997)+"...");let S=m.length,h=m.map(A=>({importPath:A.importPath,resourceType:A.resourceType,title:A.title}));if(m.length===0||o)return{imported:[],errors:0,projectRegistered:0,untrackedCount:S,discoveredPaths:l,untracked:h};let E={dryRun:!1,onConflict:"auto",visibility:"org",resources:m,collectionMemberships:a.length>0?a:void 0},d=await F("/api/cli/import",E,12e4);if(!d.ok)return{imported:[],errors:m.length,projectRegistered:0,untrackedCount:S,discoveredPaths:l,untracked:h};let i=[...d.data.created,...d.data.updated,...d.data.installed],g=new Map;for(let A of c)g.set(A.importPath,A.scope);let C=Ee();for(let A of i){if(!A.id)continue;let v=g.get(A.importPath)||"global";le({resourceId:A.id,slug:A.slug||A.importPath.split("/").pop()||A.id,installPath:A.importPath,title:A.importPath.split("/").pop()||A.id,sha:A.commitSha||"",scope:v,agent:t,installedAt:new Date().toISOString(),resourceType:A.resourceType,serverSynced:!0,...v==="project"&&C?{projectId:C.projectId}:{}})}let O=0;if(s&&C){let A=[...i,...d.data.skipped];for(let v of A){let k=v.id||v.existingId;if(!k||g.get(v.importPath)!=="project")continue;let _=await F(`/api/cli/projects/${C.projectId}/resources`,{resourceId:k});_.ok&&_.data.added&&O++}}return{imported:i.map(A=>({resourceType:A.resourceType||A.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:A.slug||A.importPath.split("/").pop()||"",title:A.importPath.split("/").pop()||"",importPath:A.importPath,id:A.id})),errors:d.data.errors.length,projectRegistered:O,untrackedCount:S,discoveredPaths:l,untracked:[]}}var to=require("readline");function va(){if(process.platform==="darwin")try{let{execSync:r}=require("child_process"),e=r("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var ze="context-manager",Qs="Context Manager",rr="collections/shared-context/context-manager";function ka(r,e){let t=re(r,e),n=(0,Ze.join)(t,ze);return(0,ot.mkdirSync)(n,{recursive:!0}),(0,ot.writeFileSync)((0,Ze.join)(n,`${ze}.md`),qs,"utf-8"),(0,Ze.join)(n,`${ze}.md`)}var Ta={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ra(r){return q().installations.some(t=>t.installPath===rr&&t.agent===r)}function ro(r){r.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(n.code){let{post:d}=await Promise.resolve().then(()=>(oe(),ts)),{saveAuth:i}=await Promise.resolve().then(()=>(ue(),Nt)),g=await d("/api/cli/auth",{code:n.code});g.ok?(i({token:g.data.token,email:g.data.user.email,orgId:g.data.org.id,orgSlug:g.data.org.slug,orgName:g.data.org.name,createdAt:new Date().toISOString()}),I()||w(`Authenticated as ${g.data.user.email}`)):U()?I()||w("Auth code already used, continuing with saved credentials."):(I()?D("init",g.error.code,g.error.message):T(`Auth failed: ${g.error.message}`),process.exit(1))}else U()||(I()?(D("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(T("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let d=je(n.agent);if(!d){let i=`Unknown agent: ${n.agent}. Available: ${We().map(g=>g.id).join(", ")||"none detected"}`;I()?D("init","NO_AGENTS",i):T(i),process.exit(1)}s=[d]}else if(s=We(),s.length===0){let d=Ve();I()?D("init","NO_AGENTS",d):T(d),process.exit(1)}let o=_e(),c=va(),a;if(n.linkProject){if(!o?.token){let k="Authentication required for project linking. Run init with --code first.";I()?D("init","AUTH_REQUIRED",k):T(k),process.exit(1)}let d=s[0],i=await F("/api/cli/register-agent",{platform:d.platform,name:`CLI (${c})`});i.ok&&(a=i.data.connectionId);let g=await F(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});g.ok||(I()?D("init",g.error.code,g.error.message):T(`Failed to join project: ${g.error.message}`),process.exit(1));let{project:C,resources:O,members:x}=g.data;tt({projectId:C.id,projectName:C.name,projectSlug:C.slug});let A=De(d),v=[];for(let k of O)try{let R=k.installPath,_=await Z(`/api/cli/resource/${R}`);if(!_.ok)continue;let P=_.data;await A.install(P,"project",d),le({resourceId:k.id,slug:k.slug||k.id,installPath:R,title:k.title,sha:k.latestSha||"",scope:"project",agent:d.id,installedAt:new Date().toISOString(),projectId:C.id}),k.latestSha&&await F("/api/cli/install",{resourceId:k.id,agentPlatform:d.platform,installedSha:k.latestSha}).catch(()=>{}),v.push({title:k.title,resourceType:k.resourceType})}catch{}if(await F(`/api/cli/projects/${C.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Dt({lastSyncAt:new Date().toISOString()}),I())N("init",{project:{id:C.id,name:C.name,slug:C.slug},agent:d.id,resourcesInstalled:v.length,memberCount:x.length});else{if(w(""),w(`Joined project: ${C.name}`),C.description&&w(`"${C.description}"`),w(""),v.length>0){w(`Installed ${v.length} resource${v.length===1?"":"s"}:`);let k={};for(let _ of v)k[_.resourceType]||(k[_.resourceType]=[]),k[_.resourceType].push(_.title);let R={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[_,P]of Object.entries(k))w(` ${R[_]||_}: ${P.join(", ")}`)}else w("No resources to install (project is empty)");x.length>0&&(w(""),w(`Team (${x.length}): ${x.map(k=>k.name).join(", ")}`)),w(""),w("Quick reference:"),w(" shared-context-ai status View project sync status"),w(" shared-context-ai sync Check for resource updates")}return}let u=!1,l,p=(0,Ze.basename)(process.cwd()),y=Ee();if(o?.token&&!y&&p&&p!=="/")try{let d=await F("/api/cli/projects",{name:p});if(d.ok){let{id:i,name:g,slug:C}=d.data;tt({projectId:i,projectName:g,projectSlug:C}),u=!0,I()||w(`Created project: ${g}`)}else l=d.error.message,I()||T(`Project creation failed: ${l}`)}catch(d){l=d instanceof Error?d.message:String(d),I()||T(`Project creation error: ${l}`)}else y?u=!1:o?.token||(l="not authenticated");let b=[],f={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let d of s){let i=!1,g=!1,C=[],O=[];if(o?.token){let x=await F("/api/cli/register-agent",{platform:d.platform,name:`CLI (${c})`});if(x.ok){if(!a){a=x.data.connectionId;let{saveAuth:A}=await Promise.resolve().then(()=>(ue(),Nt));A({...o,connectionId:a})}}else I()||T(`Warning: Could not register ${d.label} connection: ${x.error.message}`)}if(o?.token&&Ra(d.id))g=!0,i=!0;else if(o?.token)try{let x=await Z(`/api/cli/resource/${rr}`);if(x.ok){let A=x.data,k=await De(d).install(A,n.project?"project":"user",d);if(le({resourceId:A.resource.id,slug:A.resource.slug||"context-manager",installPath:rr,title:A.resource.title,sha:A.resource.latestSha||"",scope:n.project?"project":"global",agent:d.id,installedAt:new Date().toISOString(),pluginFormat:f[d.id]||"directory",memberCount:A.memberResources?.length}),A.resource.latestSha&&await F("/api/cli/install",{resourceId:A.resource.id,agentPlatform:d.platform,installedSha:A.resource.latestSha}).catch(()=>{}),A.memberResources)for(let R of A.memberResources){let _=R.slug||R.id,P=Ta[R.resourceType]||R.resourceType+"s",L=R.orgSlug||A.resource.orgSlug,$=L?`${P}/${L}/${_}`:`${P}/${_}`;le({resourceId:R.id,slug:_,installPath:$,title:R.title,sha:R.latestSha||"",scope:n.project?"project":"global",agent:d.id,installedAt:new Date().toISOString(),collectionId:A.resource.id}),C.push({title:R.title,resourceType:R.resourceType}),R.latestSha&&await F("/api/cli/install",{resourceId:R.id,agentPlatform:d.platform,installedSha:R.latestSha}).catch(()=>{})}if(i=!0,!I()&&k.warnings.length>0)for(let R of k.warnings)T(`Warning: ${R}`)}}catch{}if(!i&&(ka(d,!!n.project),le({resourceId:"context-manager",slug:ze,installPath:`agents/${ze}`,title:Qs,sha:"",scope:n.project?"project":"global",agent:d.id,installedAt:new Date().toISOString()}),o?.token))try{let x=`agents/shared-context/${ze}`,A=await Z(`/api/cli/resource/${x}`);if(A.ok&&A.data.resource){let v=A.data.resource;v.latestSha&&await F("/api/cli/install",{resourceId:v.id,agentPlatform:d.platform,installedSha:v.latestSha}),le({resourceId:v.id,slug:v.slug||ze,installPath:`agents/shared-context/${v.slug||ze}`,title:v.title||Qs,sha:v.latestSha||"",scope:n.project?"project":"global",agent:d.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let x=[],A=(0,Ze.join)(process.cwd(),d.dir),v=(0,Ze.join)((0,eo.homedir)(),d.dir);(0,ot.existsSync)(A)&&x.push({root:A,agent:d,isProject:!0}),A!==v&&(0,ot.existsSync)(v)&&x.push({root:v,agent:d,isProject:!1}),x.length>0&&(O=(await tr({scanRoots:x,agentId:d.id,platformInternals:["context-manager",".claude-plugin"],registerToProject:!0})).imported.map(R=>({resourceType:R.resourceType,slug:R.slug,title:R.title})))}catch{}b.push({agent:d,collectionInstalled:i,installedMembers:C,importedResources:O,skippedEssentials:g})}if(Dt({lastSyncAt:new Date().toISOString()}),b.some(d=>!d.skippedEssentials)&&!I()&&process.stdin.isTTY){let{getConfig:d,updateConfig:i}=await Promise.resolve().then(()=>(ue(),Nt));if(d().telemetry===void 0)try{if(await new Promise(O=>{let x=(0,to.createInterface)({input:process.stdin,output:process.stdout});x.question(`
144
144
  Help improve Shared Context skills? We collect anonymous usage data
145
145
  (which skills you use, never conversation content). Change anytime with
146
- \`shared-context-ai config set telemetry off\`. [y/N] `,I=>{A.close(),b(I.trim().toLowerCase()==="y"||I.trim().toLowerCase()==="yes")})})){i({telemetry:!0});let{enableTelemetryHook:b}=await Promise.resolve().then(()=>(Kr(),Gs));b(),w("Telemetry enabled.")}else i({telemetry:!1}),w("Telemetry disabled.")}catch{}}if(c){let m=_.reduce((i,d)=>i+d.importedResources.length,0);$("/api/cli/sync-report",{connectionId:c,lastSyncResult:{updatesAvailable:0,importedCount:m}}).catch(()=>{})}let E=_.every(m=>m.skippedEssentials),y=_.some(m=>!m.skippedEssentials),C=_.some(m=>m.importedResources.length>0);if(x()){let m=d=>({agent:d.agent.id,collection:d.collectionInstalled?Yt:void 0,contextManagerOnly:!d.collectionInstalled,skipped:d.skippedEssentials,...d.collectionInstalled&&!d.skippedEssentials?{membersInstalled:d.installedMembers.map(S=>({title:S.title,resourceType:S.resourceType}))}:{},...d.importedResources.length>0?{importedResources:d.importedResources.map(S=>({resourceType:S.resourceType,slug:S.slug,title:S.title}))}:{}}),i=Se();N("init",{...m(_[0]),agents:_.map(m),...u?{projectCreated:!0,projectId:i?.projectId}:{},...i&&!u?{projectLinked:!0,projectId:i.projectId}:{},...a?{projectError:a}:{},authenticated:L()})}else{for(let m of _)if(!m.skippedEssentials){if(w(""),m.collectionInstalled){w(`Context Manager installed for ${m.agent.label} (${m.installedMembers.length} resources)`);let i={};for(let S of m.installedMembers)i[S.resourceType]||(i[S.resourceType]=[]),i[S.resourceType].push(S.title);let d={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};w("");for(let[S,b]of Object.entries(i)){let A=d[S]||S;w(` ${A}: ${b.join(", ")}`)}}else w(`Context Manager installed for ${m.agent.label} (offline)`),w("Context Manager agent written locally");if(m.importedResources.length>0){w(""),w(`Imported ${m.importedResources.length} existing resource${m.importedResources.length===1?"":"s"}:`);for(let i of m.importedResources)w(` ${i.resourceType.padEnd(12)} ${i.slug.padEnd(24)} ${i.title}`)}}E&&!u&&!C&&(w(""),w("Already initialized. Nothing to do.")),(y||u||C)&&(w(""),w("Quick reference:"),w(' shared-context-ai search "query" Search for resources'),w(" shared-context-ai install <installPath> Install a resource"),w(" shared-context-ai list List installed resources"),w(" shared-context-ai sync Check updates & discover resources"),w(" shared-context-ai preview <installPath> Preview before installing"))}})}var Oo=require("http"),ko=require("crypto");ce();ne();ce();re();async function vo(r){let e=await $("/api/cli/auth",{code:r});return e.ok?(Tr({token:e.data.token,email:e.data.user.email,orgId:e.data.org.id,orgSlug:e.data.org.slug,orgName:e.data.org.name,createdAt:new Date().toISOString()}),x()?N("login",{email:e.data.user.email,org:e.data.org.slug}):w(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(x()?D("login",e.error.code,e.error.message):T(`Login failed: ${e.error.message}`),!1)}async function Ma(){let r=(0,ko.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,Oo.createServer)((n,s)=>{let o=new URL(n.url||"/","http://localhost"),l=o.searchParams.get("code"),c=o.searchParams.get("state");if(!l||c!==r){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),vo(l).then(e)});t.listen(0,"127.0.0.1",async()=>{let n=t.address();if(!n||typeof n=="string"){t.close(),e(!1);return}let s=n.port,l=`${Ie().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${r}`;x()||(w("Opening browser for authentication..."),w(`If the browser doesn't open, visit: ${l}`));try{let c=(await Promise.resolve().then(()=>(xo(),_o))).default;await c(l)}catch{x()||w(`Could not open browser. Please visit:
147
- ${l}`)}setTimeout(()=>{t.close(),x()||T("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function To(r){r.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await vo(e.code):t=await Ma(),process.exit(t?0:1)})}ne();re();var Ua={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ro(r){let e=Ua[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${e}/external/${r.githubOwner}/${r.slug}`:r.orgSlug?`${e}/${r.orgSlug}/${r.slug}`:`${e}/${r.slug}`}function Po(r){r.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let n=new URLSearchParams({q:e});t.type&&n.set("type",t.type),t.tag&&n.set("tag",t.tag),t.limit&&n.set("limit",t.limit);let s=L()?`/api/cli/search?${n}`:`/api/public/search?${n}`,o=await G(s);o.ok||(x()?D("search",o.error.code,o.error.message):w(`Search failed: ${o.error.message}`),process.exit(1));let l=o.data.results;if(x()){let u=l.map(a=>{let p=Ro(a);return{installPath:p,installCommand:`npx shared-context-ai install ${p}`,title:a.title,description:a.description,resourceType:a.resourceType,installCount:a.installCount,topicTags:a.topicTags}});N("search",{results:u,count:u.length});return}if(l.length===0){let u=t.type?`${t.type}s`:"results";w(`No ${u} found.`);return}w(`Found ${l.length} result${l.length===1?"":"s"}:
148
- `);let c=l.map(u=>[Ro(u),u.title,`\u2193${u.installCount}`]);w(he(c)),w(`
149
- Install a skill: npx shared-context-ai install <installPath>`)})}ne();ce();re();function jo(r){let e=r.slug||r.resourceId;return r.storageType==="github"&&r.githubOwner?`skills/external/${r.githubOwner}/${e}`:r.orgSlug?`skills/${r.orgSlug}/${e}`:`skills/${e}`}function Do(r){r.command("list").description("List installed skills").alias("ls").action(async()=>{if(L()){let e=await G("/api/cli/installed");e.ok||(x()?D("list",e.error.code,e.error.message):w(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(x()){let s=t.map(o=>({...o,installPath:jo(o)}));N("list",{installations:s,count:s.length});return}if(t.length===0){w("No skills installed."),w("Use 'shared-context-ai search' to find skills to install.");return}w(`${t.length} skill${t.length===1?"":"s"} installed:
150
- `);let n=t.map(s=>[jo(s),s.title,s.hasUpdate?"(update available)":"(current)"]);w(he(n))}else{let t=V().installations;if(x()){N("list",{installations:t,count:t.length});return}if(t.length===0){w("No skills installed locally.");return}w(`${t.length} skill${t.length===1?"":"s"} installed locally:
151
- `);let n=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);w(he(n)),w(`
152
- Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}ne();re();function No(r){r.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let n=L()?"/api/cli/resource":"/api/public/resource",s=await G(`${n}/${e}/preview`);s.ok||(x()?D("preview",s.error.code,s.error.message):T(`Preview failed: ${s.error.message}`),process.exit(1)),x()?N("preview",s.data):w(s.data.content)})}ne();re();function $o(r){r.command("check").description("Check for skill updates").action(async()=>{L()||(x()?D("check","AUTH_MISSING","Login required to check for updates."):T("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await G("/api/cli/updates");e.ok||(x()?D("check",e.error.code,e.error.message):T(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:n}=e.data;if(x()){N("check",{updates:t,count:n});return}if(n===0){w("All skills are up to date.");return}w(`${n} update${n===1?"":"s"} available:
153
- `);let s=t.map(o=>{let l=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${l}`:o.orgSlug?`skills/${o.orgSlug}/${l}`:`skills/${l}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});w(he(s)),w(`
154
- Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var st=require("path"),sr=require("fs"),Fo=require("child_process");ne();ce();re();var Mo={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Lo(r){let e=r.slug||r.resourceId;return`${Mo[r.resourceType]||r.resourceType+"s"}/${e}`}function Uo(r){r.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,n)=>{let s=n.optsWithGlobals();L()||(x()?D("update","AUTH_MISSING","Login required to update resources."):T("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=ve(s.agent);if(!o){let a=Me();x()?D("update","NO_AGENTS",a):T(a),process.exit(1)}let l=await G("/api/cli/updates");l.ok||(x()?D("update",l.error.code,l.error.message):T(`Failed to check updates: ${l.error.message}`),process.exit(1));let c=l.data.updates;if(e&&(c=c.filter(a=>Lo(a)===e||a.slug===e||a.resourceId===e),c.length===0)){x()?D("update","SKILL_NOT_FOUND",`No update available for "${e}".`):w(`No update available for "${e}".`);return}if(c.length===0){x()?N("update",{updated:[],count:0}):w("All resources are up to date.");return}let u=[];for(let a of c){let g=V().installations.find(C=>C.resourceId===a.resourceId&&C.agent===o.id),_;if(g?.installPath){let C=g.installPath.split("/");C[C.length-1]=a.slug||a.resourceId,_=C.join("/")}else _=Lo(a);if(g?.installMode==="plugin"&&a.resourceType==="collection"){try{let C=a.orgSlug||"",m=a.slug||a.resourceId,i=Ft(o.id),d=`/api/cli/resource/collections/${C}/${m}?format=plugin&platform=${i}`,S=await Lt(d,m),b=ut(o.id);b&&(0,Fo.execSync)(`${b} plugin install "${S}"`,{stdio:"pipe"}),a.latestSha&&await $("/api/cli/update",{resourceId:a.resourceId,installedSha:a.latestSha}),ae({...g,sha:a.latestSha,installedAt:new Date().toISOString()}),u.push({installPath:_,title:a.title}),x()||w(` Updated plugin: ${_}`)}catch(C){x()||T(` Plugin update failed for ${_}: ${C}`)}continue}let f=await G(`/api/cli/resource/${_}`);if(!f.ok){x()||T(` Failed to fetch ${_}: ${f.error.message}`);continue}let h=f.data,E=_.split("/").slice(1);if(h.resource.resourceType==="agent"){let C=te(o,!!s.project),m=(0,st.join)(C,...E);q(m,h.files)}else if(h.resource.resourceType==="mcp")Ut(o,!!s.project,h);else{let C=H(o,!!s.project),m=(0,st.join)(C,...E);q(m,h.files)}if(g&&g.installPath&&g.installPath!==_){let C=g.installPath.split("/").slice(1),m;h.resource.resourceType==="agent"?m=(0,st.join)(te(o,!!s.project),...C):h.resource.resourceType!=="mcp"&&(m=(0,st.join)(H(o,!!s.project),...C)),m&&(0,sr.existsSync)(m)&&((0,sr.rmSync)(m,{recursive:!0}),x()||w(` Removed old path: ${g.installPath}`))}let y=a.latestSha||h.resource.latestSha;if(y&&await $("/api/cli/update",{resourceId:a.resourceId,installedSha:y}),ae({...g||{},resourceId:a.resourceId,slug:a.slug||a.resourceId,installPath:_,title:h.resource.title,sha:y||"",scope:g?.scope||(s.project?"project":"global"),agent:o.id,installedAt:new Date().toISOString(),latestSha:y||void 0,resourceType:a.resourceType||h.resource.resourceType,serverSynced:!0}),u.push({installPath:_,title:h.resource.title}),x()||w(` Updated ${_}`),h.resource.resourceType==="collection"&&h.memberResources&&g?.installMode!=="plugin"){let C=V(),m=new Set(C.installations.map(i=>i.resourceId));for(let i of h.memberResources){if(m.has(i.id))continue;let d=i.slug||i.id,S=Mo[i.resourceType]||i.resourceType+"s",b=a.orgSlug?`${a.orgSlug}/`:"",A=`${S}/${b}${d}`,I=await G(`/api/cli/resource/${A}`);if(!I.ok){x()||T(` Failed to fetch new member ${A}: ${I.error.message}`);continue}let O=I.data,k=A.split("/").slice(1);if(O.resource.resourceType==="agent"){let v=te(o,!!s.project);q((0,st.join)(v,...k),O.files)}else if(O.resource.resourceType==="mcp")Ut(o,!!s.project,O);else{let v=H(o,!!s.project);q((0,st.join)(v,...k),O.files)}i.latestSha&&await $("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{}),ae({resourceId:i.id,slug:d,installPath:A,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:h.resource.id,resourceType:i.resourceType,serverSynced:!0}),x()||w(` + New member: ${A}`)}}}u.length>0&&$e(),x()?N("update",{updated:u,count:u.length}):u.length>0&&w(`
155
- ${u.length} resource${u.length===1?"":"s"} updated.`)})}var se=require("fs"),ht=require("path"),Ho=require("child_process");ne();ce();re();function Bo(r){r.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{if(!e){let h=V().installations;if(h.length===0&&(x()?D("uninstall","NOTHING_INSTALLED","No resources installed."):w("No resources installed."),process.exit(0)),x())N("uninstall",{installations:h.map(E=>({path:E.installPath||E.slug,title:E.title,agent:E.agent}))});else{w(`Installed resources:
156
- `);let E=h.map(y=>[y.installPath||y.slug,y.title||"",`(${y.agent})`]);w(he(E)),w(`
157
- Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=ve(s.agent);if(!o){let f=Me();x()?D("uninstall","NO_AGENTS",f):T(f),process.exit(1)}let c=V().installations.find(f=>f.installPath===e||f.slug===e||f.resourceId===e),u=e.split("/"),p=["skills","files","commands","hooks","collections","agents","mcps"].includes(u[0])?u[0]:null,g=p?u.slice(1):u,_=!1;if(p==="collections")if(c?.installMode==="plugin"){let f=ut(o.id);if(f)try{(0,Ho.execSync)(`${f} plugin uninstall "${c.slug}"`,{stdio:"pipe"}),x()||w(`Uninstalled native ${f} plugin: ${c.slug}`)}catch(h){x()||T(`Native uninstall failed: ${h}. Removing tracking only.`)}wt(c.resourceId,o.id),L()&&await $("/api/cli/uninstall",{resourceId:c.resourceId,agentPlatform:o.platform}).catch(()=>{}),$e(),x()?N("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`);return}else{let f=Te(o),h=g[g.length-1],E=s.project?"project":"user",y=await f.uninstall(h,E,o,c?.resourceId);if(_=y.removed,!x())for(let C of y.warnings)T(`Warning: ${C}`);if(c){let m=V().installations.filter(i=>i.collectionId===c.resourceId&&i.agent===o.id);for(let i of m){let d=i.installPath.split("/"),S=d[0],b=d.slice(1);if(S==="agents"){let A=te(o,!!s.project),I=(0,ht.join)(A,...b);(0,se.existsSync)(I)&&(0,se.rmSync)(I,{recursive:!0,force:!0})}else if(S==="mcps"){let A=b[b.length-1],I=fe(o,!!s.project);if((0,se.existsSync)(I))try{let O=JSON.parse((0,se.readFileSync)(I,"utf-8"));if(typeof O.mcpServers=="object"&&O.mcpServers&&!Array.isArray(O.mcpServers)){let k=O.mcpServers;A in k&&(delete k[A],O.mcpServers=k,(0,se.writeFileSync)(I,JSON.stringify(O,null,2)+`
158
- `,"utf-8"))}}catch{}}else if(S==="hooks")Vr(we(o,!!s.project),i.installPath);else{let A=H(o,!!s.project),I=(0,ht.join)(A,...b);(0,se.existsSync)(I)&&(0,se.rmSync)(I,{recursive:!0,force:!0})}wt(i.resourceId,o.id)}}}else if(p==="agents"){let f=te(o,!!s.project),h=(0,ht.join)(f,...g);_=(0,se.existsSync)(h),_&&(0,se.rmSync)(h,{recursive:!0,force:!0})}else if(p==="mcps"){let f=g[g.length-1],h=fe(o,!!s.project);if((0,se.existsSync)(h))try{let E=JSON.parse((0,se.readFileSync)(h,"utf-8"));if(typeof E.mcpServers=="object"&&E.mcpServers&&!Array.isArray(E.mcpServers)){let y=E.mcpServers;f in y&&(delete y[f],E.mcpServers=y,(0,se.writeFileSync)(h,JSON.stringify(E,null,2)+`
159
- `,"utf-8"),_=!0)}}catch{}}else if(p==="hooks"){let f=we(o,!!s.project);_=Vr(f,e),!_&&!x()&&T(`Note: No tagged hook entries found in ${f} \u2014 may need manual removal if installed before v0.1.10`)}else{let f=H(o,!!s.project),h=(0,ht.join)(f,...g);if(_=(0,se.existsSync)(h),_&&(0,se.rmSync)(h,{recursive:!0,force:!0}),!_&&c?.slug){let E=(0,ht.join)(f,c.slug);(0,se.existsSync)(E)&&(0,se.rmSync)(E,{recursive:!0,force:!0})}}if(L()&&c){let f=await $("/api/cli/uninstall",{resourceId:c.resourceId});!f.ok&&!x()&&T(`Warning: Could not record uninstall on server: ${f.error.message}`)}c&&wt(c.resourceId,o.id),$e(),x()?N("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`)})}ce();ne();re();function Wo(r){r.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=Ae(),t=Ie(),n=V(),s=Fe(),o=Se(),l=n.installations.filter(g=>!g.projectId),c=n.installations.filter(g=>g.projectId),u=new Map;for(let g of c){let _=g.projectId;u.has(_)||u.set(_,[]),u.get(_).push(g)}let a=[];if(L()&&u.size>0)for(let[g,_]of u){let f=await G(`/api/cli/projects/${g}/resources`).catch(()=>null),h=f&&f.ok?f.data.resources.length:_.length,E=o?.projectId===g?o.projectName:`Project ${g.slice(0,8)}`;a.push({projectId:g,projectName:E,localCount:_.length,serverCount:h,synced:_.length>=h})}let p={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(g=>g.id),installedCount:n.installations.length,globalCount:l.length,projects:a};if(x()){N("status",p);return}if(w("Shared Context CLI Status"),w("\u2500".repeat(40)),e?.token?w(` Auth: ${e.email} (${e.orgSlug})`):w(" Auth: Not logged in"),w(` API: ${t.apiBase}`),s.length>0?w(` Agents: ${s.map(g=>g.label).join(", ")}`):w(" Agents: None detected"),w(` Global: ${l.length} resource${l.length===1?"":"s"} installed`),a.length>0){w(""),w("Projects:");for(let g of a){let _=g.synced?"\u2713 synced":`\u26A0 ${g.serverCount-g.localCount} new`;w(` ${g.projectName}: ${g.localCount}/${g.serverCount} resources (${_})`)}}else o&&(w(""),w(` Project: ${o.projectName} (linked)`))})}ce();ne();re();function Vo(r){r.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=Ae();e.revoke&&L()&&await Dr("/api/cli/auth"),Rr(),x()?N("logout",{email:t?.email||null}):w("Logged out.")})}var or=require("fs"),qo=require("path");ne();re();function Go(r){r.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=t.github;if(o&&e&&(x()?D("import","INVALID_ARGS","Cannot use --github with a local path"):T("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(x()?D("import","INVALID_ARGS","Provide a local path or --github <url>"):T("Error: Provide a local path or --github <url>"),process.exit(1)),L()||(x()?D("import","AUTH_MISSING","Authentication required for import"):T("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(x()?D("import","INVALID_ARGS","--on-conflict is not supported with --github"):T("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(x()?D("import","INVALID_ARGS","--dry-run is not supported with --github"):T("Error: --dry-run is not supported with --github"),process.exit(1));let h={url:o};t.resourceType&&(h.resourceType=t.resourceType),x()||w(`
160
- Importing from GitHub: ${o}`);let E=await $("/api/cli/github-import",h);E.ok||(x()?D("import",E.error.code,E.error.message):T(`
161
- Import failed: ${E.error.message}`),process.exit(1));let y=E.data;if(x()){N("import",y);return}w(""),w(` Source: ${y.source.owner}/${y.source.repo}`),w(` Type: ${y.resourceType}`),w(` Title: ${y.title}`),y.slug&&w(` Slug: ${y.slug}`),w(` URL: ${y.url}`),w(""),w("Import complete: 1 created");return}let l=(0,qo.resolve)(e);(!(0,or.existsSync)(l)||!(0,or.statSync)(l).isDirectory())&&(x()?D("import","INVALID_PATH",`Not a directory: ${l}`):T(`Error: Not a directory: ${l}`),process.exit(1));let c=Kt(l);if(c.resources.length===0){x()?N("import",{resources:[],message:"No resources found"}):w("No resources found in the specified directory.");return}if(!x()){let h=new Map;for(let y of c.resources)h.set(y.resourceType,(h.get(y.resourceType)||0)+1);let E=[...h.entries()].map(([y,C])=>`${C} ${y}${C===1?"":"s"}`).join(", ");w(`
162
- Discovered ${c.resources.length} resources in ${e}:`),w(` ${E}`),c.formatLabel&&c.pluginName?w(` ${c.formatLabel}: ${c.pluginName}`):c.pluginName&&w(` Plugin: ${c.pluginName}`)}let u=t.tags?t.tags.split(",").map(h=>h.trim()).filter(Boolean):void 0,a={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:u,resources:c.resources,collectionMemberships:c.collectionMemberships.length>0?c.collectionMemberships:void 0};!x()&&!t.dryRun?w(`
163
- Executing import...`):x()||w(`
164
- Dry run \u2014 previewing changes...`);let p=await $("/api/cli/import",a,12e4);p.ok||(x()?D("import",p.error.code,p.error.message):T(`
165
- Import failed: ${p.error.message}`),process.exit(1));let g=p.data;if(x()){N("import",g);return}let _=[...g.created.map(h=>({...h,action:"created"})),...g.updated.map(h=>({...h,action:"updated"})),...g.installed.map(h=>({...h,action:"installed"})),...g.cloned.map(h=>({...h,action:"cloned"})),...g.skipped.map(h=>({...h,action:"skipped"})),...g.errors.map(h=>({...h,action:"error"}))];if(_.length>0){w("");let h=_.length,E=_.map((y,C)=>{let m=`[${String(C+1).padStart(String(h).length)}/${h}]`,i=(y.resourceType||"").padEnd(10),d=(y.importPath.split("/").pop()||"").padEnd(24),S="";switch(y.action){case"created":S=`\u2713 created${y.slug?` (slug: ${y.slug})`:""}`;break;case"updated":S="\u2713 updated";break;case"installed":{let b=y.versionsBehind;S=`\u2713 installed${b?` (${b} versions behind)`:""}`;break}case"cloned":S=`\u2713 cloned${y.slug?` (slug: ${y.slug})`:""}`;break;case"skipped":S=`\u2713 skipped (${y.reason||"up to date"})`;break;case"error":S=`\u2717 error: ${y.error||"unknown"}`;break}return` ${m} ${i} ${d} ${S}`});for(let y of E)w(y)}if(g.collections.length>0)for(let h of g.collections){let E=h.importPath.split("/").pop()||h.importPath;w(` collection ${E.padEnd(20)} \u2713 ${h.membersLinked} members linked${h.membersFailed>0?`, ${h.membersFailed} failed`:""}`)}w("");let f=[g.created.length>0?`${g.created.length} created`:null,g.installed.length>0?`${g.installed.length} installed`:null,g.cloned.length>0?`${g.cloned.length} cloned`:null,g.updated.length>0?`${g.updated.length} updated`:null,g.skipped.length>0?`${g.skipped.length} skipped`:null,g.errors.length>0?`${g.errors.length} errors`:null].filter(Boolean);t.dryRun?w(`Dry run complete: ${f.join(", ")}`):w(`Import complete: ${f.join(", ")}`),g.errors.length>0&&process.exit(1)})}var An=require("path"),Ko=require("os");ne();ce();re();var Ga={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function za(r){let e=r.slug||r.resourceId;return`${Ga[r.resourceType]||r.resourceType+"s"}/${e}`}function Xo(r){r.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(!n.force&&!jr()){let b=V(),A=b.installations.filter(k=>k.latestSha&&k.sha&&k.latestSha!==k.sha),I=b.lastSyncAt?Math.floor((Date.now()-new Date(b.lastSyncAt).getTime())/6e4):void 0,O={updatesAvailable:A.length,untrackedResources:0,driftRepairs:0,updates:A.map(k=>({installPath:k.installPath,title:k.title,sha:k.sha,latestSha:k.latestSha})),untracked:[],summary:wn(A.length,0)+(I!==void 0?` (cached ${I}m ago, run --force to refresh)`:""),throttled:!0,cacheAge:I};bn(O,!!n.quiet);return}L()||(x()?D("sync","AUTH_MISSING","Login required to sync."):T("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=ve(n.agent),o=await G("/api/cli/installed");if(!o.ok){let A=V().installations.filter(O=>O.latestSha&&O.sha&&O.latestSha!==O.sha);!x()&&!n.quiet&&T(`Warning: Could not reach server (${o.error.message}). Showing cached state.`);let I={updatesAvailable:A.length,untrackedResources:0,driftRepairs:0,updates:A.map(O=>({installPath:O.installPath,title:O.title,sha:O.sha,latestSha:O.latestSha})),untracked:[],summary:wn(A.length,0)+" (offline)",throttled:!1};bn(I,!!n.quiet);return}let l=o.data.installations,c=new Map(l.map(b=>[b.resourceId,b])),u=V(),a=0;for(let b of u.installations){let A=c.get(b.resourceId);if(A)b.latestSha=A.latestSha||void 0,b.resourceType=b.resourceType||A.resourceType,b.serverSynced=!0,A.installedSha&&b.sha&&A.installedSha!==b.sha&&(!x()&&!n.quiet&&w(` Drift repaired: ${b.installPath} (local=${b.sha.slice(0,7)} \u2192 server=${A.installedSha.slice(0,7)})`),b.sha=A.installedSha,a++),c.delete(b.resourceId);else if(b.serverSynced!==!1){let I=await $("/api/cli/install",{resourceId:b.resourceId,agentPlatform:s?.platform||"claude_code",installedSha:b.sha});I.ok?b.serverSynced=!0:(I.error.code==="NOT_FOUND"||I.error.code==="RESOURCE_NOT_FOUND")&&(b.serverSynced=!1,b.resourceId="",a++)}}u.installations=u.installations.filter(b=>b.resourceId!=="");let p=Array.from(c.values());if(p.length>0&&!x()&&!n.quiet){w(`
166
- ${p.length} resource${p.length===1?"":"s"} installed elsewhere (web/other machine):`);for(let b of p.slice(0,5))w(` ${za(b)} \u2014 ${b.title}`);p.length>5&&w(` ...and ${p.length-5} more`)}Ne(u);let g=s?[s]:Fe();g.length===0&&!x()&&!n.quiet&&T("No AI agents detected \u2014 resource discovery skipped. Use --agent to specify one.");let _=g.map(b=>({root:n.project?(0,An.join)(process.cwd(),b.dir):(0,An.join)((0,Ko.homedir)(),b.dir),agent:b,isProject:!!n.project})),f={imported:[],errors:0,projectRegistered:0,untrackedCount:0,discoveredPaths:[],untracked:[]};if(_.length>0){if(f=await Xt({scanRoots:_,agentId:s?.id||g[0]?.id||"unknown",registerToProject:!!n.project,skipImport:n.import===!1}),f.imported.length>0&&!x()&&!n.quiet){w(`
167
- Imported ${f.imported.length} resource${f.imported.length===1?"":"s"}:`);let b=f.imported.map(A=>[` ${(A.resourceType||"").padEnd(12)}`,(A.slug||A.importPath.split("/").pop()||"").padEnd(24),A.importPath]);w(he(b))}if(f.errors>0&&!x()&&T(`
168
- ${f.errors} import error(s)`),f.projectRegistered>0&&!x()&&!n.quiet){let b=Se();w(`
169
- Project "${b?.projectName}": registered ${f.projectRegistered} resource${f.projectRegistered===1?"":"s"}`)}}let h=f.untrackedCount,E=Se(),y=0;if(E){let b=await G(`/api/cli/projects/${E.projectId}/resources`);if(!b.ok)!x()&&!n.quiet&&(T(`Warning: Project "${E.projectName}" not found on server (may have been deleted).`),T(" Remove .shared-context/project.json to unlink this directory."));else{let A=b.data.project;A&&(A.name!==E.projectName||A.slug!==E.projectSlug)&&Ye({projectId:E.projectId,projectName:A.name,projectSlug:A.slug});let I=b.data.resources,O=u.installations.filter(P=>P.projectId===E.projectId),k=new Set(O.map(P=>P.resourceId)),v=I.filter(P=>!k.has(P.id));if(v.length>0)if(!s)!x()&&!n.quiet&&T(`
170
- Project "${E.projectName}" has ${v.length} new resource${v.length===1?"":"s"} \u2014 use --agent to install them.`);else{let P=Te(s);for(let j of v){let U=j.installPath;try{let W=await G(`/api/cli/resource/${U}`);if(!W.ok)continue;await P.install(W.data,"project",s),ae({resourceId:j.id,slug:j.slug||j.id,installPath:U,title:j.title,sha:j.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:E.projectId,resourceType:j.resourceType,serverSynced:!0}),j.latestSha&&await $("/api/cli/install",{resourceId:j.id,agentPlatform:s.platform,installedSha:j.latestSha}).catch(()=>{}),y++}catch{}}!x()&&!n.quiet&&y>0&&w(`
171
- Project "${E.projectName}": installed ${y} new resource${y===1?"":"s"}`)}if(n.project){let P=new Set(I.map(W=>W.id)),j=new Set(f.discoveredPaths),U=0;for(let W of u.installations){if(P.has(W.resourceId)||!j.has(W.installPath))continue;(await $(`/api/cli/projects/${E.projectId}/resources`,{resourceId:W.resourceId})).ok&&(W.projectId=E.projectId,U++)}U>0&&!x()&&!n.quiet&&w(`
172
- Project "${E.projectName}": registered ${U} existing resource${U===1?"":"s"}`)}await $(`/api/cli/projects/${E.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let C=f.imported.length;if(n.force){let b=u.lastSyncAt;u.lastSyncAt=b||new Date().toISOString()}else u.lastSyncAt=new Date().toISOString();Ne(u);let m=u.installations.filter(b=>b.latestSha&&b.sha&&b.latestSha!==b.sha),i=Ae();i?.connectionId&&$("/api/cli/sync-report",{connectionId:i.connectionId,lastSyncResult:{updatesAvailable:m.length,importedCount:C}}).catch(()=>{});try{let{pushTelemetry:b}=await Promise.resolve().then(()=>(Cn(),Jo));await b(!0)}catch{}let d=f.untracked,S={updatesAvailable:m.length,untrackedResources:d.length,driftRepairs:a,updates:m.map(b=>({installPath:b.installPath,title:b.title,sha:b.sha,latestSha:b.latestSha})),untracked:d,summary:wn(m.length,d.length,a),throttled:!1};bn(S,!!n.quiet)})}function wn(r,e,t=0){let n=[];return r>0&&n.push(`${r} update${r===1?"":"s"} available`),e>0&&n.push(`${e} untracked resource${e===1?"":"s"}`),t>0&&n.push(`${t} drift repair${t===1?"":"s"}`),n.length===0?"Everything is up to date.":n.join(", ")}function bn(r,e){if(x()){N("sync",r);return}if(e){let t=r.summary;r.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),r.untrackedResources>0&&(t+=` \u2014 ${r.untrackedResources} untracked`),w(t);return}if(w(""),r.updates.length>0){w(`${r.updates.length} update${r.updates.length===1?"":"s"} available:
173
- `);let t=r.updates.map(n=>[` ${n.installPath}`,n.title,`${n.sha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]);w(he(t)),w("")}if(r.untracked.length>0){w(`${r.untracked.length} untracked resource${r.untracked.length===1?"":"s"}:
174
- `);let t=r.untracked.map(n=>[` ${n.resourceType.padEnd(12)}`,n.importPath.padEnd(30),n.title]);w(he(t)),w("")}r.updatesAvailable===0&&r.untrackedResources===0?w("Everything is up to date."):(r.updatesAvailable>0&&w("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&w("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),w("")}var Yo=require("path");ne();ne();re();function Qo(r){r.command("project").description("Manage projects").command("create").description("Create a project for the current folder").argument("[name]","Project name (defaults to folder name)").action(async t=>{if(!L()){let a="Not authenticated. Run 'shared-context-ai login' first.";x()?D("project create","AUTH_MISSING",a):T(a),process.exit(1)}let n=Se();if(n){x()?N("project create",{alreadyExists:!0,project:{id:n.projectId,name:n.projectName,slug:n.projectSlug}}):w(`Project already linked: ${n.projectName}`);return}let s=t?.trim()||(0,Yo.basename)(process.cwd());if(!s||s==="/"){let a='Could not determine project name. Provide one: shared-context-ai project create "My Project"';x()?D("project create","INVALID_NAME",a):T(a),process.exit(1)}let o=await $("/api/cli/projects",{name:s});o.ok||(x()?D("project create",o.error.code,o.error.message):T(`Failed to create project: ${o.error.message}`),process.exit(1));let{id:l,name:c,slug:u}=o.data;Ye({projectId:l,projectName:c,projectSlug:u}),x()?N("project create",{id:l,name:c,slug:u}):(w(`Created project: ${c}`),w(""),w("Quick reference:"),w(" shared-context-ai install <installPath> Add a resource to this project"),w(" shared-context-ai sync Check for resource updates"),w(" shared-context-ai status View project sync status"))})}Cn();var cr=require("fs"),ar=require("path"),In=require("os");re();function Za(){let r=process.env.SC_PROFILE;return r?(0,ar.join)((0,In.homedir)(),".config","shared-context","profiles",r):(0,ar.join)((0,In.homedir)(),".config","shared-context")}function Ja(){let r=(0,ar.join)(Za(),"usage.jsonl");if(!(0,cr.existsSync)(r))return[];try{let e=(0,cr.readFileSync)(r,"utf8").trim().split(`
175
- `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function ei(r){r.command("stats").description("Show local usage statistics").option("--days <n>","Number of days to show","7").action(e=>{let t=parseInt(e.days,10)||7,n=new Date;n.setDate(n.getDate()-t);let o=Ja().filter(u=>new Date(u.ts)>=n);if(o.length===0){x()?N("stats",{days:t,events:0,skills:[],agents:[]}):w("No usage data yet");return}let l=new Map,c=new Map;for(let u of o)if(u.event==="skill_invoked"){let a=l.get(u.slug)||{count:0,ok:0};a.count++,u.ok&&a.ok++,l.set(u.slug,a)}else if(u.event==="agent_invoked"){let a=c.get(u.slug)||{count:0,ok:0,totalMs:0,totalTokens:0};a.count++,u.ok&&a.ok++,u.dur_ms&&(a.totalMs+=u.dur_ms),u.tokens&&(a.totalTokens+=u.tokens),c.set(u.slug,a)}if(x()){N("stats",{days:t,events:o.length,skills:[...l.entries()].map(([u,a])=>({slug:u,...a})),agents:[...c.entries()].map(([u,a])=>({slug:u,...a,avgMs:a.count>0?Math.round(a.totalMs/a.count):0,avgTokens:a.count>0?Math.round(a.totalTokens/a.count):0}))});return}if(w(`Usage over the last ${t} day${t===1?"":"s"} (${o.length} event${o.length===1?"":"s"})
176
- `),l.size>0){w("Skills:");let u=[...l.entries()].sort((a,p)=>p[1].count-a[1].count).map(([a,p])=>[` ${a}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`]);w(he(u))}if(c.size>0){l.size>0&&w(""),w("Agents:");let u=[...c.entries()].sort((a,p)=>p[1].count-a[1].count).map(([a,p])=>{let g=p.count>0?Math.round(p.totalMs/p.count):0;return[` ${a}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`,g>0?`avg ${(g/1e3).toFixed(1)}s`:""]});w(he(u))}})}Kr();var ti={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."},lr=class extends Error{constructor(t,n){super(n||ti[t]);this.code=t;this.name="CliError"}get recovery(){return ti[this.code]}};re();var ie=new Fn;ie.name("shared-context-ai").description("CLI for Shared Context - search, install, and manage AI skills").version("0.1.0").option("--json","Output as JSON (default when piped)").option("--human","Output as human-readable text (default in TTY)").option("--agent <name>","Override agent detection").option("--project","Use project-local directory instead of global").hook("preAction",r=>{let e=r.opts();Hn(!!e.json,!!e.human)});Ks(ie);To(ie);Po(ie);Fs(ie);Do(ie);No(ie);$o(ie);Uo(ie);Bo(ie);Wo(ie);Vo(ie);Go(ie);Xo(ie);Qo(ie);En(ie);ei(ie);Jr(ie);process.on("uncaughtException",r=>{r instanceof lr?x()?D(process.argv[2]||"unknown",r.code,r.message):(T(`Error: ${r.message}`),T(r.recovery)):x()?D(process.argv[2]||"unknown","UNEXPECTED",r.message||"Unexpected error"):T(`Error: ${r.message||r}`),process.exit(1)});ie.parse();
146
+ \`shared-context-ai config set telemetry off\`. [y/N] `,A=>{x.close(),O(A.trim().toLowerCase()==="y"||A.trim().toLowerCase()==="yes")})})){i({telemetry:!0});let{enableTelemetryHook:O}=await Promise.resolve().then(()=>(nn(),Ys));O(),w("Telemetry enabled.")}else i({telemetry:!1}),w("Telemetry disabled.")}catch{}}if(a){let d=b.reduce((i,g)=>i+g.importedResources.length,0);F("/api/cli/sync-report",{connectionId:a,lastSyncResult:{updatesAvailable:0,importedCount:d}}).catch(()=>{})}let S=b.every(d=>d.skippedEssentials),h=b.some(d=>!d.skippedEssentials),E=b.some(d=>d.importedResources.length>0);if(I()){let d=g=>({agent:g.agent.id,collection:g.collectionInstalled?rr:void 0,contextManagerOnly:!g.collectionInstalled,skipped:g.skippedEssentials,...g.collectionInstalled&&!g.skippedEssentials?{membersInstalled:g.installedMembers.map(C=>({title:C.title,resourceType:C.resourceType}))}:{},...g.importedResources.length>0?{importedResources:g.importedResources.map(C=>({resourceType:C.resourceType,slug:C.slug,title:C.title}))}:{}}),i=Ee();N("init",{...d(b[0]),agents:b.map(d),...u?{projectCreated:!0,projectId:i?.projectId}:{},...i&&!u?{projectLinked:!0,projectId:i.projectId}:{},...l?{projectError:l}:{},authenticated:U()})}else{for(let d of b)if(!d.skippedEssentials){if(w(""),d.collectionInstalled){w(`Context Manager installed for ${d.agent.label} (${d.installedMembers.length} resources)`);let i={};for(let C of d.installedMembers)i[C.resourceType]||(i[C.resourceType]=[]),i[C.resourceType].push(C.title);let g={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};w("");for(let[C,O]of Object.entries(i)){let x=g[C]||C;w(` ${x}: ${O.join(", ")}`)}}else w(`Context Manager installed for ${d.agent.label} (offline)`),w("Context Manager agent written locally");if(d.importedResources.length>0){w(""),w(`Imported ${d.importedResources.length} existing resource${d.importedResources.length===1?"":"s"}:`);for(let i of d.importedResources)w(` ${i.resourceType.padEnd(12)} ${i.slug.padEnd(24)} ${i.title}`)}}S&&!u&&!E&&(w(""),w("Already initialized. Nothing to do.")),(h||u||E)&&(w(""),w("Quick reference:"),w(' shared-context-ai search "query" Search for resources'),w(" shared-context-ai install <installPath> Install a resource"),w(" shared-context-ai list List installed resources"),w(" shared-context-ai sync Check updates & discover resources"),w(" shared-context-ai preview <installPath> Preview before installing"))}})}var jo=require("http"),Do=require("crypto");ue();oe();ue();se();async function No(r){let e=await F("/api/cli/auth",{code:r});return e.ok?(Dr({token:e.data.token,email:e.data.user.email,orgId:e.data.org.id,orgSlug:e.data.org.slug,orgName:e.data.org.name,createdAt:new Date().toISOString()}),I()?N("login",{email:e.data.user.email,org:e.data.org.slug}):w(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(I()?D("login",e.error.code,e.error.message):T(`Login failed: ${e.error.message}`),!1)}async function Za(){let r=(0,Do.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,jo.createServer)((n,s)=>{let o=new URL(n.url||"/","http://localhost"),c=o.searchParams.get("code"),a=o.searchParams.get("state");if(!c||a!==r){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),No(c).then(e)});t.listen(0,"127.0.0.1",async()=>{let n=t.address();if(!n||typeof n=="string"){t.close(),e(!1);return}let s=n.port,c=`${Oe().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${r}`;I()||(w("Opening browser for authentication..."),w(`If the browser doesn't open, visit: ${c}`));try{let a=(await Promise.resolve().then(()=>(Po(),Ro))).default;await a(c)}catch{I()||w(`Could not open browser. Please visit:
147
+ ${c}`)}setTimeout(()=>{t.close(),I()||T("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function $o(r){r.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await No(e.code):t=await Za(),process.exit(t?0:1)})}oe();se();var Ja={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Lo(r){let e=Ja[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${e}/external/${r.githubOwner}/${r.slug}`:r.orgSlug?`${e}/${r.orgSlug}/${r.slug}`:`${e}/${r.slug}`}function Fo(r){r.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let n=new URLSearchParams({q:e});t.type&&n.set("type",t.type),t.tag&&n.set("tag",t.tag),t.limit&&n.set("limit",t.limit);let s=U()?`/api/cli/search?${n}`:`/api/public/search?${n}`,o=await Z(s);o.ok||(I()?D("search",o.error.code,o.error.message):w(`Search failed: ${o.error.message}`),process.exit(1));let c=o.data.results;if(I()){let u=c.map(l=>{let p=Lo(l);return{installPath:p,installCommand:`npx shared-context-ai install ${p}`,title:l.title,description:l.description,resourceType:l.resourceType,installCount:l.installCount,topicTags:l.topicTags}});N("search",{results:u,count:u.length});return}if(c.length===0){let u=t.type?`${t.type}s`:"results";w(`No ${u} found.`);return}w(`Found ${c.length} result${c.length===1?"":"s"}:
148
+ `);let a=c.map(u=>[Lo(u),u.title,`\u2193${u.installCount}`]);w(ye(a)),w(`
149
+ Install a skill: npx shared-context-ai install <installPath>`)})}oe();ue();se();function Mo(r){let e=r.slug||r.resourceId;return r.storageType==="github"&&r.githubOwner?`skills/external/${r.githubOwner}/${e}`:r.orgSlug?`skills/${r.orgSlug}/${e}`:`skills/${e}`}function Uo(r){r.command("list").description("List installed skills").alias("ls").action(async()=>{if(U()){let e=await Z("/api/cli/installed");e.ok||(I()?D("list",e.error.code,e.error.message):w(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(I()){let s=t.map(o=>({...o,installPath:Mo(o)}));N("list",{installations:s,count:s.length});return}if(t.length===0){w("No skills installed."),w("Use 'shared-context-ai search' to find skills to install.");return}w(`${t.length} skill${t.length===1?"":"s"} installed:
150
+ `);let n=t.map(s=>[Mo(s),s.title,s.hasUpdate?"(update available)":"(current)"]);w(ye(n))}else{let t=q().installations;if(I()){N("list",{installations:t,count:t.length});return}if(t.length===0){w("No skills installed locally.");return}w(`${t.length} skill${t.length===1?"":"s"} installed locally:
151
+ `);let n=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);w(ye(n)),w(`
152
+ Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}oe();se();function Ho(r){r.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let n=U()?"/api/cli/resource":"/api/public/resource",s=await Z(`${n}/${e}/preview`);s.ok||(I()?D("preview",s.error.code,s.error.message):T(`Preview failed: ${s.error.message}`),process.exit(1)),I()?N("preview",s.data):w(s.data.content)})}oe();se();function Bo(r){r.command("check").description("Check for skill updates").action(async()=>{U()||(I()?D("check","AUTH_MISSING","Login required to check for updates."):T("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await Z("/api/cli/updates");e.ok||(I()?D("check",e.error.code,e.error.message):T(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:n}=e.data;if(I()){N("check",{updates:t,count:n});return}if(n===0){w("All skills are up to date.");return}w(`${n} update${n===1?"":"s"} available:
153
+ `);let s=t.map(o=>{let c=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${c}`:o.orgSlug?`skills/${o.orgSlug}/${c}`:`skills/${c}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});w(ye(s)),w(`
154
+ Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var at=require("path"),cr=require("fs"),Vo=require("child_process");oe();ue();se();var qo={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Wo(r){let e=r.slug||r.resourceId;return`${qo[r.resourceType]||r.resourceType+"s"}/${e}`}function Go(r){r.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,n)=>{let s=n.optsWithGlobals();U()||(I()?D("update","AUTH_MISSING","Login required to update resources."):T("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=je(s.agent);if(!o){let l=Ve();I()?D("update","NO_AGENTS",l):T(l),process.exit(1)}let c=await Z("/api/cli/updates");c.ok||(I()?D("update",c.error.code,c.error.message):T(`Failed to check updates: ${c.error.message}`),process.exit(1));let a=c.data.updates;if(e&&(a=a.filter(l=>Wo(l)===e||l.slug===e||l.resourceId===e),a.length===0)){I()?D("update","SKILL_NOT_FOUND",`No update available for "${e}".`):w(`No update available for "${e}".`);return}if(a.length===0){I()?N("update",{updated:[],count:0}):w("All resources are up to date.");return}let u=[];for(let l of a){let y=q().installations.find(E=>E.resourceId===l.resourceId&&E.agent===o.id),b;if(y?.installPath){let E=y.installPath.split("/");E[E.length-1]=l.slug||l.resourceId,b=E.join("/")}else b=Wo(l);if(y?.installMode==="plugin"&&l.resourceType==="collection"){try{let E=l.orgSlug||"",d=l.slug||l.resourceId,i=Wt(o.id),g=`/api/cli/resource/collections/${E}/${d}?format=plugin&platform=${i}`,C=await Bt(g,d),O=dt(o.id);O&&(0,Vo.execSync)(`${O} plugin install "${C}"`,{stdio:"pipe"}),l.latestSha&&await F("/api/cli/update",{resourceId:l.resourceId,installedSha:l.latestSha}),le({...y,sha:l.latestSha,installedAt:new Date().toISOString()}),u.push({installPath:b,title:l.title}),I()||w(` Updated plugin: ${b}`)}catch(E){I()||T(` Plugin update failed for ${b}: ${E}`)}continue}let f=await Z(`/api/cli/resource/${b}`);if(!f.ok){I()||T(` Failed to fetch ${b}: ${f.error.message}`);continue}let m=f.data,S=b.split("/").slice(1);if(m.resource.resourceType==="agent"){let E=re(o,!!s.project),d=(0,at.join)(E,...S);G(d,m.files)}else if(m.resource.resourceType==="mcp")Vt(o,!!s.project,m);else{let E=W(o,!!s.project),d=(0,at.join)(E,...S);G(d,m.files)}if(y&&y.installPath&&y.installPath!==b){let E=y.installPath.split("/").slice(1),d;m.resource.resourceType==="agent"?d=(0,at.join)(re(o,!!s.project),...E):m.resource.resourceType!=="mcp"&&(d=(0,at.join)(W(o,!!s.project),...E)),d&&(0,cr.existsSync)(d)&&((0,cr.rmSync)(d,{recursive:!0}),I()||w(` Removed old path: ${y.installPath}`))}let h=l.latestSha||m.resource.latestSha;if(h&&await F("/api/cli/update",{resourceId:l.resourceId,installedSha:h}),le({...y||{},resourceId:l.resourceId,slug:l.slug||l.resourceId,installPath:b,title:m.resource.title,sha:h||"",scope:y?.scope||(s.project?"project":"global"),agent:o.id,installedAt:new Date().toISOString(),latestSha:h||void 0,resourceType:l.resourceType||m.resource.resourceType,serverSynced:!0}),u.push({installPath:b,title:m.resource.title}),I()||w(` Updated ${b}`),m.resource.resourceType==="collection"&&m.memberResources&&y?.installMode!=="plugin"){let E=q(),d=new Set(E.installations.map(i=>i.resourceId));for(let i of m.memberResources){if(d.has(i.id))continue;let g=i.slug||i.id,C=qo[i.resourceType]||i.resourceType+"s",O=l.orgSlug?`${l.orgSlug}/`:"",x=`${C}/${O}${g}`,A=await Z(`/api/cli/resource/${x}`);if(!A.ok){I()||T(` Failed to fetch new member ${x}: ${A.error.message}`);continue}let v=A.data,k=x.split("/").slice(1);if(v.resource.resourceType==="agent"){let R=re(o,!!s.project);G((0,at.join)(R,...k),v.files)}else if(v.resource.resourceType==="mcp")Vt(o,!!s.project,v);else{let R=W(o,!!s.project);G((0,at.join)(R,...k),v.files)}i.latestSha&&await F("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{}),le({resourceId:i.id,slug:g,installPath:x,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:m.resource.id,resourceType:i.resourceType,serverSynced:!0}),I()||w(` + New member: ${x}`)}}}u.length>0&&He(),I()?N("update",{updated:u,count:u.length}):u.length>0&&w(`
155
+ ${u.length} resource${u.length===1?"":"s"} updated.`)})}var ie=require("fs"),yt=require("path"),zo=require("child_process");oe();ue();se();function Zo(r){r.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{if(!e){let m=q().installations;if(m.length===0&&(I()?D("uninstall","NOTHING_INSTALLED","No resources installed."):w("No resources installed."),process.exit(0)),I())N("uninstall",{installations:m.map(S=>({path:S.installPath||S.slug,title:S.title,agent:S.agent}))});else{w(`Installed resources:
156
+ `);let S=m.map(h=>[h.installPath||h.slug,h.title||"",`(${h.agent})`]);w(ye(S)),w(`
157
+ Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=je(s.agent);if(!o){let f=Ve();I()?D("uninstall","NO_AGENTS",f):T(f),process.exit(1)}let a=q().installations.find(f=>f.installPath===e||f.slug===e||f.resourceId===e),u=e.split("/"),p=["skills","files","commands","hooks","collections","agents","mcps"].includes(u[0])?u[0]:null,y=p?u.slice(1):u,b=!1;if(p==="collections")if(a?.installMode==="plugin"){let f=dt(o.id);if(f)try{(0,zo.execSync)(`${f} plugin uninstall "${a.slug}"`,{stdio:"pipe"}),I()||w(`Uninstalled native ${f} plugin: ${a.slug}`)}catch(m){I()||T(`Native uninstall failed: ${m}. Removing tracking only.`)}At(a.resourceId,o.id),U()&&await F("/api/cli/uninstall",{resourceId:a.resourceId,agentPlatform:o.platform}).catch(()=>{}),He(),I()?N("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`);return}else{let f=De(o),m=y[y.length-1],S=s.project?"project":"user",h=await f.uninstall(m,S,o,a?.resourceId);if(b=h.removed,!I())for(let E of h.warnings)T(`Warning: ${E}`);if(a){let d=q().installations.filter(i=>i.collectionId===a.resourceId&&i.agent===o.id);for(let i of d){let g=i.installPath.split("/"),C=g[0],O=g.slice(1);if(C==="agents"){let x=re(o,!!s.project),A=(0,yt.join)(x,...O);(0,ie.existsSync)(A)&&(0,ie.rmSync)(A,{recursive:!0,force:!0})}else if(C==="mcps"){let x=O[O.length-1],A=pe(o,!!s.project);if((0,ie.existsSync)(A))try{let v=JSON.parse((0,ie.readFileSync)(A,"utf-8"));if(typeof v.mcpServers=="object"&&v.mcpServers&&!Array.isArray(v.mcpServers)){let k=v.mcpServers;x in k&&(delete k[x],v.mcpServers=k,(0,ie.writeFileSync)(A,JSON.stringify(v,null,2)+`
158
+ `,"utf-8"))}}catch{}}else if(C==="hooks")Xr(Ie(o,!!s.project),i.installPath);else{let x=W(o,!!s.project),A=(0,yt.join)(x,...O);(0,ie.existsSync)(A)&&(0,ie.rmSync)(A,{recursive:!0,force:!0})}At(i.resourceId,o.id)}}}else if(p==="agents"){let f=re(o,!!s.project),m=(0,yt.join)(f,...y);b=(0,ie.existsSync)(m),b&&(0,ie.rmSync)(m,{recursive:!0,force:!0})}else if(p==="mcps"){let f=y[y.length-1],m=pe(o,!!s.project);if((0,ie.existsSync)(m))try{let S=JSON.parse((0,ie.readFileSync)(m,"utf-8"));if(typeof S.mcpServers=="object"&&S.mcpServers&&!Array.isArray(S.mcpServers)){let h=S.mcpServers;f in h&&(delete h[f],S.mcpServers=h,(0,ie.writeFileSync)(m,JSON.stringify(S,null,2)+`
159
+ `,"utf-8"),b=!0)}}catch{}}else if(p==="hooks"){let f=Ie(o,!!s.project);b=Xr(f,e),!b&&!I()&&T(`Note: No tagged hook entries found in ${f} \u2014 may need manual removal if installed before v0.1.10`)}else{let f=W(o,!!s.project),m=(0,yt.join)(f,...y);if(b=(0,ie.existsSync)(m),b&&(0,ie.rmSync)(m,{recursive:!0,force:!0}),!b&&a?.slug){let S=(0,yt.join)(f,a.slug);(0,ie.existsSync)(S)&&(0,ie.rmSync)(S,{recursive:!0,force:!0})}}if(U()&&a){let f=await F("/api/cli/uninstall",{resourceId:a.resourceId});!f.ok&&!I()&&T(`Warning: Could not record uninstall on server: ${f.error.message}`)}a&&At(a.resourceId,o.id),He(),I()?N("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`)})}ue();oe();se();function Jo(r){r.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=_e(),t=Oe(),n=q(),s=We(),o=Ee(),c=n.installations.filter(y=>!y.projectId),a=n.installations.filter(y=>y.projectId),u=new Map;for(let y of a){let b=y.projectId;u.has(b)||u.set(b,[]),u.get(b).push(y)}let l=[];if(U()&&u.size>0)for(let[y,b]of u){let f=await Z(`/api/cli/projects/${y}/resources`).catch(()=>null),m=f&&f.ok?f.data.resources.length:b.length,S=o?.projectId===y?o.projectName:`Project ${y.slice(0,8)}`;l.push({projectId:y,projectName:S,localCount:b.length,serverCount:m,synced:b.length>=m})}let p={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(y=>y.id),installedCount:n.installations.length,globalCount:c.length,projects:l};if(I()){N("status",p);return}if(w("Shared Context CLI Status"),w("\u2500".repeat(40)),e?.token?w(` Auth: ${e.email} (${e.orgSlug})`):w(" Auth: Not logged in"),w(` API: ${t.apiBase}`),s.length>0?w(` Agents: ${s.map(y=>y.label).join(", ")}`):w(" Agents: None detected"),w(` Global: ${c.length} resource${c.length===1?"":"s"} installed`),l.length>0){w(""),w("Projects:");for(let y of l){let b=y.synced?"\u2713 synced":`\u26A0 ${y.serverCount-y.localCount} new`;w(` ${y.projectName}: ${y.localCount}/${y.serverCount} resources (${b})`)}}else o&&(w(""),w(` Project: ${o.projectName} (linked)`))})}ue();oe();se();function Ko(r){r.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=_e();e.revoke&&U()&&await It("/api/cli/auth"),Nr(),I()?N("logout",{email:t?.email||null}):w("Logged out.")})}var lr=require("fs"),Xo=require("path");oe();se();function Yo(r){r.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=t.github;if(o&&e&&(I()?D("import","INVALID_ARGS","Cannot use --github with a local path"):T("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(I()?D("import","INVALID_ARGS","Provide a local path or --github <url>"):T("Error: Provide a local path or --github <url>"),process.exit(1)),U()||(I()?D("import","AUTH_MISSING","Authentication required for import"):T("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(I()?D("import","INVALID_ARGS","--on-conflict is not supported with --github"):T("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(I()?D("import","INVALID_ARGS","--dry-run is not supported with --github"):T("Error: --dry-run is not supported with --github"),process.exit(1));let m={url:o};t.resourceType&&(m.resourceType=t.resourceType),I()||w(`
160
+ Importing from GitHub: ${o}`);let S=await F("/api/cli/github-import",m);S.ok||(I()?D("import",S.error.code,S.error.message):T(`
161
+ Import failed: ${S.error.message}`),process.exit(1));let h=S.data;if(I()){N("import",h);return}w(""),w(` Source: ${h.source.owner}/${h.source.repo}`),w(` Type: ${h.resourceType}`),w(` Title: ${h.title}`),h.slug&&w(` Slug: ${h.slug}`),w(` URL: ${h.url}`),w(""),w("Import complete: 1 created");return}let c=(0,Xo.resolve)(e);(!(0,lr.existsSync)(c)||!(0,lr.statSync)(c).isDirectory())&&(I()?D("import","INVALID_PATH",`Not a directory: ${c}`):T(`Error: Not a directory: ${c}`),process.exit(1));let a=er(c);if(a.resources.length===0){I()?N("import",{resources:[],message:"No resources found"}):w("No resources found in the specified directory.");return}if(!I()){let m=new Map;for(let h of a.resources)m.set(h.resourceType,(m.get(h.resourceType)||0)+1);let S=[...m.entries()].map(([h,E])=>`${E} ${h}${E===1?"":"s"}`).join(", ");w(`
162
+ Discovered ${a.resources.length} resources in ${e}:`),w(` ${S}`),a.formatLabel&&a.pluginName?w(` ${a.formatLabel}: ${a.pluginName}`):a.pluginName&&w(` Plugin: ${a.pluginName}`)}let u=t.tags?t.tags.split(",").map(m=>m.trim()).filter(Boolean):void 0,l={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:u,resources:a.resources,collectionMemberships:a.collectionMemberships.length>0?a.collectionMemberships:void 0};!I()&&!t.dryRun?w(`
163
+ Executing import...`):I()||w(`
164
+ Dry run \u2014 previewing changes...`);let p=await F("/api/cli/import",l,12e4);p.ok||(I()?D("import",p.error.code,p.error.message):T(`
165
+ Import failed: ${p.error.message}`),process.exit(1));let y=p.data;if(I()){N("import",y);return}let b=[...y.created.map(m=>({...m,action:"created"})),...y.updated.map(m=>({...m,action:"updated"})),...y.installed.map(m=>({...m,action:"installed"})),...y.cloned.map(m=>({...m,action:"cloned"})),...y.skipped.map(m=>({...m,action:"skipped"})),...y.errors.map(m=>({...m,action:"error"}))];if(b.length>0){w("");let m=b.length,S=b.map((h,E)=>{let d=`[${String(E+1).padStart(String(m).length)}/${m}]`,i=(h.resourceType||"").padEnd(10),g=(h.importPath.split("/").pop()||"").padEnd(24),C="";switch(h.action){case"created":C=`\u2713 created${h.slug?` (slug: ${h.slug})`:""}`;break;case"updated":C="\u2713 updated";break;case"installed":{let O=h.versionsBehind;C=`\u2713 installed${O?` (${O} versions behind)`:""}`;break}case"cloned":C=`\u2713 cloned${h.slug?` (slug: ${h.slug})`:""}`;break;case"skipped":C=`\u2713 skipped (${h.reason||"up to date"})`;break;case"error":C=`\u2717 error: ${h.error||"unknown"}`;break}return` ${d} ${i} ${g} ${C}`});for(let h of S)w(h)}if(y.collections.length>0)for(let m of y.collections){let S=m.importPath.split("/").pop()||m.importPath;w(` collection ${S.padEnd(20)} \u2713 ${m.membersLinked} members linked${m.membersFailed>0?`, ${m.membersFailed} failed`:""}`)}w("");let f=[y.created.length>0?`${y.created.length} created`:null,y.installed.length>0?`${y.installed.length} installed`:null,y.cloned.length>0?`${y.cloned.length} cloned`:null,y.updated.length>0?`${y.updated.length} updated`:null,y.skipped.length>0?`${y.skipped.length} skipped`:null,y.errors.length>0?`${y.errors.length} errors`:null].filter(Boolean);t.dryRun?w(`Dry run complete: ${f.join(", ")}`):w(`Import complete: ${f.join(", ")}`),y.errors.length>0&&process.exit(1)})}var Tn=require("path"),si=require("os");oe();ue();se();var tc={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ri(r,e){let t=r.installations.findIndex(n=>n.resourceId===e.resourceId&&n.agent===e.agent);t>=0?r.installations[t]=e:r.installations.push(e)}function ni(r){let e=r.slug||r.resourceId,t=tc[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${t}/external/${r.githubOwner}/${e}`:r.orgSlug?`${t}/${r.orgSlug}/${e}`:`${t}/${e}`}function oi(r){r.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(!n.force&&!Lr()){let _=q(),P=_.installations.filter(M=>M.latestSha&&M.sha&&M.latestSha!==M.sha),L=_.lastSyncAt?Math.floor((Date.now()-new Date(_.lastSyncAt).getTime())/6e4):void 0,$={updatesAvailable:P.length,untrackedResources:0,driftRepairs:0,autoInstalled:0,autoInstallFailures:0,updates:P.map(M=>({installPath:M.installPath,title:M.title,sha:M.sha,latestSha:M.latestSha})),untracked:[],summary:vn(P.length,0)+(L!==void 0?` (cached ${L}m ago, run --force to refresh)`:""),throttled:!0,cacheAge:L};kn($,!!n.quiet);return}U()||(I()?D("sync","AUTH_MISSING","Login required to sync."):T("Login required. Run 'shared-context-ai login'."),process.exit(1));let s=je(n.agent),o=await Z("/api/cli/installed");if(!o.ok){let P=q().installations.filter($=>$.latestSha&&$.sha&&$.latestSha!==$.sha);!I()&&!n.quiet&&T(`Warning: Could not reach server (${o.error.message}). Showing cached state.`);let L={updatesAvailable:P.length,untrackedResources:0,driftRepairs:0,autoInstalled:0,autoInstallFailures:0,updates:P.map($=>({installPath:$.installPath,title:$.title,sha:$.sha,latestSha:$.latestSha})),untracked:[],summary:vn(P.length,0)+" (offline)",throttled:!1};kn(L,!!n.quiet);return}let c=o.data.installations,a=new Map(c.map(_=>[_.resourceId,_])),u=q(),l=0;for(let _ of u.installations){let P=a.get(_.resourceId);if(P)_.latestSha=P.latestSha||void 0,_.resourceType=_.resourceType||P.resourceType,_.serverSynced=!0,P.installedSha&&_.sha&&P.installedSha!==_.sha&&(!I()&&!n.quiet&&w(` Drift repaired: ${_.installPath} (local=${_.sha.slice(0,7)} \u2192 server=${P.installedSha.slice(0,7)})`),_.sha=P.installedSha,l++),a.delete(_.resourceId);else if(_.serverSynced!==!1){let L=await F("/api/cli/install",{resourceId:_.resourceId,agentPlatform:s?.platform||"claude_code",installedSha:_.sha});L.ok?_.serverSynced=!0:(L.error.code==="NOT_FOUND"||L.error.code==="RESOURCE_NOT_FOUND")&&(_.serverSynced=!1,_.resourceId="",l++)}}u.installations=u.installations.filter(_=>_.resourceId!=="");let p=Array.from(a.values()),y=0,b=0,f=!1;if(p.length>0&&s){for(let _ of p){if(f){b++;continue}let P=ni(_);try{let L=await Z(`/api/cli/resource/${P}`);if(!L.ok){if(b++,L.error.code==="RATE_LIMITED"||L.error.code==="429"){f=!0,!I()&&!n.quiet&&T(` Auto-install rate-limited after ${y} resource(s). Remaining will retry on next sync.`);continue}!I()&&!n.quiet&&T(` Auto-install skipped: ${P} \u2014 ${L.error.message}`);continue}let $=L.data,M=await Jr($,s,{project:!1,manifest:u,authed:!0});for(let ne of M.warnings)!I()&&!n.quiet&&T(` Warning: ${ne}`);for(let ne of M.notes)!I()&&!n.quiet&&w(` ${ne}`);let Se=$.resource.resourceType==="collection",z={resourceId:$.resource.id,slug:M.slug,installPath:M.installPath,title:$.resource.title,sha:$.resource.latestSha||_.installedSha||"",scope:"global",agent:s.id,installedAt:new Date().toISOString(),latestSha:$.resource.latestSha||void 0,resourceType:$.resource.resourceType,serverSynced:!0,...Se?{pluginFormat:Ht(s.id),memberCount:$.memberResources?.length,installMode:M.installMode,pluginDir:M.pluginDir}:{}};if(ri(u,z),Se&&$.memberResources&&M.installMode==="decomposed")for(let ne of $.memberResources)ri(u,Zr(ne,$.resource,s.id));y++}catch(L){b++,!I()&&!n.quiet&&T(` Auto-install failed: ${P} \u2014 ${L}`)}}y>0&&!I()&&!n.quiet&&w(`
166
+ Auto-installed ${y} resource${y===1?"":"s"} from web dashboard`)}else if(p.length>0&&!I()&&!n.quiet){w(`
167
+ ${p.length} resource${p.length===1?"":"s"} installed elsewhere (use --agent to auto-install):`);for(let _ of p.slice(0,5))w(` ${ni(_)} \u2014 ${_.title}`);p.length>5&&w(` ...and ${p.length-5} more`)}Ue(u);let m=s?[s]:We();m.length===0&&!I()&&!n.quiet&&T("No AI agents detected \u2014 resource discovery skipped. Use --agent to specify one.");let S=m.map(_=>({root:n.project?(0,Tn.join)(process.cwd(),_.dir):(0,Tn.join)((0,si.homedir)(),_.dir),agent:_,isProject:!!n.project})),h={imported:[],errors:0,projectRegistered:0,untrackedCount:0,discoveredPaths:[],untracked:[]};if(S.length>0){if(h=await tr({scanRoots:S,agentId:s?.id||m[0]?.id||"unknown",registerToProject:!!n.project,skipImport:n.import===!1}),h.imported.length>0&&!I()&&!n.quiet){w(`
168
+ Imported ${h.imported.length} resource${h.imported.length===1?"":"s"}:`);let _=h.imported.map(P=>[` ${(P.resourceType||"").padEnd(12)}`,(P.slug||P.importPath.split("/").pop()||"").padEnd(24),P.importPath]);w(ye(_))}if(h.errors>0&&!I()&&T(`
169
+ ${h.errors} import error(s)`),h.projectRegistered>0&&!I()&&!n.quiet){let _=Ee();w(`
170
+ Project "${_?.projectName}": registered ${h.projectRegistered} resource${h.projectRegistered===1?"":"s"}`)}}let E=h.untrackedCount,d=Ee(),i=0;if(d){let _=await Z(`/api/cli/projects/${d.projectId}/resources`);if(!_.ok)!I()&&!n.quiet&&(T(`Warning: Project "${d.projectName}" not found on server (may have been deleted).`),T(" Remove .shared-context/project.json to unlink this directory."));else{let P=_.data.project;P&&(P.name!==d.projectName||P.slug!==d.projectSlug)&&tt({projectId:d.projectId,projectName:P.name,projectSlug:P.slug});let L=_.data.resources,$=u.installations.filter(z=>z.projectId===d.projectId),M=new Set($.map(z=>z.resourceId)),Se=L.filter(z=>!M.has(z.id));if(Se.length>0)if(!s)!I()&&!n.quiet&&T(`
171
+ Project "${d.projectName}" has ${Se.length} new resource${Se.length===1?"":"s"} \u2014 use --agent to install them.`);else{let z=De(s);for(let ne of Se){let we=ne.installPath;try{let Ne=await Z(`/api/cli/resource/${we}`);if(!Ne.ok)continue;await z.install(Ne.data,"project",s),le({resourceId:ne.id,slug:ne.slug||ne.id,installPath:we,title:ne.title,sha:ne.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:d.projectId,resourceType:ne.resourceType,serverSynced:!0}),ne.latestSha&&await F("/api/cli/install",{resourceId:ne.id,agentPlatform:s.platform,installedSha:ne.latestSha}).catch(()=>{}),i++}catch{}}!I()&&!n.quiet&&i>0&&w(`
172
+ Project "${d.projectName}": installed ${i} new resource${i===1?"":"s"}`)}if(n.project){let z=new Set(L.map(Ne=>Ne.id)),ne=new Set(h.discoveredPaths),we=0;for(let Ne of u.installations){if(z.has(Ne.resourceId)||!ne.has(Ne.installPath))continue;(await F(`/api/cli/projects/${d.projectId}/resources`,{resourceId:Ne.resourceId})).ok&&(Ne.projectId=d.projectId,we++)}we>0&&!I()&&!n.quiet&&w(`
173
+ Project "${d.projectName}": registered ${we} existing resource${we===1?"":"s"}`)}await F(`/api/cli/projects/${d.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let g=h.imported.length,C=q(),O=new Set(C.installations.map(_=>`${_.resourceId}:${_.agent}`)),x=[...C.installations,...u.installations.filter(_=>!O.has(`${_.resourceId}:${_.agent}`))];if(u.installations=x,n.force){let _=u.lastSyncAt;u.lastSyncAt=_||new Date().toISOString()}else b===0&&(u.lastSyncAt=new Date().toISOString());Ue(u);let A=u.installations.filter(_=>_.latestSha&&_.sha&&_.latestSha!==_.sha),v=_e();v?.connectionId&&F("/api/cli/sync-report",{connectionId:v.connectionId,lastSyncResult:{updatesAvailable:A.length,importedCount:g}}).catch(()=>{});try{let{pushTelemetry:_}=await Promise.resolve().then(()=>(On(),ti));await _(!0)}catch{}let k=h.untracked,R={updatesAvailable:A.length,untrackedResources:k.length,driftRepairs:l,autoInstalled:y,autoInstallFailures:b,updates:A.map(_=>({installPath:_.installPath,title:_.title,sha:_.sha,latestSha:_.latestSha})),untracked:k,summary:vn(A.length,k.length,l,y,b),throttled:!1};kn(R,!!n.quiet)})}function vn(r,e,t=0,n=0,s=0){let o=[];return n>0&&o.push(`${n} auto-installed`),r>0&&o.push(`${r} update${r===1?"":"s"} available`),e>0&&o.push(`${e} untracked resource${e===1?"":"s"}`),t>0&&o.push(`${t} drift repair${t===1?"":"s"}`),s>0&&o.push(`${s} auto-install failure${s===1?"":"s"}`),o.length===0?"Everything is up to date.":o.join(", ")}function kn(r,e){if(I()){N("sync",r);return}if(e){let t=r.summary;r.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),r.untrackedResources>0&&(t+=` \u2014 ${r.untrackedResources} untracked`),w(t);return}if(w(""),r.updates.length>0){w(`${r.updates.length} update${r.updates.length===1?"":"s"} available:
174
+ `);let t=r.updates.map(n=>[` ${n.installPath}`,n.title,`${n.sha.slice(0,7)} \u2192 ${n.latestSha.slice(0,7)}`]);w(ye(t)),w("")}if(r.untracked.length>0){w(`${r.untracked.length} untracked resource${r.untracked.length===1?"":"s"}:
175
+ `);let t=r.untracked.map(n=>[` ${n.resourceType.padEnd(12)}`,n.importPath.padEnd(30),n.title]);w(ye(t)),w("")}r.updatesAvailable===0&&r.untrackedResources===0?w("Everything is up to date."):(r.updatesAvailable>0&&w("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&w("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),w("")}var ii=require("path"),ai=require("readline");oe();oe();se();function ci(r){let e=r.command("project").description("Manage projects");e.command("create").description("Create a project for the current folder").argument("[name]","Project name (defaults to folder name)").action(async t=>{if(!U()){let l="Not authenticated. Run 'shared-context-ai login' first.";I()?D("project create","AUTH_MISSING",l):T(l),process.exit(1)}let n=Ee();if(n){I()?N("project create",{alreadyExists:!0,project:{id:n.projectId,name:n.projectName,slug:n.projectSlug}}):w(`Project already linked: ${n.projectName}`);return}let s=t?.trim()||(0,ii.basename)(process.cwd());if(!s||s==="/"){let l='Could not determine project name. Provide one: shared-context-ai project create "My Project"';I()?D("project create","INVALID_NAME",l):T(l),process.exit(1)}let o=await F("/api/cli/projects",{name:s});o.ok||(I()?D("project create",o.error.code,o.error.message):T(`Failed to create project: ${o.error.message}`),process.exit(1));let{id:c,name:a,slug:u}=o.data;tt({projectId:c,projectName:a,projectSlug:u}),I()?N("project create",{id:c,name:a,slug:u}):(w(`Created project: ${a}`),w(""),w("Quick reference:"),w(" shared-context-ai install <installPath> Add a resource to this project"),w(" shared-context-ai sync Check for resource updates"),w(" shared-context-ai status View project sync status"))}),e.command("delete").description("Delete the project linked to the current folder").option("--id <projectId>","Project ID to delete (overrides local config)").option("--force","Skip confirmation prompt").action(async t=>{if(!U()){let a="Not authenticated. Run 'shared-context-ai login' first.";I()?D("project delete","AUTH_MISSING",a):T(a),process.exit(1)}let n=Ee(),s=t.id||n?.projectId,o=n?.projectName||s;if(!s){let a="No project linked to this folder. Use --id <projectId> to specify one.";I()?D("project delete","NO_PROJECT",a):T(a),process.exit(1)}if(!t.force&&!I()&&process.stdin.isTTY&&!await new Promise(u=>{let l=(0,ai.createInterface)({input:process.stdin,output:process.stdout});l.question(`Delete project "${o}"? This cannot be undone. [y/N] `,p=>{l.close(),u(p.trim().toLowerCase()==="y"||p.trim().toLowerCase()==="yes")})})){w("Cancelled.");return}let c=await It(`/api/cli/projects/${s}`);c.ok||(I()?D("project delete",c.error.code,c.error.message):T(`Failed to delete project: ${c.error.message}`),process.exit(1)),n?.projectId===s&&Us(),I()?N("project delete",{deleted:!0,projectId:s}):w(`Deleted project: ${c.data.name}`)})}On();var dr=require("fs"),fr=require("path"),Rn=require("os");se();function rc(){let r=process.env.SC_PROFILE;return r?(0,fr.join)((0,Rn.homedir)(),".config","shared-context","profiles",r):(0,fr.join)((0,Rn.homedir)(),".config","shared-context")}function nc(){let r=(0,fr.join)(rc(),"usage.jsonl");if(!(0,dr.existsSync)(r))return[];try{let e=(0,dr.readFileSync)(r,"utf8").trim().split(`
176
+ `).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function li(r){r.command("stats").description("Show local usage statistics").option("--days <n>","Number of days to show","7").action(e=>{let t=parseInt(e.days,10)||7,n=new Date;n.setDate(n.getDate()-t);let o=nc().filter(u=>new Date(u.ts)>=n);if(o.length===0){I()?N("stats",{days:t,events:0,skills:[],agents:[]}):w("No usage data yet");return}let c=new Map,a=new Map;for(let u of o)if(u.event==="skill_invoked"){let l=c.get(u.slug)||{count:0,ok:0};l.count++,u.ok&&l.ok++,c.set(u.slug,l)}else if(u.event==="agent_invoked"){let l=a.get(u.slug)||{count:0,ok:0,totalMs:0,totalTokens:0};l.count++,u.ok&&l.ok++,u.dur_ms&&(l.totalMs+=u.dur_ms),u.tokens&&(l.totalTokens+=u.tokens),a.set(u.slug,l)}if(I()){N("stats",{days:t,events:o.length,skills:[...c.entries()].map(([u,l])=>({slug:u,...l})),agents:[...a.entries()].map(([u,l])=>({slug:u,...l,avgMs:l.count>0?Math.round(l.totalMs/l.count):0,avgTokens:l.count>0?Math.round(l.totalTokens/l.count):0}))});return}if(w(`Usage over the last ${t} day${t===1?"":"s"} (${o.length} event${o.length===1?"":"s"})
177
+ `),c.size>0){w("Skills:");let u=[...c.entries()].sort((l,p)=>p[1].count-l[1].count).map(([l,p])=>[` ${l}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`]);w(ye(u))}if(a.size>0){c.size>0&&w(""),w("Agents:");let u=[...a.entries()].sort((l,p)=>p[1].count-l[1].count).map(([l,p])=>{let y=p.count>0?Math.round(p.totalMs/p.count):0;return[` ${l}`,`${p.count} use${p.count===1?"":"s"}`,`${Math.round(p.ok/p.count*100)}% ok`,y>0?`avg ${(y/1e3).toFixed(1)}s`:""]});w(ye(u))}})}nn();var ui={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."},pr=class extends Error{constructor(t,n){super(n||ui[t]);this.code=t;this.name="CliError"}get recovery(){return ui[this.code]}};se();var ce=new qn;ce.name("shared-context-ai").description("CLI for Shared Context - search, install, and manage AI skills").version("0.1.0").option("--json","Output as JSON (default when piped)").option("--human","Output as human-readable text (default in TTY)").option("--agent <name>","Override agent detection").option("--project","Use project-local directory instead of global").hook("preAction",r=>{let e=r.opts();Zn(!!e.json,!!e.human)});ro(ce);$o(ce);Fo(ce);Vs(ce);Uo(ce);Ho(ce);Bo(ce);Go(ce);Zo(ce);Jo(ce);Ko(ce);Yo(ce);oi(ce);ci(ce);_n(ce);li(ce);rn(ce);process.on("uncaughtException",r=>{r instanceof pr?I()?D(process.argv[2]||"unknown",r.code,r.message):(T(`Error: ${r.message}`),T(r.recovery)):I()?D(process.argv[2]||"unknown","UNEXPECTED",r.message||"Unexpected error"):T(`Error: ${r.message||r}`),process.exit(1)});ce.parse();