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