shared-context-ai 0.1.24 → 0.1.25

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.
package/dist/index 2.js DELETED
@@ -1,176 +0,0 @@
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,I){return t.formatItem(g,n,I,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(I=>o(t.styleOptionTerm(t.optionTerm(I)),t.styleOptionDescription(t.optionDescription(I))));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 In(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 I=p.trimStart();u=[I],a=this.displayWidth(I)}),o.push(u.join(""))}),o.join(`
6
- `)}};function In(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}gr.Help=hr;gr.stripColor=In});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}
7
- - a short flag is a single dash and a single character
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?`
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(),_r=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:()=>Ir()??(F.stdout.isTTY&&F.stdout.hasColors?.()),getErrHasColors:()=>Ir()??(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
19
- - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
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 I=Re.resolve(p,g);if(kt.existsSync(I))return I;if(s.includes(Re.extname(g)))return;let d=s.find(m=>kt.existsSync(`${I}${m}`));if(d)return`${I}${d}`}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}
22
- `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
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 Ir(){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=_r;xr.useColor=Ir});var $n=Z(be=>{"use strict";var{Argument:Dn}=Ot(),{Command:Or}=Pn(),{CommanderError:bi,InvalidArgumentError:jn}=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 Dn(r,e);be.Command=Or;be.Option=Nn;be.Argument=Dn;be.Help=Ai;be.CommanderError=bi;be.InvalidArgumentError=jn;be.InvalidOptionArgumentError=jn});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 P(r,e,t){console.log(JSON.stringify({ok:!1,command:r,errors:[{code:e,message:t}]}))}function b(r){console.log(r)}function v(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:()=>_e,getManifest:()=>B,getSyncState:()=>vi,removeFromManifest:()=>wt,saveAuth:()=>Tr,saveConfig:()=>qn,saveManifest:()=>Ne,saveSyncState:()=>Ti,shouldSync:()=>Dr,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 _i(){(0,Se.mkdirSync)(St(),{recursive:!0})}function Et(r,e){try{return(0,Se.existsSync)(r)?JSON.parse((0,Se.readFileSync)(r,"utf-8")):e}catch{return e}}function Ct(r,e,t=!1){if(_i(),(0,Se.writeFileSync)(r,JSON.stringify(e,null,2)+`
29
- `,"utf-8"),t)try{(0,Se.chmodSync)(r,384)}catch{}}function Ae(){return Et(vr(),null)}function Tr(r){Ct(vr(),r,!0)}function Rr(){try{(0,Se.writeFileSync)(vr(),"{}","utf-8")}catch{}}function _e(){return Et(Vn(),Ii)}function qn(r){Ct(Vn(),r)}function vt(r){let e=_e();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,Se.unlinkSync)(t)}catch{}return e}function B(){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=B(),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=B();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),Ne(t)}function $e(){let r=B();delete r.lastSyncAt,Ne(r)}function Tt(r){let e=B();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 Dr(){let r=parseInt(process.env.SC_SYNC_COOLDOWN||"",10),e=r>=0?r:ki,t=B();return t.lastSyncAt?Date.now()-new Date(t.lastSyncAt).getTime()>=e:!0}var Se,Ke,Wn,Bn,Ii,xi,ki,ce=pe(()=>{"use strict";Se=require("fs"),Ke=require("path"),Wn=require("os"),Bn=(0,Ke.join)((0,Wn.homedir)(),".config","shared-context");Ii={apiBase:"https://sharedcontext.ai"};xi={version:2,installations:[]};ki=720*60*1e3});var Zn={};gt(Zn,{del:()=>jr,fetchRaw:()=>Nr,get:()=>G,isAuthenticated:()=>L,patch:()=>Ri,post:()=>$});function Gn(){return _e().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 jr(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 Dt=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 Di=require("fs"),oe=require("path"),Yn=Lr(),ji=Dt(),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 Y(r){this.sep=oe.sep,this.fs=Di,Qn(r)&&Qn(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}ts.exports=Y;Y.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(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw c}if(l&&l.isFile())throw ji.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};Y.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};Y.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,I){g?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(d,m){o.fs.write(m,e,0,e.length,0,function(){o.fs.close(m,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):I?o.fs.write(I,e,0,e.length,0,function(){o.fs.close(I,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};Y.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)};Y.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))})})})};Y.prototype.getAttributes=function(){};Y.prototype.setAttributes=function(){};Y.crc32update=function(r,e){return es[(r^e)&255]^r>>>8};Y.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=Y.crc32update(t,r[n++]);return~t>>>0};Y.methodToString=function(r){switch(r){case Yn.STORED:return"STORED ("+r+")";case Yn.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};Y.canonical=function(r){if(!r)return"";let e=oe.posix.normalize("/"+r.split("\\").join("/"));return oe.join(".",e)};Y.zipnamefix=function(r){if(!r)return"";let e=oe.posix.normalize("/"+r.split("\\").join("/"));return oe.posix.join(".",e)};Y.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]};Y.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)))};Y.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};Y.readBigUInt64LE=function(r,e){let t=r.readUInt32LE(e);return r.readUInt32LE(e+4)*4294967296+t};Y.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)};Y.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};Y.isWin=Ni;Y.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=Dt();at.exports.FileAttr=ss();at.exports.decoder=is()});var cs=Z((_c,as)=>{"use strict";var Ue=ct(),T=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,I=0,d=0,m=0;r|=Ue.isWin?2560:768,t|=T.FLG_EFS;let y={extraLen:0},f=i=>Math.max(0,i)>>>0,h=i=>Math.max(0,i)&65535,C=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&T.FLG_EFS)>0},set flags_efs(i){i?t|=T.FLG_EFS:t&=~T.FLG_EFS},get flags_desc(){return(t&T.FLG_DESC)>0},set flags_desc(i){i?t|=T.FLG_DESC:t&=~T.FLG_DESC},get method(){return n},set method(i){switch(i){case T.STORED:this.version=10;case T.DEFLATED:default:this.version=20}n=i},get time(){return Ue.fromDOS2Date(this.timeval)},set time(i){i=new Date(i),this.timeval=Ue.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=f(i)},get timeHighByte(){return C(s>>>8)},get crc(){return o},set crc(i){o=f(i)},get compressedSize(){return l},set compressedSize(i){l=f(i)},get size(){return c},set size(i){c=f(i)},get fileNameLength(){return u},set fileNameLength(i){u=i},get extraLength(){return a},set extraLength(i){a=i},get extraLocalLength(){return y.extraLen},set extraLocalLength(i){y.extraLen=i},get commentLength(){return p},set commentLength(i){p=i},get diskNumStart(){return g},set diskNumStart(i){g=f(i)},get inAttr(){return I},set inAttr(i){I=f(i)},get attr(){return d},set attr(i){d=f(i)},get fileAttr(){return(d||0)>>16&4095},get offset(){return m},set offset(i){m=f(i)},get encrypted(){return(t&T.FLG_ENC)===T.FLG_ENC},get centralHeaderSize(){return T.CENHDR+u+a+p},get realDataOffset(){return m+T.LOCHDR+y.fnameLen+y.extraLen},get localHeader(){return y},loadLocalHeaderFromBinary:function(i){var S=i.slice(m,m+T.LOCHDR);if(S.readUInt32LE(0)!==T.LOCSIG)throw Ue.Errors.INVALID_LOC();y.version=S.readUInt16LE(T.LOCVER),y.flags=S.readUInt16LE(T.LOCFLG),y.flags_desc=(y.flags&T.FLG_DESC)>0,y.method=S.readUInt16LE(T.LOCHOW),y.time=S.readUInt32LE(T.LOCTIM),y.crc=S.readUInt32LE(T.LOCCRC),y.compressedSize=S.readUInt32LE(T.LOCSIZ),y.size=S.readUInt32LE(T.LOCLEN),y.fnameLen=S.readUInt16LE(T.LOCNAM),y.extraLen=S.readUInt16LE(T.LOCEXT);let E=m+T.LOCHDR+y.fnameLen,w=E+y.extraLen;return i.slice(E,w)},loadFromBinary:function(i){if(i.length!==T.CENHDR||i.readUInt32LE(0)!==T.CENSIG)throw Ue.Errors.INVALID_CEN();r=i.readUInt16LE(T.CENVEM),e=i.readUInt16LE(T.CENVER),t=i.readUInt16LE(T.CENFLG),n=i.readUInt16LE(T.CENHOW),s=i.readUInt32LE(T.CENTIM),o=i.readUInt32LE(T.CENCRC),l=i.readUInt32LE(T.CENSIZ),c=i.readUInt32LE(T.CENLEN),u=i.readUInt16LE(T.CENNAM),a=i.readUInt16LE(T.CENEXT),p=i.readUInt16LE(T.CENCOM),g=i.readUInt16LE(T.CENDSK),I=i.readUInt16LE(T.CENATT),d=i.readUInt32LE(T.CENATX),m=i.readUInt32LE(T.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(T.LOCHDR);return i.writeUInt32LE(T.LOCSIG,0),i.writeUInt16LE(e,T.LOCVER),i.writeUInt16LE(t,T.LOCFLG),i.writeUInt16LE(n,T.LOCHOW),i.writeUInt32LE(s,T.LOCTIM),i.writeUInt32LE(o,T.LOCCRC),i.writeUInt32LE(l,T.LOCSIZ),i.writeUInt32LE(c,T.LOCLEN),i.writeUInt16LE(u,T.LOCNAM),i.writeUInt16LE(y.extraLen,T.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(T.CENHDR+u+a+p);return i.writeUInt32LE(T.CENSIG,0),i.writeUInt16LE(r,T.CENVEM),i.writeUInt16LE(e,T.CENVER),i.writeUInt16LE(t,T.CENFLG),i.writeUInt16LE(n,T.CENHOW),i.writeUInt32LE(s,T.CENTIM),i.writeUInt32LE(o,T.CENCRC),i.writeUInt32LE(l,T.CENSIZ),i.writeUInt32LE(c,T.CENLEN),i.writeUInt16LE(u,T.CENNAM),i.writeUInt16LE(a,T.CENEXT),i.writeUInt16LE(p,T.CENCOM),i.writeUInt16LE(g,T.CENDSK),i.writeUInt16LE(I,T.CENATT),i.writeUInt32LE(d,T.CENATX),i.writeUInt32LE(m,T.CENOFF),i},toJSON:function(){let i=function(S){return S+" 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:I,attr:d,offset:m,centralHeaderSize:i(T.CENHDR+u+a+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var us=Z((Ic,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=Dt(),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 jt={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?jt.genSalt=function(){return r.slice(0,12)}:r==="node"?jt.genSalt=bt.node:jt.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=jt.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 U=ct(),qi=Mr(),Q=U.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:U.decoder;a=g.hasOwnProperty("efs")?g.efs:!1;function I(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function d(i){if(!t.flags_desc&&!t.localHeader.flags_desc){if(U.crc32(i)!==t.localHeader.crc)return!1}else{let S={},E=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(E)==Q.LOCSIG||e.readUInt32LE(E)==Q.CENSIG)throw U.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(E)==Q.EXTSIG)S.crc=e.readUInt32LE(E+Q.EXTCRC),S.compressedSize=e.readUInt32LE(E+Q.EXTSIZ),S.size=e.readUInt32LE(E+Q.EXTLEN);else if(e.readUInt16LE(E+12)===19280)S.crc=e.readUInt32LE(E+Q.EXTCRC-4),S.compressedSize=e.readUInt32LE(E+Q.EXTSIZ-4),S.size=e.readUInt32LE(E+Q.EXTLEN-4);else throw U.Errors.DESCRIPTOR_UNKNOWN();if(S.compressedSize!==t.compressedSize||S.size!==t.size||S.crc!==t.crc)throw U.Errors.DESCRIPTOR_FAULTY();if(U.crc32(i)!==S.crc)return!1}return!0}function m(i,S,E){if(typeof S>"u"&&typeof i=="string"&&(E=i,i=void 0),o)return i&&S&&S(Buffer.alloc(0),U.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var w=I();if(w.length===0)return i&&S&&S(w),w;if(t.encrypted){if(typeof E!="string"&&!Buffer.isBuffer(E))throw U.Errors.INVALID_PASS_PARAM();w=Ur.ZipCrypto.decrypt(w,t,E)}var A=Buffer.alloc(t.size);switch(t.method){case U.Constants.STORED:if(w.copy(A),d(A))return i&&S&&S(A),A;throw i&&S&&S(A,U.Errors.BAD_CRC()),U.Errors.BAD_CRC();case U.Constants.DEFLATED:var _=new Ur.Inflater(w,t.size);if(i)_.inflateAsync(function(O){O.copy(O,0),S&&(d(O)?S(O):S(O,U.Errors.BAD_CRC()))});else{if(_.inflate(A).copy(A,0),!d(A))throw U.Errors.BAD_CRC(`"${g.decode(n)}"`);return A}break;default:throw i&&S&&S(Buffer.alloc(0),U.Errors.UNKNOWN_METHOD()),U.Errors.UNKNOWN_METHOD()}}function y(i,S){if((!l||!l.length)&&Buffer.isBuffer(e))return i&&S&&S(I()),I();if(l.length&&!o){var E;switch(t.method){case U.Constants.STORED:return t.compressedSize=t.size,E=Buffer.alloc(l.length),l.copy(E),i&&S&&S(E),E;default:case U.Constants.DEFLATED:var w=new Ur.Deflater(l);if(i)w.deflateAsync(function(_){E=Buffer.alloc(_.length),t.compressedSize=_.length,_.copy(E),S&&S(E)});else{var A=w.deflate();return t.compressedSize=A.length,A}w=null;break}}else if(i&&S)S(Buffer.alloc(0));else return Buffer.alloc(0)}function f(i,S){return U.readBigUInt64LE(i,S)}function h(i){try{for(var S=0,E,w,A;S+4<i.length;)E=i.readUInt16LE(S),S+=2,w=i.readUInt16LE(S),S+=2,A=i.slice(S,S+w),S+=w,Q.ID_ZIP64===E&&C(A)}catch{throw U.Errors.EXTRA_FIELD_PARSE_ERROR()}}function C(i){var S,E,w,A;i.length>=Q.EF_ZIP64_SCOMP&&(S=f(i,Q.EF_ZIP64_SUNCOMP),t.size===Q.EF_ZIP64_OR_32&&(t.size=S)),i.length>=Q.EF_ZIP64_RHO&&(E=f(i,Q.EF_ZIP64_SCOMP),t.compressedSize===Q.EF_ZIP64_OR_32&&(t.compressedSize=E)),i.length>=Q.EF_ZIP64_DSN&&(w=f(i,Q.EF_ZIP64_RHO),t.offset===Q.EF_ZIP64_OR_32&&(t.offset=w)),i.length>=Q.EF_ZIP64_DSN+4&&(A=i.readUInt32LE(Q.EF_ZIP64_DSN),t.diskNumStart===Q.EF_ZIP64_OR_16&&(t.diskNumStart=A))}return{get entryName(){return g.decode(n)},get rawEntryName(){return n},set entryName(i){n=U.toBuffer(i,g.encode);var S=n[n.length-1];o=S===47||S===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,h(i)},get comment(){return g.decode(s)},set comment(i){if(s=U.toBuffer(i,g.encode),t.commentLength=s.length,s.length>65535)throw U.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 y(!1,null)},getCompressedDataAsync:function(i){y(!0,i)},setData:function(i){l=U.toBuffer(i,U.decoder.encode),!o&&l.length?(t.size=l.length,t.method=U.Constants.DEFLATED,t.crc=U.crc32(i),t.changed=!0):t.method=U.Constants.STORED},getData:function(i){return t.changed?l:m(!1,null,i)},getDataAsync:function(i,S){t.changed?i(l):m(!0,i,S)},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(),S=U.Constants.CENHDR;return n.copy(i,S),S+=n.length,c.copy(i,S),S+=t.extraLength,s.copy(i,S),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=u.length;let S=t.localHeaderToBinary(),E=Buffer.alloc(S.length+n.length+t.extraLocalLength);return S.copy(E,i),i+=S.length,n.copy(E,i),i+=n.length,u.copy(E,i),i+=u.length,E},toJSON:function(){let i=function(S){return"<"+(S&&S.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 _s=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?m(a.readEntries):l=!0;function I(){let f=new Set;for(let h of Object.keys(n)){let C=h.split("/");if(C.pop(),!!C.length)for(let i=0;i<C.length;i++){let S=C.slice(0,i+1).join("/")+"/";f.add(S)}}for(let h of f)if(!(h in n)){let C=new bs(a);C.entryName=h,C.attr=16,C.temporary=!0,t.push(C),n[C.entryName]=C,u.add(C)}}function d(){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 f=o.offset,h=0;h<t.length;h++){var C=f,i=new bs(a,r);i.header=r.slice(C,C+=de.Constants.CENHDR),i.entryName=r.slice(C,C+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(C,C+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(C,C+i.header.commentLength)),f+=i.header.centralHeaderSize,t[h]=i,n[i.entryName]=i}u.clear(),I()}function m(f){var h=r.length-de.Constants.ENDHDR,C=Math.max(0,h-65535),i=C,S=r.length,E=-1,w=0;for(typeof a.trailingSpace=="boolean"&&a.trailingSpace&&(C=0),h;h>=i;h--)if(r[h]===80){if(r.readUInt32LE(h)===de.Constants.ENDSIG){E=h,w=h,S=h+de.Constants.ENDHDR,i=h-de.Constants.END64HDR;continue}if(r.readUInt32LE(h)===de.Constants.END64SIG){i=C;continue}if(r.readUInt32LE(h)===de.Constants.ZIP64SIG){E=h,S=h+de.readBigUInt64LE(r,h+de.Constants.ZIP64SIZE)+de.Constants.ZIP64LEAD;break}}if(E==-1)throw de.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(E,S)),o.commentLength&&(s=r.slice(w+de.Constants.ENDHDR)),f&&d()}function y(){t.length>1&&!p&&t.sort((f,h)=>f.entryName.toLowerCase().localeCompare(h.entryName.toLowerCase()))}return{get entries(){return l||d(),t.filter(f=>!u.has(f))},get comment(){return g.decode(s)},set comment(f){s=de.toBuffer(f,g.encode),o.commentLength=s.length},getEntryCount:function(){return l?t.length:o.diskEntries},forEach:function(f){this.entries.forEach(f)},getEntry:function(f){return l||d(),n[f]||null},setEntry:function(f){l||d(),t.push(f),n[f.entryName]=f,o.totalEntries=t.length},deleteFile:function(f,h=!0){l||d();let C=n[f];this.getEntryChildren(C,h).map(S=>S.entryName).forEach(this.deleteEntry)},deleteEntry:function(f){l||d();let h=n[f],C=t.indexOf(h);C>=0&&(t.splice(C,1),delete n[f],o.totalEntries=t.length)},getEntryChildren:function(f,h=!0){if(l||d(),typeof f=="object")if(f.isDirectory&&h){let C=[],i=f.entryName;for(let S of t)S.entryName.startsWith(i)&&C.push(S);return C}else return[f];return[]},getChildCount:function(f){if(f&&f.isDirectory){let h=this.getEntryChildren(f);return h.includes(f)?h.length-1:h.length}return 0},compressToBuffer:function(){l||d(),y();let f=[],h=[],C=0,i=0;o.size=0,o.offset=0;let S=0;for(let A of this.entries){let _=A.getCompressedData();A.header.offset=i;let O=A.packLocalHeader(),k=O.length+_.length;i+=k,f.push(O),f.push(_);let R=A.packCentralHeader();h.push(R),o.size+=R.length,C+=k+R.length,S++}C+=o.mainHeaderSize,o.offset=i,o.totalEntries=S,i=0;let E=Buffer.alloc(C);for(let A of f)A.copy(E,i),i+=A.length;for(let A of h)A.copy(E,i),i+=A.length;let w=o.toBinary();return s&&s.copy(w,de.Constants.ENDHDR),w.copy(E,i),r=E,l=!1,E},toAsyncBuffer:function(f,h,C,i){try{l||d(),y();let S=[],E=[],w=0,A=0,_=0;o.size=0,o.offset=0;let O=function(k){if(k.length>0){let R=k.shift(),D=R.entryName+R.extra.toString();C&&C(D),R.getCompressedDataAsync(function(j){i&&i(D),R.header.offset=A;let V=R.packLocalHeader(),q=V.length+j.length;A+=q,S.push(V),S.push(j);let ee=R.packCentralHeader();E.push(ee),o.size+=ee.length,w+=q+ee.length,_++,O(k)})}else{w+=o.mainHeaderSize,o.offset=A,o.totalEntries=_,A=0;let R=Buffer.alloc(w);S.forEach(function(j){j.copy(R,A),A+=j.length}),E.forEach(function(j){j.copy(R,A),A+=j.length});let D=o.toBinary();s&&s.copy(D,de.Constants.ENDHDR),D.copy(R,A),r=R,l=!1,f(R)}};O(Array.from(this.entries))}catch(S){h(S)}}}}});var Os=Z((Dc,xs)=>{"use strict";var X=ct(),K=require("path"),zi=Hr(),Zi=_s(),Xe=(...r)=>X.findLast(r,e=>typeof e=="boolean"),Is=(...r)=>X.findLast(r,e=>typeof e=="string"),Ji=(...r)=>X.findLast(r,e=>typeof e=="function"),Ki={noSort:!1,readEntries:!1,method:X.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=X.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new X(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=X.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=X.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw X.Errors.INVALID_FILENAME();let o=new Zi(t,n),{canonical:l,sanitize:c,zipnamefix:u}=X;function a(d){if(d&&o){var m;if(typeof d=="string"&&(m=o.getEntry(K.posix.normalize(d))),typeof d=="object"&&typeof d.entryName<"u"&&typeof d.header<"u"&&(m=o.getEntry(d.entryName)),m)return m}return null}function p(d){let{join:m,normalize:y,sep:f}=K.posix;return m(K.isAbsolute(d)?"/":".",y(f+d.split("\\").join(f)+f))}function g(d){return d instanceof RegExp?(function(m){return function(y){return m.test(y)}})(d):typeof d!="function"?()=>!0:d}let I=(d,m)=>{let y=m.slice(-1);return y=y===s.sep?s.sep:"",K.relative(d,m)+y};return{readFile:function(d,m){var y=a(d);return y&&y.getData(m)||null},childCount:function(d){let m=a(d);if(m)return o.getChildCount(m)},readFileAsync:function(d,m){var y=a(d);y?y.getDataAsync(m):m(null,"getEntry failed for:"+d)},readAsText:function(d,m){var y=a(d);if(y){var f=y.getData();if(f&&f.length)return f.toString(m||"utf8")}return""},readAsTextAsync:function(d,m,y){var f=a(d);f?f.getDataAsync(function(h,C){if(C){m(h,C);return}h&&h.length?m(h.toString(y||"utf8")):m("")}):m("")},deleteFile:function(d,m=!0){var y=a(d);y&&o.deleteFile(y.entryName,m)},deleteEntry:function(d){var m=a(d);m&&o.deleteEntry(m.entryName)},addZipComment:function(d){o.comment=d},getZipComment:function(){return o.comment||""},addZipEntryComment:function(d,m){var y=a(d);y&&(y.comment=m)},getZipEntryComment:function(d){var m=a(d);return m&&m.comment||""},updateFile:function(d,m){var y=a(d);y&&y.setData(m)},addLocalFile:function(d,m,y,f){if(s.fs.existsSync(d)){m=m?p(m):"";let h=K.win32.basename(K.win32.normalize(d));m+=y||h;let C=s.fs.statSync(d),i=C.isFile()?s.fs.readFileSync(d):Buffer.alloc(0);C.isDirectory()&&(m+=s.sep),this.addFile(m,i,f,C)}else throw X.Errors.FILE_NOT_FOUND(d)},addLocalFileAsync:function(d,m){d=typeof d=="object"?d:{localPath:d};let y=K.resolve(d.localPath),{comment:f}=d,{zipPath:h,zipName:C}=d,i=this;s.fs.stat(y,function(S,E){if(S)return m(S,!1);h=h?p(h):"";let w=K.win32.basename(K.win32.normalize(y));if(h+=C||w,E.isFile())s.fs.readFile(y,function(A,_){return A?m(A,!1):(i.addFile(h,_,f,E),setImmediate(m,void 0,!0))});else if(E.isDirectory())return h+=s.sep,i.addFile(h,Buffer.alloc(0),f,E),setImmediate(m,void 0,!0)})},addLocalFolder:function(d,m,y){if(y=g(y),m=m?p(m):"",d=K.normalize(d),s.fs.existsSync(d)){let f=s.findFiles(d),h=this;if(f.length)for(let C of f){let i=K.join(m,I(d,C));y(i)&&h.addLocalFile(C,K.dirname(i))}}else throw X.Errors.FILE_NOT_FOUND(d)},addLocalFolderAsync:function(d,m,y,f){f=g(f),y=y?p(y):"",d=K.normalize(d);var h=this;s.fs.open(d,"r",function(C){if(C&&C.code==="ENOENT")m(void 0,X.Errors.FILE_NOT_FOUND(d));else if(C)m(void 0,C);else{var i=s.findFiles(d),S=-1,E=function(){if(S+=1,S<i.length){var w=i[S],A=I(d,w).split("\\").join("/");A=A.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),f(A)?s.fs.stat(w,function(_,O){_&&m(void 0,_),O.isFile()?s.fs.readFile(w,function(k,R){k?m(void 0,k):(h.addFile(y+A,R,"",O),E())}):(h.addFile(y+A+"/",Buffer.alloc(0),"",O),E())}):process.nextTick(()=>{E()})}else m(!0,void 0)};E()}})},addLocalFolderAsync2:function(d,m){let y=this;d=typeof d=="object"?d:{localPath:d},localPath=K.resolve(p(d.localPath));let{zipPath:f,filter:h,namefix:C}=d;h instanceof RegExp?h=(function(E){return function(w){return E.test(w)}})(h):typeof h!="function"&&(h=function(){return!0}),f=f?p(f):"",C=="latin1"&&(C=E=>E.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof C!="function"&&(C=E=>E);let i=E=>K.join(f,C(I(localPath,E))),S=E=>K.win32.basename(K.win32.normalize(C(E)));s.fs.open(localPath,"r",function(E){E&&E.code==="ENOENT"?m(void 0,X.Errors.FILE_NOT_FOUND(localPath)):E?m(void 0,E):s.findFilesAsync(localPath,function(w,A){if(w)return m(w);A=A.filter(_=>h(i(_))),A.length||m(void 0,!1),setImmediate(A.reverse().reduce(function(_,O){return function(k,R){if(k||R===!1)return setImmediate(_,k,!1);y.addLocalFileAsync({localPath:O,zipPath:K.dirname(i(O)),zipName:S(O)},_)}},m))})})},addLocalFolderPromise:function(d,m){return new Promise((y,f)=>{this.addLocalFolderAsync2(Object.assign({localPath:d},m),(h,C)=>{h&&f(h),C&&y(this)})})},addFile:function(d,m,y,f){d=u(d);let h=a(d),C=h!=null;C||(h=new zi(n),h.entryName=d),h.comment=y||"";let i=typeof f=="object"&&f instanceof s.fs.Stats;i&&(h.header.time=f.mtime);var S=h.isDirectory?16:0;let E=h.isDirectory?16384:32768;return i?E|=4095&f.mode:typeof f=="number"?E|=4095&f:E|=h.isDirectory?493:420,S=(S|E<<16)>>>0,h.attr=S,h.setData(m),C||o.setEntry(h),h},getEntries:function(d){return o.password=d,o?o.entries:[]},getEntry:function(d){return a(d)},getEntryCount:function(){return o.getEntryCount()},forEach:function(d){return o.forEach(d)},extractEntryTo:function(d,m,y,f,h,C){f=Xe(!1,f),h=Xe(!1,h),y=Xe(!0,y),C=Is(h,C);var i=a(d);if(!i)throw X.Errors.NO_ENTRY();var S=l(i.entryName),E=c(m,C&&!i.isDirectory?C:y?S:K.basename(S));if(i.isDirectory){var w=o.getEntryChildren(i);return w.forEach(function(O){if(O.isDirectory)return;var k=O.getData();if(!k)throw X.Errors.CANT_EXTRACT_FILE();var R=l(O.entryName),D=c(m,y?R:K.basename(R));let j=h?O.header.fileAttr:void 0;s.writeFileTo(D,k,f,j)}),!0}var A=i.getData(o.password);if(!A)throw X.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(E)&&!f)throw X.Errors.CANT_OVERRIDE();let _=h?d.header.fileAttr:void 0;return s.writeFileTo(E,A,f,_),!0},test:function(d){if(!o)return!1;for(var m in o.entries)try{if(m.isDirectory)continue;var y=o.entries[m].getData(d);if(!y)return!1}catch{return!1}return!0},extractAllTo:function(d,m,y,f){if(y=Xe(!1,y),f=Is(y,f),m=Xe(!1,m),!o)throw X.Errors.NO_ZIP();o.entries.forEach(function(h){var C=c(d,l(h.entryName));if(h.isDirectory){s.makeDir(C);return}var i=h.getData(f);if(!i)throw X.Errors.CANT_EXTRACT_FILE();let S=y?h.header.fileAttr:void 0;s.writeFileTo(C,i,m,S);try{s.fs.utimesSync(C,h.header.time,h.header.time)}catch{throw X.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(d,m,y,f){if(f=Ji(m,y,f),y=Xe(!1,y),m=Xe(!1,m),!f)return new Promise((E,w)=>{this.extractAllToAsync(d,m,y,function(A){A?w(A):E(this)})});if(!o){f(X.Errors.NO_ZIP());return}d=K.resolve(d);let h=E=>c(d,K.normalize(l(E.entryName))),C=(E,w)=>new Error(E+': "'+w+'"'),i=[],S=[];o.entries.forEach(E=>{E.isDirectory?i.push(E):S.push(E)});for(let E of i){let w=h(E),A=y?E.header.fileAttr:void 0;try{s.makeDir(w),A&&s.fs.chmodSync(w,A),s.fs.utimesSync(w,E.header.time,E.header.time)}catch{f(C("Unable to create folder",w))}}S.reverse().reduce(function(E,w){return function(A){if(A)E(A);else{let _=K.normalize(l(w.entryName)),O=c(d,_);w.getDataAsync(function(k,R){if(R)E(R);else if(!k)E(X.Errors.CANT_EXTRACT_FILE());else{let D=y?w.header.fileAttr:void 0;s.writeFileToAsync(O,k,m,D,function(j){j||E(C("Unable to write file",O)),s.fs.utimes(O,w.header.time,w.header.time,function(V){V?E(C("Unable to set times",O)):E()})})}})}}},f)()},writeZip:function(d,m){if(arguments.length===1&&typeof d=="function"&&(m=d,d=""),!d&&n.filename&&(d=n.filename),!!d){var y=o.compressToBuffer();if(y){var f=s.writeFileTo(d,y,!0);typeof m=="function"&&m(f?null:new Error("failed"),"")}}},writeZipPromise:function(d,m){let{overwrite:y,perm:f}=Object.assign({overwrite:!0},m);return new Promise((h,C)=>{!d&&n.filename&&(d=n.filename),d||C("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let S=E=>E?h(E):C("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(d,i,y,f,S)},C)})},toBufferPromise:function(){return new Promise((d,m)=>{o.toAsyncBuffer(d,m)})},toBuffer:function(d,m,y,f){return typeof d=="function"?(o.toAsyncBuffer(d,m,y,f),null):o.compressToBuffer()}}}});var Gs={};gt(Gs,{enableTelemetryHook:()=>qs,registerConfig:()=>Jr});function Zr(){let r=process.env.SC_PROFILE;return r?(0,je.join)((0,pt.homedir)(),".config","shared-context","profiles",r):(0,je.join)((0,pt.homedir)(),".config","shared-context")}function qs(){try{let r=(0,je.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,je.join)(Zr(),"manifest.json"),c="";try{let g=(JSON.parse(e(l,"utf8")).installations||[]).find(I=>I.slug==="telemetry"||I.installPath?.includes("hooks/telemetry"));g?.installPath&&(c=(0,je.join)((0,pt.homedir)(),".config","shared-context",g.installPath,"scripts","telemetry.js"))}catch{}if((!c||!(0,Be.existsSync)(c))&&(c=(0,je.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,je.join)(Zr(),"usage.jsonl");try{(0,Be.existsSync)(r)&&(0,Be.unlinkSync)(r)}catch{}try{let e=(0,je.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()?P("config","INVALID_VALUE","Telemetry value must be on or off"):v("Usage: shared-context-ai config set telemetry on|off");return}o?(Sa(),x()?N("config",{key:"telemetry",value:!1}):b("Telemetry disabled. Usage data and hooks removed.")):(vt({telemetry:!0}),qs(),x()?N("config",{key:"telemetry",value:!0}):b("Telemetry enabled. Usage data will be collected and uploaded."));return}x()?P("config","UNKNOWN_KEY",`Unknown config key: ${t}`):v(`Unknown config key: ${t}. Available: telemetry`)}),e.command("get [key]").description("Show configuration values").action(t=>{let n=_e();if(t==="telemetry"){let s=n.telemetry??!1;x()?N("config",{key:"telemetry",value:s}):b(`telemetry: ${s?"on":"off"}`);return}if(t){x()?P("config","UNKNOWN_KEY",`Unknown config key: ${t}`):v(`Unknown config key: ${t}`);return}x()?N("config",{telemetry:n.telemetry??!1}):b(`telemetry: ${n.telemetry?"on":"off"}`)})}var Be,je,pt,Vs,Kr=pe(()=>{"use strict";Be=require("fs"),je=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 _a(){try{return Yr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Qr(){return Xr===void 0&&(Xr=Aa()||_a()),Xr}var Yr,Xr,Xs=pe(()=>{"use strict";Yr=me(require("fs"),1)});function nt(){return en===void 0&&(en=Ia()||Qr()),en}var Ys,en,Ia,tn=pe(()=>{"use strict";Ys=me(require("fs"),1);Xs();Ia=()=>{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,_t,xa,Oa,on,to=pe(()=>{"use strict";sn=me(require("process"),1),_t=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 _t.default.access(t,_t.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await _t.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 Io={};gt(Io,{apps:()=>ze,default:()=>La,openApp:()=>$a});async function ja(){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 Da(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,_o,yn,rr,Fa,Da,pn,Eo,mt,Co,wo,It,Na,$a,ze,La,xo=pe(()=>{"use strict";mn=me(require("process"),1),hn=require("buffer"),gn=me(require("path"),1),Ao=require("url"),_o=require("util"),yn=me(require("child_process"),1),rr=me(require("fs/promises"),1);to();ro();So();tn();Fa={},Da=(0,_o.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},It=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return wo(r.app,c=>It({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return wo(e,c=>It({...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 ja():await dn();if(a.id in c){let p=c[a.id];return e==="browserPrivate"&&t.push(u[p]),It({...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 It({...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 It({...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(`
35
- `)+`
36
- `,"utf8")}catch{}}async function Zo(r=!1){if(!_e().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&&b(`Uploaded ${s} usage event${s===1?"":"s"}`)}return{uploaded:n.data?.accepted??0}}return!r&&!x()&&v("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"),Ee=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,Ee.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,Ee.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,Ee.join)(process.cwd(),r.dir,r.skillsSubdir):(0,Ee.join)((0,Le.homedir)(),r.dir,r.skillsSubdir)}function te(r,e){return e?(0,Ee.join)(process.cwd(),r.dir,"agents"):(0,Ee.join)((0,Le.homedir)(),r.dir,"agents")}function fe(r,e){return e?(0,Ee.join)(process.cwd(),".mcp.json"):r.id==="claude-code"?(0,Ee.join)((0,Le.homedir)(),".claude.json"):r.id==="cursor"?(0,Ee.join)((0,Le.homedir)(),".cursor","mcp.json"):(0,Ee.join)(process.cwd(),".mcp.json")}function Ce(r,e){return e?(0,Ee.join)(process.cwd(),r.dir,"settings.json"):(0,Ee.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"),Ds=".shared-context",js="project.json";function we(){let r=(0,Mt.join)(process.cwd(),Ds,js);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(),Ds);(0,He.mkdirSync)(e,{recursive:!0}),(0,He.writeFileSync)((0,Mt.join)(e,js),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 W(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(!B().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=Ce(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()?P("install","NO_AGENTS",i):v(i),process.exit(1)}let l=L(),u=await G(`${l?"/api/cli/resource":"/api/public/resource"}/${e}`);u.ok||(x()?P("install",u.error.code,u.error.message):v(`Install failed: ${u.error.message}`),process.exit(1));let a=u.data,p=a.resource.slug||a.resource.id,g=Br(a),I,d="decomposed",m;if(a.resource.resourceType==="agent"){let i=te(o,!!s.project),S=Ns(i,p,a.resource.id,a);S.renamed&&(p=S.slug,g=Br({...a,resource:{...a.resource,slug:p}}),x()||b(`Note: Renamed to "${p}" (collision with existing resource)`)),I=(0,xe.join)(i,p);try{W(I,a.files)}catch(E){x()?P("install","WRITE_FAILED",`Failed to write files: ${E}`):v(`Failed to write files: ${E}`),process.exit(1)}}else if(a.resource.resourceType==="mcp"){I="";try{Ut(o,!!s.project,a)}catch(i){x()?P("install","WRITE_FAILED",`Failed to install MCP config: ${i}`):v(`Failed to install MCP config: ${i}`),process.exit(1)}}else if(a.resource.resourceType==="hook"){I="";try{Xi(o,!!s.project,a,g)}catch(i){x()?P("install","WRITE_FAILED",`Failed to install hook config: ${i}`):v(`Failed to install hook config: ${i}`),process.exit(1)}}else{let i=H(o,!!s.project);if(a.resource.resourceType!=="collection"){let S=Ns(i,p,a.resource.id,a);S.renamed&&(p=S.slug,g=Br({...a,resource:{...a.resource,slug:p}}),x()||b(`Note: Renamed to "${p}" (collision with existing resource)`))}I=(0,xe.join)(i,p);try{if(a.resource.resourceType==="collection"){let S=ut(o.id);if(S)try{let E=a.resource.slug||a.resource.id,w=a.resource.orgSlug||"",A=Ft(o.id),_=l?`/api/cli/resource/collections/${w}/${E}?format=plugin&platform=${A}`:`/api/public/resource/collections/${w}/${E}?format=plugin&platform=${A}`,O=await Lt(_,E);(0,$s.execSync)(`${S} plugin install "${O}"`,{stdio:"pipe"}),I=O,d="plugin",m=O,x()||b(`Installed as native ${S} plugin`)}catch(E){x()||v(`Native plugin install failed, falling back to decomposed: ${E}`);let A=await Te(o).install(a,s.project?"project":"user",o);I=A.installDir;for(let _ of A.warnings)x()||v(`Warning: ${_}`)}else{let w=await Te(o).install(a,s.project?"project":"user",o);if(I=w.installDir,!x())for(let A of w.warnings)v(`Warning: ${A}`)}}else W(I,a.files)}catch(S){x()?P("install","WRITE_FAILED",`Failed to write files: ${S}`):v(`Failed to write files: ${S}`),process.exit(1)}}let y;if(l&&a.resource.latestSha){let i=await $("/api/cli/install",{resourceId:a.resource.id,agentPlatform:o.platform,installedSha:a.resource.latestSha});i.ok||(y=`Could not record install on server: ${i.error.message}`,x()||v(`Warning: ${y}`))}let f=s.project?we():null;f&&l&&await $(`/api/cli/projects/${f.projectId}/resources`,{resourceId:a.resource.id}).catch(()=>{});let h={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},C=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,...C?{pluginFormat:h[o.id]||"directory",memberCount:a.memberResources?.length,installMode:d,pluginDir:m}:{},...f?{projectId:f.projectId}:{}}),a.memberResources&&a.resource.resourceType==="collection"){if(d==="decomposed")for(let i of a.memberResources){let S=i.slug||i.id,E=Ls[i.resourceType]||i.resourceType+"s",w=a.resource.orgSlug?`${a.resource.orgSlug}/`:"",A=`${E}/${w}${S}`;ae({resourceId:i.id,slug:S,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:I||void 0,files:a.files.length,...a.resource.resourceType==="mcp"?{mcpConfigPath:fe(o,!!s.project)}:{},...a.resource.resourceType==="hook"?{settingsPath:Ce(o,!!s.project)}:{},...a.memberResources?{memberResources:a.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...y&&{warning:y}});else{if(a.resource.resourceType==="mcp"?b(`Installed MCP "${a.resource.title}" to ${fe(o,!!s.project)}`):a.resource.resourceType==="hook"?b(`Installed hook "${a.resource.title}" to ${Ce(o,!!s.project)}`):a.memberResources&&a.memberResources.length>0?b(`Installed "${a.resource.title}" (${a.memberResources.length} resources)`):b(`Installed "${a.resource.title}" to ${I}`),a.resource.resourceType!=="mcp"&&a.resource.resourceType!=="hook"&&!(a.memberResources&&a.memberResources.length>0)&&b(` ${a.files.length} file${a.files.length===1?"":"s"} written`),a.memberResources&&a.memberResources.length>0){let i={};for(let E of a.memberResources){let w=E.resourceType||"other";i[w]||(i[w]=[]),i[w].push(E.title)}let S={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};b("");for(let[E,w]of Object.entries(i)){let A=S[E]||E;b(` ${A}: ${w.join(", ")}`)}}l||(b(""),b("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"),I=g>0?u[g-1]:u[1];o[I]=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(d=>!d.path.includes("/")),I=s.mainFiles.filter(d=>d.path.includes("/"));if(g.length>0){let d=g.find(m=>m.path==="README.md");d&&g.push({path:"SKILL.md",content:ea(e,d.content)}),W(a,g),p+=g.length}I.length>0&&(W(c,I),p+=I.length)}if(s.agentFiles.length>0){let g=te(n,o);W(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(Ce(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"),I=g>0?u[g-1]:u[1];o[I]=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(d=>!d.path.includes("/")),I=s.mainFiles.filter(d=>d.path.includes("/"));if(g.length>0){let d=g.find(m=>m.path==="README.md");d&&g.push({path:"SKILL.md",content:ia(e,d.content)}),W(a,g),p+=g.length}I.length>0&&(W(c,I),p+=I.length)}if(s.agentFiles.length>0){let g=te(n,o);W(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(Ce(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 I=a.indexOf("resources"),d=I>0?a[I-1]:a[1];o[d]=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(I=>!I.path.includes("/")),g=s.mainFiles.filter(I=>I.path.includes("/"));if(p.length>0){let I=p.find(d=>d.path==="README.md");I&&p.push({path:"SKILL.md",content:la(e,I.content)}),W(u,p),a+=p.length}g.length>0&&(W(l,g),a+=g.length)}if(s.agentFiles.length>0){let p=te(n,o);W(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)+`
46
- `,"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(I=>!I.path.includes("/")),g=s.mainFiles.filter(I=>I.path.includes("/"));if(p.length>0){let I=p.find(d=>d.path==="README.md");I&&p.push({path:"SKILL.md",content:fa(e,I.content)}),W(u,p),a+=p.length}g.length>0&&(W(l,g),a+=g.length)}if(s.agentFiles.length>0){let p=te(n,o);W(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(I=>!I.path.includes("/")),g=s.mainFiles.filter(I=>I.path.includes("/"));p.length>0&&(W(u,p),a+=p.length),g.length>0&&(W(l,g),a+=g.length)}if(s.agentFiles.length>0){let p=te(n,o);W(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=`---
50
- name: Context Manager
51
- description: "Your AI chief of staff \u2014 distills expert knowledge into resources, finds off-the-shelf solutions, and manages your working context"
52
- tools:
53
- - Read
54
- - Write
55
- - Edit
56
- - Bash
57
- - Grep
58
- - Glob
59
- - Agent
60
- - WebSearch
61
- ---
62
-
63
- # Context Manager
64
-
65
- You are a chief of staff for AI automation. You help knowledge workers build their AI workforce \u2014 distilling their expertise into well-structured resources (agents, skills, hooks, collections) and sourcing off-the-shelf solutions from the Shared Context library when custom building isn't needed.
66
-
67
- ## Build vs Source: When to Search the Library First
68
-
69
- **Search the library first** when:
70
- - The user wants a tool connector or MCP (e.g., "I need to connect to Slack")
71
- - The user wants a common task automated but doesn't have strong opinions about *how*
72
- - The user doesn't have the domain expertise to teach
73
- - The task is generic and not company-specific
74
-
75
- **Build custom** when:
76
- - The user has domain expertise they want to encode ("here's how I do code reviews")
77
- - The workflow is company-specific with unique steps, templates, or constraints
78
- - Existing library resources are close but miss critical requirements
79
- - The task requires specific judgment calls that only this user can define
80
-
81
- ## CLI Quick Reference
82
-
83
- | Action | Command |
84
- |--------|---------|
85
- | Search | \`npx shared-context-ai search "query"\` |
86
- | Preview | \`npx shared-context-ai preview <installPath>\` |
87
- | Install | \`npx shared-context-ai install <installPath>\` |
88
- | List installed | \`npx shared-context-ai list\` |
89
- | Sync state | \`npx shared-context-ai sync\` |
90
- | Check updates | \`npx shared-context-ai check\` |
91
- | Update all | \`npx shared-context-ai update\` |
92
- | Uninstall | \`npx shared-context-ai uninstall <installPath>\` |
93
- | Status | \`npx shared-context-ai status\` |
94
-
95
- ### How to Search Effectively
96
-
97
- Use specific keywords. Separate multiple keywords with commas \u2014 the search returns results matching **all** terms.
98
-
99
- \`\`\`bash
100
- npx shared-context-ai search "testing"
101
- npx shared-context-ai search "react,testing"
102
- npx shared-context-ai search "code review" --type skill
103
- npx shared-context-ai search "database" --type mcp
104
- npx shared-context-ai search "deployment" --tag devops
105
- \`\`\`
106
-
107
- ### Install Paths
108
-
109
- \`\`\`bash
110
- npx shared-context-ai install skills/acme/api-testing
111
- npx shared-context-ai install agents/acme/code-reviewer
112
- npx shared-context-ai install hooks/acme/pre-commit-lint
113
- npx shared-context-ai install mcps/acme/postgres-mcp
114
- npx shared-context-ai install collections/acme/devops-bundle
115
- \`\`\`
116
-
117
- ## Building Resources
118
-
119
- When building custom resources, follow these patterns:
120
-
121
- **Skills** \u2014 Specific repeatable processes with defined inputs/outputs. Files: \`skills/{slug}/SKILL.md\`
122
- **Agents** \u2014 Ongoing responsibilities that own a domain. Files: \`agents/{slug}/{slug}.md\`
123
- **Hooks** \u2014 Automatic event responses (SessionStart, PreToolUse, etc.). Files: \`hooks/{slug}/hook.json\`
124
-
125
- ### Build Process
126
-
127
- 1. **Interview** \u2014 Ask targeted questions to understand the goal, expertise, and constraints
128
- 2. **Build** \u2014 Create resource files with supporting sub-files and filesystem architecture
129
- 3. **Test** \u2014 Run a real scenario, observe output, refine based on feedback
130
- 4. **Wire** \u2014 Check existing resources for integration opportunities
131
-
132
- ### Key Principles
133
-
134
- - **Distillation, not generation** \u2014 Every instruction should capture something an LLM couldn't know without being told
135
- - **Specificity over comprehensiveness** \u2014 Only include instructions that meaningfully change Claude's output
136
- - **Filesystem as memory** \u2014 Design persistent storage so resources accumulate knowledge over time
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(`---
139
- `)&&!r.startsWith(`---\r
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 I=0;I<a.length;I++){let d=a[I];if(p&&/^\s+-\s/.test(d)){let h=d.replace(/^\s+-\s/,"").trim();if(h){let C=dt(h);g?u[p].push(C):l[p].push(C)}continue}p=null,g=!1;let m=d.indexOf(":");if(m===-1)continue;let y=d.slice(0,m).trim(),f=d.slice(m+1).trim();if(!f&&y&&I+1<a.length&&/^\s+-\s/.test(a[I+1])){p=y,c.has(y)?(g=!0,u[y]=[]):(g=!1,l[y]=[]);continue}y==="name"||y==="title"?e.name=dt(f):y==="description"?e.description=dt(f):y==="skill_class"?e.skillClass=dt(f):y==="service"?e.service=dt(f):y&&f&&(o[y]=dt(f))}return u.requires?.length&&(e.requires=u.requires),u.tools?.length&&(e.tools=u.tools),Object.keys(o).length&&(e.fields=o),Object.keys(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 De(r){let e=ya(r);return`sha256:${(0,Ws.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Ie(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(d,m){let y=[],f=[];for(let h of Hs){let C=(0,z.join)(d,h.folder);if(!(0,M.existsSync)(C)||!At(C))continue;let i=m?`${m}/${h.folder}`:h.folder;if(h.folder==="files"){for(let S of zr(C)){if(!S.endsWith(".md"))continue;let E=(0,z.join)(C,S),w=(0,M.readFileSync)(E,"utf-8"),A=tt(w),_=A.name||(0,z.basename)(S,".md"),O=`${i}/${(0,z.basename)(S,".md")}`;y.push({importPath:O,resourceType:"file",title:_,description:A.description||null,body:A.body,bodyHash:De(w),metadata:{}})}continue}if(h.mainFile===null)for(let S of zr(C)){if(!S.endsWith(".md"))continue;let E=(0,z.basename)(S,".md"),w=`${i}/${E}`;if(At((0,z.join)(C,E)))continue;let A=(0,M.readFileSync)((0,z.join)(C,S),"utf-8"),_=tt(A),O=_.name||Ie(E),k={};_.skillClass&&(k.skillClass=_.skillClass),_.service&&(k.service=_.service),_.requires?.length&&(k.requires=_.requires),_.tools?.length&&(k.tools=_.tools),_.fields&&Object.keys(_.fields).length&&(k.fields=_.fields),h.folder==="commands"&&(k.fields||(k.fields={}),k.fields["user-invocable"]="true"),y.push({importPath:w,resourceType:h.resourceType,title:O,description:_.description||null,body:_.body,bodyHash:De(A),metadata:k})}for(let S of Gr(C)){let E=h.mainFile||`${S}.md`,w=(0,z.join)(C,S,E);if(!(0,M.existsSync)(w)){if(h.mainFile===null)for(let V of Gr((0,z.join)(C,S))){let q=`${V}.md`,ee=(0,z.join)(C,S,V,q);if(!(0,M.existsSync)(ee))continue;let Je=(0,M.readFileSync)(ee,"utf-8"),ye=tt(Je),ri=ye.name||Ie(V),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),y.push({importPath:`${i}/${V}`,resourceType:h.resourceType,title:ri,description:ye.description||null,body:ye.body,bodyHash:De(Je),metadata:ot})}continue}let A=(0,M.readFileSync)(w,"utf-8"),_=`${i}/${S}`,O,k,R,D={},j=null;if(h.resourceType==="hook"||h.resourceType==="mcp"){try{let V=JSON.parse(A);O=V.name||Ie(S),k=V.description||null}catch{O=Ie(S),k=null}R=A}else if(h.resourceType==="collection"){let V=(0,z.join)(C,S,Zt,Jt);if((0,M.existsSync)(V))try{let q=JSON.parse((0,M.readFileSync)(V,"utf-8"));O=q.name||Ie(S),k=q.description||null,R=A,q.resources&&Array.isArray(q.resources)&&f.push({collectionImportPath:_,memberImportPaths:q.resources.map(ee=>{let Je=ee.split("/");return Je.length>=3?`${Je[0]}/${Je[Je.length-1]}`:ee})})}catch{O=Ie(S),k=null,R=A}else j=tt(A),O=j.name||Ie(S),k=j.description||null,R=j.body,j.arrayFields?.resources&&f.push({collectionImportPath:_,memberImportPaths:j.arrayFields.resources.map(q=>{let ee=q.split("/");return ee.length>=3?`${ee[0]}/${ee[ee.length-1]}`:q})})}else j=tt(A),O=j.name||Ie(S),k=j.description||null,R=j.body,j.skillClass&&(D.skillClass=j.skillClass),j.service&&(D.service=j.service),j.requires?.length&&(D.requires=j.requires),j.tools?.length&&(D.tools=j.tools),j.fields&&Object.keys(j.fields).length&&(D.fields=j.fields);h.folder==="commands"&&(D.fields||(D.fields={}),D.fields["user-invocable"]="true"),y.push({importPath:_,resourceType:h.resourceType,title:O,description:k,body:R,bodyHash:De(A),metadata:D})}}return{resources:y,memberships:f}}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 d of u)if((0,M.existsSync)(d))try{let m=JSON.parse((0,M.readFileSync)(d,"utf-8"));if(m.mcpServers&&typeof m.mcpServers=="object")for(let[y,f]of Object.entries(m.mcpServers)){let h=`mcps/${y}`;if(t.some(S=>S.importPath===h))continue;let C=Ie(y),i=JSON.stringify({name:C,description:`MCP server: ${y}`,mcpServers:{[y]:f}},null,2);t.push({importPath:h,resourceType:"mcp",title:C,description:`MCP server: ${y}`,body:i,bodyHash:De(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,M.existsSync)(e.settingsPath))try{let d=JSON.parse((0,M.readFileSync)(e.settingsPath,"utf-8"));if(d.hooks&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)){let m={};for(let[y,f]of Object.entries(d.hooks))if(Array.isArray(f))for(let h of f){if(!h||typeof h!="object")continue;let C=h,i=C._sc;if(!i)continue;m[i]||(m[i]={}),m[i][y]||(m[i][y]=[]);let{_sc:S,...E}=C;m[i][y].push(E)}for(let[y,f]of Object.entries(m)){let h=y;if(t.some(E=>E.importPath===h))continue;let C=y.split("/").pop()||y,i=Ie(C),S=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:f},null,2);t.push({importPath:h,resourceType:"hook",title:i,description:`Hook: ${i}`,body:S,bodyHash:De(S),metadata:{}})}}}catch{}for(let d of qr){if(d.path===Bs)continue;let m=(0,z.join)(r,d.path);if((0,M.existsSync)(m)){try{let y=JSON.parse((0,M.readFileSync)(m,"utf-8"));if(s=s||y.name||void 0,o=d.formatLabel,!t.some(f=>f.resourceType==="collection")){let f=t.filter(E=>E.resourceType!=="collection").map(E=>({resourceRef:E.importPath})),h=d.converter(y,f),C=(0,z.join)(r,"README.md"),i=(0,M.existsSync)(C)?(0,M.readFileSync)(C,"utf-8"):"",S="collections/_root";t.push({importPath:S,resourceType:"collection",title:Ie(h.name),description:h.description||null,body:i,bodyHash:De(i),metadata:{},manifestMetadata:{...h.author?{author:h.author}:{},...h.homepage?{homepage:h.homepage}:{},...h.license?{license:h.license}:{}}}),h.resources.length>0&&n.push({collectionImportPath:S,memberImportPaths:h.resources})}}catch{}break}}{let f=function(h,C,i){if(!(i>4))for(let S of Gr(h)){if(y.has(S))continue;let E=(0,z.join)(h,S),w=C?`${C}/${S}`:S;for(let A of qr){if(A.path===Bs)continue;let _=(0,z.join)(E,A.path);if((0,M.existsSync)(_)){if(d.has(w))break;d.add(w);try{let O=JSON.parse((0,M.readFileSync)(_,"utf-8")),k=l(E,w);if(k.resources.length===0)break;t.push(...k.resources),n.push(...k.memberships);let R=k.resources.filter(ee=>ee.resourceType!=="collection").map(ee=>({resourceRef:ee.importPath})),D=A.converter(O,R),j=(0,z.join)(E,"README.md"),V=(0,M.existsSync)(j)?(0,M.readFileSync)(j,"utf-8"):"",q=`${w}/_collection`;t.push({importPath:q,resourceType:"collection",title:Ie(D.name),description:D.description||null,body:V,bodyHash:De(V),metadata:{},manifestMetadata:{...D.author?{author:D.author}:{},...D.homepage?{homepage:D.homepage}:{},...D.license?{license:D.license}:{}}}),n.push({collectionImportPath:q,memberImportPaths:k.resources.map(ee=>ee.importPath)}),s||(s=O.name||void 0),o||(o=A.formatLabel)}catch{}break}}f(E,w,i+1)}};var I=f;let d=new Set,m=new Set(Hs.map(h=>h.folder)),y=new Set([...m,"worktrees","plugins","node_modules","todos"]);f(r,"",0)}let p=(0,z.join)(r,"files");if((0,M.existsSync)(p)&&At(p)&&!t.some(d=>d.resourceType==="file"))for(let d of zr(p)){if(!d.endsWith(".md"))continue;let m=(0,z.join)(p,d),y=(0,M.readFileSync)(m,"utf-8"),f=tt(y),h=f.name||(0,z.basename)(d,".md"),C=`files/${(0,z.basename)(d,".md")}`;t.some(i=>i.importPath===C)||t.push({importPath:C,resourceType:"file",title:h,description:f.description||null,body:f.body,bodyHash:De(y),metadata:{}})}return{resources:[...t.filter(d=>d.resourceType!=="collection"),...t.filter(d=>d.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:_,agent:O,isProject:k}of e){let R=Kt(_,{settingsPath:Ce(O,k),mcpConfigPath:fe(O,k)});for(let D of R.resources)u.has(D.importPath)||(u.add(D.importPath),l.push({...D,scope:k?"project":"global"}));for(let D of R.collectionMemberships)u.has(`cm:${D.collectionImportPath}`)||(u.add(`cm:${D.collectionImportPath}`),c.push(D))}let a=l.map(_=>_.importPath),p=B(),g=new Set(p.installations.map(_=>_.installPath)),I=new Map;for(let _ of p.installations){let O=_.installPath.split("/"),k=O[0],R=O[O.length-1];I.has(k)||I.set(k,new Set),I.get(k).add(R)}let d=new Set(n),m=l.filter(_=>{if(g.has(_.importPath))return!1;let O=_.importPath.split("/"),k=O[0],R=O[O.length-1];return!((k==="mcps"||k==="hooks")&&I.get(k)?.has(R)||_.importPath.startsWith(".")||d.has(R)||_.importPath.startsWith("plugins/"))});for(let _ of m)_.description&&_.description.length>1e3&&(_.description=_.description.slice(0,997)+"...");let y=m.length,f=m.map(_=>({importPath:_.importPath,resourceType:_.resourceType,title:_.title}));if(m.length===0||o)return{imported:[],errors:0,projectRegistered:0,untrackedCount:y,discoveredPaths:a,untracked:f};let h={dryRun:!1,onConflict:"auto",visibility:"org",resources:m,collectionMemberships:c.length>0?c:void 0},C=await $("/api/cli/import",h,12e4);if(!C.ok)return{imported:[],errors:m.length,projectRegistered:0,untrackedCount:y,discoveredPaths:a,untracked:f};let i=[...C.data.created,...C.data.updated,...C.data.installed],S=new Map;for(let _ of l)S.set(_.importPath,_.scope);let E=we();for(let _ of i){if(!_.id)continue;let O=S.get(_.importPath)||"global";ae({resourceId:_.id,slug:_.slug||_.importPath.split("/").pop()||_.id,installPath:_.importPath,title:_.importPath.split("/").pop()||_.id,sha:_.commitSha||"",scope:O,agent:t,installedAt:new Date().toISOString(),resourceType:_.resourceType,serverSynced:!0,...O==="project"&&E?{projectId:E.projectId}:{}})}let w=0;if(s&&E){let _=[...i,...C.data.skipped];for(let O of _){let k=O.id||O.existingId;if(!k||S.get(O.importPath)!=="project")continue;let D=await $(`/api/cli/projects/${E.projectId}/resources`,{resourceId:k});D.ok&&D.data.added&&w++}}return{imported:i.map(_=>({resourceType:_.resourceType||_.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:_.slug||_.importPath.split("/").pop()||"",title:_.importPath.split("/").pop()||"",importPath:_.importPath,id:_.id})),errors:C.data.errors.length,projectRegistered:w,untrackedCount:y,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 B().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:f}=await Promise.resolve().then(()=>(ne(),Zn)),{saveAuth:h}=await Promise.resolve().then(()=>(ce(),Rt)),C=await f("/api/cli/auth",{code:n.code});C.ok?(h({token:C.data.token,email:C.data.user.email,orgId:C.data.org.id,orgSlug:C.data.org.slug,orgName:C.data.org.name,createdAt:new Date().toISOString()}),x()||b(`Authenticated as ${C.data.user.email}`)):L()?x()||b("Auth code already used, continuing with saved credentials."):(x()?P("init",C.error.code,C.error.message):v(`Auth failed: ${C.error.message}`),process.exit(1))}else L()||(x()?(P("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(v("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let f=ve(n.agent);if(!f){let h=`Unknown agent: ${n.agent}. Available: ${Fe().map(C=>C.id).join(", ")||"none detected"}`;x()?P("init","NO_AGENTS",h):v(h),process.exit(1)}s=[f]}else if(s=Fe(),s.length===0){let f=Me();x()?P("init","NO_AGENTS",f):v(f),process.exit(1)}let o=Ae(),l=Ea(),c;if(n.linkProject){if(!o?.token){let _="Authentication required for project linking. Run init with --code first.";x()?P("init","AUTH_REQUIRED",_):v(_),process.exit(1)}let f=s[0],h=await $("/api/cli/register-agent",{platform:f.platform,name:`CLI (${l})`});h.ok&&(c=h.data.connectionId);let C=await $(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});C.ok||(x()?P("init",C.error.code,C.error.message):v(`Failed to join project: ${C.error.message}`),process.exit(1));let{project:i,resources:S,members:E}=C.data;Ye({projectId:i.id,projectName:i.name,projectSlug:i.slug});let w=Te(f),A=[];for(let _ of S)try{let O=_.installPath,k=await G(`/api/cli/resource/${O}`);if(!k.ok)continue;let R=k.data;await w.install(R,"project",f),ae({resourceId:_.id,slug:_.slug||_.id,installPath:O,title:_.title,sha:_.latestSha||"",scope:"project",agent:f.id,installedAt:new Date().toISOString(),projectId:i.id}),_.latestSha&&await $("/api/cli/install",{resourceId:_.id,agentPlatform:f.platform,installedSha:_.latestSha}).catch(()=>{}),A.push({title:_.title,resourceType:_.resourceType})}catch{}if(await $(`/api/cli/projects/${i.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Tt({lastSyncAt:new Date().toISOString()}),x())N("init",{project:{id:i.id,name:i.name,slug:i.slug},agent:f.id,resourcesInstalled:A.length,memberCount:E.length});else{if(b(""),b(`Joined project: ${i.name}`),i.description&&b(`"${i.description}"`),b(""),A.length>0){b(`Installed ${A.length} resource${A.length===1?"":"s"}:`);let _={};for(let k of A)_[k.resourceType]||(_[k.resourceType]=[]),_[k.resourceType].push(k.title);let O={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[k,R]of Object.entries(_))b(` ${O[k]||k}: ${R.join(", ")}`)}else b("No resources to install (project is empty)");E.length>0&&(b(""),b(`Team (${E.length}): ${E.map(_=>_.name).join(", ")}`)),b(""),b("Quick reference:"),b(" shared-context-ai status View project sync status"),b(" shared-context-ai sync Check for resource updates")}return}let u=!1,a=(0,Ve.basename)(process.cwd());if(o?.token&&!we()&&a&&a!=="/")try{let f=await $("/api/cli/projects",{name:a});if(f.ok){let{id:h,name:C,slug:i}=f.data;Ye({projectId:h,projectName:C,projectSlug:i}),u=!0,x()||b(`Created project: ${C}`)}}catch{}let p=[],g={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let f of s){let h=!1,C=!1,i=[],S=[];if(o?.token){let E=await $("/api/cli/register-agent",{platform:f.platform,name:`CLI (${l})`});if(E.ok){if(!c){c=E.data.connectionId;let{saveAuth:w}=await Promise.resolve().then(()=>(ce(),Rt));w({...o,connectionId:c})}}else x()||v(`Warning: Could not register ${f.label} connection: ${E.error.message}`)}if(o?.token&&ba(f.id))C=!0,h=!0;else if(o?.token)try{let E=await G(`/api/cli/resource/${Yt}`);if(E.ok){let w=E.data,_=await Te(f).install(w,n.project?"project":"user",f);if(ae({resourceId:w.resource.id,slug:w.resource.slug||"context-manager",installPath:Yt,title:w.resource.title,sha:w.resource.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString(),pluginFormat:g[f.id]||"directory",memberCount:w.memberResources?.length}),w.resource.latestSha&&await $("/api/cli/install",{resourceId:w.resource.id,agentPlatform:f.platform,installedSha:w.resource.latestSha}).catch(()=>{}),w.memberResources)for(let O of w.memberResources){let k=O.slug||O.id,R=wa[O.resourceType]||O.resourceType+"s",D=O.orgSlug||w.resource.orgSlug,j=D?`${R}/${D}/${k}`:`${R}/${k}`;ae({resourceId:O.id,slug:k,installPath:j,title:O.title,sha:O.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString(),collectionId:w.resource.id}),i.push({title:O.title,resourceType:O.resourceType}),O.latestSha&&await $("/api/cli/install",{resourceId:O.id,agentPlatform:f.platform,installedSha:O.latestSha}).catch(()=>{})}if(h=!0,!x()&&_.warnings.length>0)for(let O of _.warnings)v(`Warning: ${O}`)}}catch{}if(!h&&(Ca(f,!!n.project),ae({resourceId:"context-manager",slug:We,installPath:`agents/${We}`,title:zs,sha:"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString()}),o?.token))try{let E=`agents/shared-context/${We}`,w=await G(`/api/cli/resource/${E}`);if(w.ok&&w.data.resource){let A=w.data.resource;A.latestSha&&await $("/api/cli/install",{resourceId:A.id,agentPlatform:f.platform,installedSha:A.latestSha}),ae({resourceId:A.id,slug:A.slug||We,installPath:`agents/shared-context/${A.slug||We}`,title:A.title||zs,sha:A.latestSha||"",scope:n.project?"project":"global",agent:f.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let E=[],w=(0,Ve.join)(process.cwd(),f.dir),A=(0,Ve.join)((0,Zs.homedir)(),f.dir);(0,rt.existsSync)(w)&&E.push({root:w,agent:f,isProject:!0}),w!==A&&(0,rt.existsSync)(A)&&E.push({root:A,agent:f,isProject:!1}),E.length>0&&(S=(await Xt({scanRoots:E,agentId:f.id,platformInternals:["context-manager",".claude-plugin"],registerToProject:!0})).imported.map(O=>({resourceType:O.resourceType,slug:O.slug,title:O.title})))}catch{}p.push({agent:f,collectionInstalled:h,installedMembers:i,importedResources:S,skippedEssentials:C})}if(Tt({lastSyncAt:new Date().toISOString()}),p.some(f=>!f.skippedEssentials)&&!x()&&process.stdin.isTTY){let{getConfig:f,updateConfig:h}=await Promise.resolve().then(()=>(ce(),Rt));if(f().telemetry===void 0)try{if(await new Promise(S=>{let E=(0,Js.createInterface)({input:process.stdin,output:process.stdout});E.question(`
144
- Help improve Shared Context skills? We collect anonymous usage data
145
- (which skills you use, never conversation content). Change anytime with
146
- \`shared-context-ai config set telemetry off\`. [y/N] `,w=>{E.close(),S(w.trim().toLowerCase()==="y"||w.trim().toLowerCase()==="yes")})})){h({telemetry:!0});let{enableTelemetryHook:S}=await Promise.resolve().then(()=>(Kr(),Gs));S(),b("Telemetry enabled.")}else h({telemetry:!1}),b("Telemetry disabled.")}catch{}}if(c){let f=p.reduce((h,C)=>h+C.importedResources.length,0);$("/api/cli/sync-report",{connectionId:c,lastSyncResult:{updatesAvailable:0,importedCount:f}}).catch(()=>{})}let d=p.every(f=>f.skippedEssentials),m=p.some(f=>!f.skippedEssentials),y=p.some(f=>f.importedResources.length>0);if(x()){let f=h=>({agent:h.agent.id,collection:h.collectionInstalled?Yt:void 0,contextManagerOnly:!h.collectionInstalled,skipped:h.skippedEssentials,...h.collectionInstalled&&!h.skippedEssentials?{membersInstalled:h.installedMembers.map(C=>({title:C.title,resourceType:C.resourceType}))}:{},...h.importedResources.length>0?{importedResources:h.importedResources.map(C=>({resourceType:C.resourceType,slug:C.slug,title:C.title}))}:{}});N("init",{...f(p[0]),agents:p.map(f),...u?{projectCreated:!0}:{},authenticated:L()})}else{for(let f of p)if(!f.skippedEssentials){if(b(""),f.collectionInstalled){b(`Context Manager installed for ${f.agent.label} (${f.installedMembers.length} resources)`);let h={};for(let i of f.installedMembers)h[i.resourceType]||(h[i.resourceType]=[]),h[i.resourceType].push(i.title);let C={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};b("");for(let[i,S]of Object.entries(h)){let E=C[i]||i;b(` ${E}: ${S.join(", ")}`)}}else b(`Context Manager installed for ${f.agent.label} (offline)`),b("Context Manager agent written locally");if(f.importedResources.length>0){b(""),b(`Imported ${f.importedResources.length} existing resource${f.importedResources.length===1?"":"s"}:`);for(let h of f.importedResources)b(` ${h.resourceType.padEnd(12)} ${h.slug.padEnd(24)} ${h.title}`)}}d&&!u&&!y&&(b(""),b("Already initialized. Nothing to do.")),(m||u||y)&&(b(""),b("Quick reference:"),b(' shared-context-ai search "query" Search for resources'),b(" shared-context-ai install <installPath> Install a resource"),b(" shared-context-ai list List installed resources"),b(" shared-context-ai sync Check updates & discover resources"),b(" 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}):b(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(x()?P("login",e.error.code,e.error.message):v(`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=`${_e().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${r}`;x()||(b("Opening browser for authentication..."),b(`If the browser doesn't open, visit: ${l}`));try{let c=(await Promise.resolve().then(()=>(xo(),Io))).default;await c(l)}catch{x()||b(`Could not open browser. Please visit:
147
- ${l}`)}setTimeout(()=>{t.close(),x()||v("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()?P("search",o.error.code,o.error.message):b(`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";b(`No ${u} found.`);return}b(`Found ${l.length} result${l.length===1?"":"s"}:
148
- `);let c=l.map(u=>[Ro(u),u.title,`\u2193${u.installCount}`]);b(he(c)),b(`
149
- Install a skill: npx shared-context-ai install <installPath>`)})}ne();ce();re();function Do(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 jo(r){r.command("list").description("List installed skills").alias("ls").action(async()=>{if(L()){let e=await G("/api/cli/installed");e.ok||(x()?P("list",e.error.code,e.error.message):b(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(x()){let s=t.map(o=>({...o,installPath:Do(o)}));N("list",{installations:s,count:s.length});return}if(t.length===0){b("No skills installed."),b("Use 'shared-context-ai search' to find skills to install.");return}b(`${t.length} skill${t.length===1?"":"s"} installed:
150
- `);let n=t.map(s=>[Do(s),s.title,s.hasUpdate?"(update available)":"(current)"]);b(he(n))}else{let t=B().installations;if(x()){N("list",{installations:t,count:t.length});return}if(t.length===0){b("No skills installed locally.");return}b(`${t.length} skill${t.length===1?"":"s"} installed locally:
151
- `);let n=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);b(he(n)),b(`
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()?P("preview",s.error.code,s.error.message):v(`Preview failed: ${s.error.message}`),process.exit(1)),x()?N("preview",s.data):b(s.data.content)})}ne();re();function $o(r){r.command("check").description("Check for skill updates").action(async()=>{L()||(x()?P("check","AUTH_MISSING","Login required to check for updates."):v("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await G("/api/cli/updates");e.ok||(x()?P("check",e.error.code,e.error.message):v(`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){b("All skills are up to date.");return}b(`${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)}`]});b(he(s)),b(`
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()?P("update","AUTH_MISSING","Login required to update resources."):v("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=ve(s.agent);if(!o){let a=Me();x()?P("update","NO_AGENTS",a):v(a),process.exit(1)}let l=await G("/api/cli/updates");l.ok||(x()?P("update",l.error.code,l.error.message):v(`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()?P("update","SKILL_NOT_FOUND",`No update available for "${e}".`):b(`No update available for "${e}".`);return}if(c.length===0){x()?N("update",{updated:[],count:0}):b("All resources are up to date.");return}let u=[];for(let a of c){let g=B().installations.find(h=>h.resourceId===a.resourceId&&h.agent===o.id),I;if(g?.installPath){let h=g.installPath.split("/");h[h.length-1]=a.slug||a.resourceId,I=h.join("/")}else I=Lo(a);if(g?.installMode==="plugin"&&a.resourceType==="collection"){try{let h=a.orgSlug||"",C=a.slug||a.resourceId,i=Ft(o.id),S=`/api/cli/resource/collections/${h}/${C}?format=plugin&platform=${i}`,E=await Lt(S,C),w=ut(o.id);w&&(0,Fo.execSync)(`${w} plugin install "${E}"`,{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:I,title:a.title}),x()||b(` Updated plugin: ${I}`)}catch(h){x()||v(` Plugin update failed for ${I}: ${h}`)}continue}let d=await G(`/api/cli/resource/${I}`);if(!d.ok){x()||v(` Failed to fetch ${I}: ${d.error.message}`);continue}let m=d.data,y=I.split("/").slice(1);if(m.resource.resourceType==="agent"){let h=te(o,!!s.project),C=(0,st.join)(h,...y);W(C,m.files)}else if(m.resource.resourceType==="mcp")Ut(o,!!s.project,m);else{let h=H(o,!!s.project),C=(0,st.join)(h,...y);W(C,m.files)}if(g&&g.installPath&&g.installPath!==I){let h=g.installPath.split("/").slice(1),C;m.resource.resourceType==="agent"?C=(0,st.join)(te(o,!!s.project),...h):m.resource.resourceType!=="mcp"&&(C=(0,st.join)(H(o,!!s.project),...h)),C&&(0,sr.existsSync)(C)&&((0,sr.rmSync)(C,{recursive:!0}),x()||b(` Removed old path: ${g.installPath}`))}let f=a.latestSha||m.resource.latestSha;if(f&&await $("/api/cli/update",{resourceId:a.resourceId,installedSha:f}),ae({...g||{},resourceId:a.resourceId,slug:a.slug||a.resourceId,installPath:I,title:m.resource.title,sha:f||"",scope:g?.scope||(s.project?"project":"global"),agent:o.id,installedAt:new Date().toISOString(),latestSha:f||void 0,resourceType:a.resourceType||m.resource.resourceType,serverSynced:!0}),u.push({installPath:I,title:m.resource.title}),x()||b(` Updated ${I}`),m.resource.resourceType==="collection"&&m.memberResources&&g?.installMode!=="plugin"){let h=B(),C=new Set(h.installations.map(i=>i.resourceId));for(let i of m.memberResources){if(C.has(i.id))continue;let S=i.slug||i.id,E=Mo[i.resourceType]||i.resourceType+"s",w=a.orgSlug?`${a.orgSlug}/`:"",A=`${E}/${w}${S}`,_=await G(`/api/cli/resource/${A}`);if(!_.ok){x()||v(` Failed to fetch new member ${A}: ${_.error.message}`);continue}let O=_.data,k=A.split("/").slice(1);if(O.resource.resourceType==="agent"){let R=te(o,!!s.project);W((0,st.join)(R,...k),O.files)}else if(O.resource.resourceType==="mcp")Ut(o,!!s.project,O);else{let R=H(o,!!s.project);W((0,st.join)(R,...k),O.files)}i.latestSha&&await $("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{}),ae({resourceId:i.id,slug:S,installPath:A,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}),x()||b(` + New member: ${A}`)}}}u.length>0&&$e(),x()?N("update",{updated:u,count:u.length}):u.length>0&&b(`
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 m=B().installations;if(m.length===0&&(x()?P("uninstall","NOTHING_INSTALLED","No resources installed."):b("No resources installed."),process.exit(0)),x())N("uninstall",{installations:m.map(y=>({path:y.installPath||y.slug,title:y.title,agent:y.agent}))});else{b(`Installed resources:
156
- `);let y=m.map(f=>[f.installPath||f.slug,f.title||"",`(${f.agent})`]);b(he(y)),b(`
157
- Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=ve(s.agent);if(!o){let d=Me();x()?P("uninstall","NO_AGENTS",d):v(d),process.exit(1)}let c=B().installations.find(d=>d.installPath===e||d.slug===e||d.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,I=!1;if(p==="collections")if(c?.installMode==="plugin"){let d=ut(o.id);if(d)try{(0,Ho.execSync)(`${d} plugin uninstall "${c.slug}"`,{stdio:"pipe"}),x()||b(`Uninstalled native ${d} plugin: ${c.slug}`)}catch(m){x()||v(`Native uninstall failed: ${m}. 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}):b(`Uninstalled "${e}"`);return}else{let d=Te(o),m=g[g.length-1],y=s.project?"project":"user",f=await d.uninstall(m,y,o,c?.resourceId);if(I=f.removed,!x())for(let h of f.warnings)v(`Warning: ${h}`);if(c){let C=B().installations.filter(i=>i.collectionId===c.resourceId&&i.agent===o.id);for(let i of C){let S=i.installPath.split("/"),E=S[0],w=S.slice(1);if(E==="agents"){let A=te(o,!!s.project),_=(0,ht.join)(A,...w);(0,se.existsSync)(_)&&(0,se.rmSync)(_,{recursive:!0,force:!0})}else if(E==="mcps"){let A=w[w.length-1],_=fe(o,!!s.project);if((0,se.existsSync)(_))try{let O=JSON.parse((0,se.readFileSync)(_,"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)(_,JSON.stringify(O,null,2)+`
158
- `,"utf-8"))}}catch{}}else if(E==="hooks")Vr(Ce(o,!!s.project),i.installPath);else{let A=H(o,!!s.project),_=(0,ht.join)(A,...w);(0,se.existsSync)(_)&&(0,se.rmSync)(_,{recursive:!0,force:!0})}wt(i.resourceId,o.id)}}}else if(p==="agents"){let d=te(o,!!s.project),m=(0,ht.join)(d,...g);I=(0,se.existsSync)(m),I&&(0,se.rmSync)(m,{recursive:!0,force:!0})}else if(p==="mcps"){let d=g[g.length-1],m=fe(o,!!s.project);if((0,se.existsSync)(m))try{let y=JSON.parse((0,se.readFileSync)(m,"utf-8"));if(typeof y.mcpServers=="object"&&y.mcpServers&&!Array.isArray(y.mcpServers)){let f=y.mcpServers;d in f&&(delete f[d],y.mcpServers=f,(0,se.writeFileSync)(m,JSON.stringify(y,null,2)+`
159
- `,"utf-8"),I=!0)}}catch{}}else if(p==="hooks"){let d=Ce(o,!!s.project);I=Vr(d,e),!I&&!x()&&v(`Note: No tagged hook entries found in ${d} \u2014 may need manual removal if installed before v0.1.10`)}else{let d=H(o,!!s.project),m=(0,ht.join)(d,...g);if(I=(0,se.existsSync)(m),I&&(0,se.rmSync)(m,{recursive:!0,force:!0}),!I&&c?.slug){let y=(0,ht.join)(d,c.slug);(0,se.existsSync)(y)&&(0,se.rmSync)(y,{recursive:!0,force:!0})}}if(L()&&c){let d=await $("/api/cli/uninstall",{resourceId:c.resourceId});!d.ok&&!x()&&v(`Warning: Could not record uninstall on server: ${d.error.message}`)}c&&wt(c.resourceId,o.id),$e(),x()?N("uninstall",{path:e,removed:!0}):b(`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=_e(),n=B(),s=Fe(),o=we(),l=n.installations.filter(g=>!g.projectId),c=n.installations.filter(g=>g.projectId),u=new Map;for(let g of c){let I=g.projectId;u.has(I)||u.set(I,[]),u.get(I).push(g)}let a=[];if(L()&&u.size>0)for(let[g,I]of u){let d=await G(`/api/cli/projects/${g}/resources`).catch(()=>null),m=d&&d.ok?d.data.resources.length:I.length,y=o?.projectId===g?o.projectName:`Project ${g.slice(0,8)}`;a.push({projectId:g,projectName:y,localCount:I.length,serverCount:m,synced:I.length>=m})}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(b("Shared Context CLI Status"),b("\u2500".repeat(40)),e?.token?b(` Auth: ${e.email} (${e.orgSlug})`):b(" Auth: Not logged in"),b(` API: ${t.apiBase}`),s.length>0?b(` Agents: ${s.map(g=>g.label).join(", ")}`):b(" Agents: None detected"),b(` Global: ${l.length} resource${l.length===1?"":"s"} installed`),a.length>0){b(""),b("Projects:");for(let g of a){let I=g.synced?"\u2713 synced":`\u26A0 ${g.serverCount-g.localCount} new`;b(` ${g.projectName}: ${g.localCount}/${g.serverCount} resources (${I})`)}}else o&&(b(""),b(` 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 jr("/api/cli/auth"),Rr(),x()?N("logout",{email:t?.email||null}):b("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()?P("import","INVALID_ARGS","Cannot use --github with a local path"):v("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(x()?P("import","INVALID_ARGS","Provide a local path or --github <url>"):v("Error: Provide a local path or --github <url>"),process.exit(1)),L()||(x()?P("import","AUTH_MISSING","Authentication required for import"):v("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(x()?P("import","INVALID_ARGS","--on-conflict is not supported with --github"):v("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(x()?P("import","INVALID_ARGS","--dry-run is not supported with --github"):v("Error: --dry-run is not supported with --github"),process.exit(1));let m={url:o};t.resourceType&&(m.resourceType=t.resourceType),x()||b(`
160
- Importing from GitHub: ${o}`);let y=await $("/api/cli/github-import",m);y.ok||(x()?P("import",y.error.code,y.error.message):v(`
161
- Import failed: ${y.error.message}`),process.exit(1));let f=y.data;if(x()){N("import",f);return}b(""),b(` Source: ${f.source.owner}/${f.source.repo}`),b(` Type: ${f.resourceType}`),b(` Title: ${f.title}`),f.slug&&b(` Slug: ${f.slug}`),b(` URL: ${f.url}`),b(""),b("Import complete: 1 created");return}let l=(0,qo.resolve)(e);(!(0,or.existsSync)(l)||!(0,or.statSync)(l).isDirectory())&&(x()?P("import","INVALID_PATH",`Not a directory: ${l}`):v(`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"}):b("No resources found in the specified directory.");return}if(!x()){let m=new Map;for(let f of c.resources)m.set(f.resourceType,(m.get(f.resourceType)||0)+1);let y=[...m.entries()].map(([f,h])=>`${h} ${f}${h===1?"":"s"}`).join(", ");b(`
162
- Discovered ${c.resources.length} resources in ${e}:`),b(` ${y}`),c.formatLabel&&c.pluginName?b(` ${c.formatLabel}: ${c.pluginName}`):c.pluginName&&b(` Plugin: ${c.pluginName}`)}let u=t.tags?t.tags.split(",").map(m=>m.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?b(`
163
- Executing import...`):x()||b(`
164
- Dry run \u2014 previewing changes...`);let p=await $("/api/cli/import",a,12e4);p.ok||(x()?P("import",p.error.code,p.error.message):v(`
165
- Import failed: ${p.error.message}`),process.exit(1));let g=p.data;if(x()){N("import",g);return}let I=[...g.created.map(m=>({...m,action:"created"})),...g.updated.map(m=>({...m,action:"updated"})),...g.installed.map(m=>({...m,action:"installed"})),...g.cloned.map(m=>({...m,action:"cloned"})),...g.skipped.map(m=>({...m,action:"skipped"})),...g.errors.map(m=>({...m,action:"error"}))];if(I.length>0){b("");let m=I.length,y=I.map((f,h)=>{let C=`[${String(h+1).padStart(String(m).length)}/${m}]`,i=(f.resourceType||"").padEnd(10),S=(f.importPath.split("/").pop()||"").padEnd(24),E="";switch(f.action){case"created":E=`\u2713 created${f.slug?` (slug: ${f.slug})`:""}`;break;case"updated":E="\u2713 updated";break;case"installed":{let w=f.versionsBehind;E=`\u2713 installed${w?` (${w} versions behind)`:""}`;break}case"cloned":E=`\u2713 cloned${f.slug?` (slug: ${f.slug})`:""}`;break;case"skipped":E=`\u2713 skipped (${f.reason||"up to date"})`;break;case"error":E=`\u2717 error: ${f.error||"unknown"}`;break}return` ${C} ${i} ${S} ${E}`});for(let f of y)b(f)}if(g.collections.length>0)for(let m of g.collections){let y=m.importPath.split("/").pop()||m.importPath;b(` collection ${y.padEnd(20)} \u2713 ${m.membersLinked} members linked${m.membersFailed>0?`, ${m.membersFailed} failed`:""}`)}b("");let d=[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?b(`Dry run complete: ${d.join(", ")}`):b(`Import complete: ${d.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&&!Dr()){let w=B(),A=w.installations.filter(k=>k.latestSha&&k.sha&&k.latestSha!==k.sha),_=w.lastSyncAt?Math.floor((Date.now()-new Date(w.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)+(_!==void 0?` (cached ${_}m ago, run --force to refresh)`:""),throttled:!0,cacheAge:_};bn(O,!!n.quiet);return}L()||(x()?P("sync","AUTH_MISSING","Login required to sync."):v("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=B().installations.filter(O=>O.latestSha&&O.sha&&O.latestSha!==O.sha);!x()&&!n.quiet&&v(`Warning: Could not reach server (${o.error.message}). Showing cached state.`);let _={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(_,!!n.quiet);return}let l=o.data.installations,c=new Map(l.map(w=>[w.resourceId,w])),u=B(),a=0;for(let w of u.installations){let A=c.get(w.resourceId);if(A)w.latestSha=A.latestSha||void 0,w.resourceType=w.resourceType||A.resourceType,w.serverSynced=!0,A.installedSha&&w.sha&&A.installedSha!==w.sha&&(!x()&&!n.quiet&&b(` Drift repaired: ${w.installPath} (local=${w.sha.slice(0,7)} \u2192 server=${A.installedSha.slice(0,7)})`),w.sha=A.installedSha,a++),c.delete(w.resourceId);else if(w.serverSynced!==!1){let _=await $("/api/cli/install",{resourceId:w.resourceId,agentPlatform:s?.platform||"claude_code",installedSha:w.sha});_.ok?w.serverSynced=!0:(_.error.code==="NOT_FOUND"||_.error.code==="RESOURCE_NOT_FOUND")&&(w.serverSynced=!1,w.resourceId="",a++)}}u.installations=u.installations.filter(w=>w.resourceId!=="");let p=Array.from(c.values());if(p.length>0&&!x()&&!n.quiet){b(`
166
- ${p.length} resource${p.length===1?"":"s"} installed elsewhere (web/other machine):`);for(let w of p.slice(0,5))b(` ${za(w)} \u2014 ${w.title}`);p.length>5&&b(` ...and ${p.length-5} more`)}Ne(u);let g=s?[s]:Fe();g.length===0&&!x()&&!n.quiet&&v("No AI agents detected \u2014 resource discovery skipped. Use --agent to specify one.");let I=g.map(w=>({root:n.project?(0,An.join)(process.cwd(),w.dir):(0,An.join)((0,Ko.homedir)(),w.dir),agent:w,isProject:!!n.project})),d={imported:[],errors:0,projectRegistered:0,untrackedCount:0,discoveredPaths:[],untracked:[]};if(I.length>0){if(d=await Xt({scanRoots:I,agentId:s?.id||g[0]?.id||"unknown",registerToProject:!!n.project,skipImport:n.import===!1}),d.imported.length>0&&!x()&&!n.quiet){b(`
167
- Imported ${d.imported.length} resource${d.imported.length===1?"":"s"}:`);let w=d.imported.map(A=>[` ${(A.resourceType||"").padEnd(12)}`,(A.slug||A.importPath.split("/").pop()||"").padEnd(24),A.importPath]);b(he(w))}if(d.errors>0&&!x()&&v(`
168
- ${d.errors} import error(s)`),d.projectRegistered>0&&!x()&&!n.quiet){let w=we();b(`
169
- Project "${w?.projectName}": registered ${d.projectRegistered} resource${d.projectRegistered===1?"":"s"}`)}}let m=d.untrackedCount,y=we(),f=0;if(y){let w=await G(`/api/cli/projects/${y.projectId}/resources`);if(!w.ok)!x()&&!n.quiet&&(v(`Warning: Project "${y.projectName}" not found on server (may have been deleted).`),v(" Remove .shared-context/project.json to unlink this directory."));else{let A=w.data.project;A&&(A.name!==y.projectName||A.slug!==y.projectSlug)&&Ye({projectId:y.projectId,projectName:A.name,projectSlug:A.slug});let _=w.data.resources,O=u.installations.filter(D=>D.projectId===y.projectId),k=new Set(O.map(D=>D.resourceId)),R=_.filter(D=>!k.has(D.id));if(R.length>0)if(!s)!x()&&!n.quiet&&v(`
170
- Project "${y.projectName}" has ${R.length} new resource${R.length===1?"":"s"} \u2014 use --agent to install them.`);else{let D=Te(s);for(let j of R){let V=j.installPath;try{let q=await G(`/api/cli/resource/${V}`);if(!q.ok)continue;await D.install(q.data,"project",s),ae({resourceId:j.id,slug:j.slug||j.id,installPath:V,title:j.title,sha:j.latestSha||"",scope:"project",agent:s.id,installedAt:new Date().toISOString(),projectId:y.projectId,resourceType:j.resourceType,serverSynced:!0}),j.latestSha&&await $("/api/cli/install",{resourceId:j.id,agentPlatform:s.platform,installedSha:j.latestSha}).catch(()=>{}),f++}catch{}}!x()&&!n.quiet&&f>0&&b(`
171
- Project "${y.projectName}": installed ${f} new resource${f===1?"":"s"}`)}if(n.project){let D=new Set(_.map(q=>q.id)),j=new Set(d.discoveredPaths),V=0;for(let q of u.installations){if(D.has(q.resourceId)||!j.has(q.installPath))continue;(await $(`/api/cli/projects/${y.projectId}/resources`,{resourceId:q.resourceId})).ok&&(q.projectId=y.projectId,V++)}V>0&&!x()&&!n.quiet&&b(`
172
- Project "${y.projectName}": registered ${V} existing resource${V===1?"":"s"}`)}await $(`/api/cli/projects/${y.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let h=d.imported.length;if(n.force){let w=u.lastSyncAt;u.lastSyncAt=w||new Date().toISOString()}else u.lastSyncAt=new Date().toISOString();Ne(u);let C=u.installations.filter(w=>w.latestSha&&w.sha&&w.latestSha!==w.sha),i=Ae();i?.connectionId&&$("/api/cli/sync-report",{connectionId:i.connectionId,lastSyncResult:{updatesAvailable:C.length,importedCount:h}}).catch(()=>{});try{let{pushTelemetry:w}=await Promise.resolve().then(()=>(Cn(),Jo));await w(!0)}catch{}let S=d.untracked,E={updatesAvailable:C.length,untrackedResources:S.length,driftRepairs:a,updates:C.map(w=>({installPath:w.installPath,title:w.title,sha:w.sha,latestSha:w.latestSha})),untracked:S,summary:wn(C.length,S.length,a),throttled:!1};bn(E,!!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`),b(t);return}if(b(""),r.updates.length>0){b(`${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)}`]);b(he(t)),b("")}if(r.untracked.length>0){b(`${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]);b(he(t)),b("")}r.updatesAvailable===0&&r.untrackedResources===0?b("Everything is up to date."):(r.updatesAvailable>0&&b("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&b("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),b("")}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()?P("project create","AUTH_MISSING",a):v(a),process.exit(1)}let n=we();if(n){x()?N("project create",{alreadyExists:!0,project:{id:n.projectId,name:n.projectName,slug:n.projectSlug}}):b(`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()?P("project create","INVALID_NAME",a):v(a),process.exit(1)}let o=await $("/api/cli/projects",{name:s});o.ok||(x()?P("project create",o.error.code,o.error.message):v(`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}):(b(`Created project: ${c}`),b(""),b("Quick reference:"),b(" shared-context-ai install <installPath> Add a resource to this project"),b(" shared-context-ai sync Check for resource updates"),b(" shared-context-ai status View project sync status"))})}Cn();var cr=require("fs"),ar=require("path"),_n=require("os");re();function Za(){let r=process.env.SC_PROFILE;return r?(0,ar.join)((0,_n.homedir)(),".config","shared-context","profiles",r):(0,ar.join)((0,_n.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:[]}):b("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(b(`Usage over the last ${t} day${t===1?"":"s"} (${o.length} event${o.length===1?"":"s"})
176
- `),l.size>0){b("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`]);b(he(u))}if(c.size>0){l.size>0&&b(""),b("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`:""]});b(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"}code;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);jo(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()?P(process.argv[2]||"unknown",r.code,r.message):(v(`Error: ${r.message}`),v(r.recovery)):x()?P(process.argv[2]||"unknown","UNEXPECTED",r.message||"Unexpected error"):v(`Error: ${r.message||r}`),process.exit(1)});ie.parse();