@unliftedq/kman 0.0.2 → 0.0.3
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/LICENSE +202 -21
- package/README.md +122 -9
- package/dist/main.js +115 -70
- package/package.json +11 -10
- package/dist/main.js.map +0 -61
package/dist/main.js
CHANGED
|
@@ -1,82 +1,127 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
3
|
-
`)}displayWidth($){return
|
|
4
|
-
`+" ".repeat(q+
|
|
5
|
-
${z}`)}boxWrap($,q){if(q<this.minWidthToWrap)return $;let
|
|
6
|
-
`)}}function
|
|
2
|
+
import{createRequire as J3}from"node:module";var s1=Object.create;var{getPrototypeOf:a1,defineProperty:Lq,getOwnPropertyNames:o1}=Object;var r1=Object.prototype.hasOwnProperty;function e1($){return this[$]}var $3,q3,P0=($,q,J)=>{var X=$!=null&&typeof $==="object";if(X){var Z=q?$3??=new WeakMap:q3??=new WeakMap,z=Z.get($);if(z)return z}J=$!=null?s1(a1($)):{};let Q=q||!$||!$.__esModule?Lq(J,"default",{value:$,enumerable:!0}):J;for(let G of o1($))if(!r1.call(Q,G))Lq(Q,G,{get:e1.bind($,G),enumerable:!0});if(X)Z.set($,Q);return Q};var N=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);var Y$=J3(import.meta.url);var P$=N((X3)=>{class D0 extends Error{constructor($,q,J){super(J);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=q,this.exitCode=$,this.nestedError=void 0}}class wq extends D0{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}X3.CommanderError=D0;X3.InvalidArgumentError=wq});var h$=N((Y3)=>{var{InvalidArgumentError:Q3}=P$();class xq{constructor($,q){switch(this.description=q||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue($,q){if(q===this.defaultValue||!Array.isArray(q))return[$];return q.push($),q}default($,q){return this.defaultValue=$,this.defaultValueDescription=q,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(q,J)=>{if(!this.argChoices.includes(q))throw new Q3(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(q,J);return q},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function G3($){let q=$.name()+($.variadic===!0?"...":"");return $.required?"<"+q+">":"["+q+"]"}Y3.Argument=xq;Y3.humanReadableArgName=G3});var S0=N((V3)=>{var{humanReadableArgName:U3}=h$();class jq{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let q=$.commands.filter((X)=>!X._hidden),J=$._getHelpCommand();if(J&&!J._hidden)q.push(J);if(this.sortSubcommands)q.sort((X,Z)=>{return X.name().localeCompare(Z.name())});return q}compareOptions($,q){let J=(X)=>{return X.short?X.short.replace(/^-/,""):X.long.replace(/^--/,"")};return J($).localeCompare(J(q))}visibleOptions($){let q=$.options.filter((X)=>!X.hidden),J=$._getHelpOption();if(J&&!J.hidden){let X=J.short&&$._findOption(J.short),Z=J.long&&$._findOption(J.long);if(!X&&!Z)q.push(J);else if(J.long&&!Z)q.push($.createOption(J.long,J.description));else if(J.short&&!X)q.push($.createOption(J.short,J.description))}if(this.sortOptions)q.sort(this.compareOptions);return q}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let q=[];for(let J=$.parent;J;J=J.parent){let X=J.options.filter((Z)=>!Z.hidden);q.push(...X)}if(this.sortOptions)q.sort(this.compareOptions);return q}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((q)=>{q.description=q.description||$._argsDescription[q.name()]||""});if($.registeredArguments.find((q)=>q.description))return $.registeredArguments;return[]}subcommandTerm($){let q=$.registeredArguments.map((J)=>U3(J)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(q?" "+q:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,q){return q.visibleCommands($).reduce((J,X)=>{return Math.max(J,this.displayWidth(q.styleSubcommandTerm(q.subcommandTerm(X))))},0)}longestOptionTermLength($,q){return q.visibleOptions($).reduce((J,X)=>{return Math.max(J,this.displayWidth(q.styleOptionTerm(q.optionTerm(X))))},0)}longestGlobalOptionTermLength($,q){return q.visibleGlobalOptions($).reduce((J,X)=>{return Math.max(J,this.displayWidth(q.styleOptionTerm(q.optionTerm(X))))},0)}longestArgumentTermLength($,q){return q.visibleArguments($).reduce((J,X)=>{return Math.max(J,this.displayWidth(q.styleArgumentTerm(q.argumentTerm(X))))},0)}commandUsage($){let q=$._name;if($._aliases[0])q=q+"|"+$._aliases[0];let J="";for(let X=$.parent;X;X=X.parent)J=X.name()+" "+J;return J+q+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")q.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)q.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)q.push(`env: ${$.envVar}`);if(q.length>0){let J=`(${q.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}argumentDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0)q.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(q.length>0){let J=`(${q.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}formatItemList($,q,J){if(q.length===0)return[];return[J.styleTitle($),...q,""]}groupItems($,q,J){let X=new Map;return $.forEach((Z)=>{let z=J(Z);if(!X.has(z))X.set(z,[])}),q.forEach((Z)=>{let z=J(Z);if(!X.has(z))X.set(z,[]);X.get(z).push(Z)}),X}formatHelp($,q){let J=q.padWidth($,q),X=q.helpWidth??80;function Z(W,V){return q.formatItem(W,J,V,q)}let z=[`${q.styleTitle("Usage:")} ${q.styleUsage(q.commandUsage($))}`,""],Q=q.commandDescription($);if(Q.length>0)z=z.concat([q.boxWrap(q.styleCommandDescription(Q),X),""]);let G=q.visibleArguments($).map((W)=>{return Z(q.styleArgumentTerm(q.argumentTerm(W)),q.styleArgumentDescription(q.argumentDescription(W)))});if(z=z.concat(this.formatItemList("Arguments:",G,q)),this.groupItems($.options,q.visibleOptions($),(W)=>W.helpGroupHeading??"Options:").forEach((W,V)=>{let F=W.map((S)=>{return Z(q.styleOptionTerm(q.optionTerm(S)),q.styleOptionDescription(q.optionDescription(S)))});z=z.concat(this.formatItemList(V,F,q))}),q.showGlobalOptions){let W=q.visibleGlobalOptions($).map((V)=>{return Z(q.styleOptionTerm(q.optionTerm(V)),q.styleOptionDescription(q.optionDescription(V)))});z=z.concat(this.formatItemList("Global Options:",W,q))}return this.groupItems($.commands,q.visibleCommands($),(W)=>W.helpGroup()||"Commands:").forEach((W,V)=>{let F=W.map((S)=>{return Z(q.styleSubcommandTerm(q.subcommandTerm(S)),q.styleSubcommandDescription(q.subcommandDescription(S)))});z=z.concat(this.formatItemList(V,F,q))}),z.join(`
|
|
3
|
+
`)}displayWidth($){return Hq($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((q)=>{if(q==="[options]")return this.styleOptionText(q);if(q==="[command]")return this.styleSubcommandText(q);if(q[0]==="["||q[0]==="<")return this.styleArgumentText(q);return this.styleCommandText(q)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((q)=>{if(q==="[options]")return this.styleOptionText(q);if(q[0]==="["||q[0]==="<")return this.styleArgumentText(q);return this.styleSubcommandText(q)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,q){return Math.max(q.longestOptionTermLength($,q),q.longestGlobalOptionTermLength($,q),q.longestSubcommandTermLength($,q),q.longestArgumentTermLength($,q))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,q,J,X){let z=" ".repeat(2);if(!J)return z+$;let Q=$.padEnd(q+$.length-X.displayWidth($)),G=2,Y=(this.helpWidth??80)-q-G-2,W;if(Y<this.minWidthToWrap||X.preformatted(J))W=J;else W=X.boxWrap(J,Y).replace(/\n/g,`
|
|
4
|
+
`+" ".repeat(q+G));return z+Q+" ".repeat(G)+W.replace(/\n/g,`
|
|
5
|
+
${z}`)}boxWrap($,q){if(q<this.minWidthToWrap)return $;let J=$.split(/\r\n|\n/),X=/[\s]*[^\s]+/g,Z=[];return J.forEach((z)=>{let Q=z.match(X);if(Q===null){Z.push("");return}let G=[Q.shift()],B=this.displayWidth(G[0]);Q.forEach((Y)=>{let W=this.displayWidth(Y);if(B+W<=q){G.push(Y),B+=W;return}Z.push(G.join(""));let V=Y.trimStart();G=[V],B=this.displayWidth(V)}),Z.push(G.join(""))}),Z.join(`
|
|
6
|
+
`)}}function Hq($){let q=/\x1b\[\d*(;\d*)*m/g;return $.replace(q,"")}V3.Help=jq;V3.stripColor=Hq});var I0=N((P3)=>{var{InvalidArgumentError:F3}=P$();class _q{constructor($,q){this.flags=$,this.description=q||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let J=N3($);if(this.short=J.shortFlag,this.long=J.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,this.helpGroupHeading=void 0}default($,q){return this.defaultValue=$,this.defaultValueDescription=q,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let q=$;if(typeof $==="string")q={[$]:!0};return this.implied=Object.assign(this.implied||{},q),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_collectValue($,q){if(q===this.defaultValue||!Array.isArray(q))return[$];return q.push($),q}choices($){return this.argChoices=$.slice(),this.parseArg=(q,J)=>{if(!this.argChoices.includes(q))throw new F3(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(q,J);return q},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return Oq(this.name().replace(/^no-/,""));return Oq(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class yq{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((q)=>{if(q.negate)this.negativeOptions.set(q.attributeName(),q);else this.positiveOptions.set(q.attributeName(),q)}),this.negativeOptions.forEach((q,J)=>{if(this.positiveOptions.has(J))this.dualOptions.add(J)})}valueFromOption($,q){let J=q.attributeName();if(!this.dualOptions.has(J))return!0;let X=this.negativeOptions.get(J).presetArg,Z=X!==void 0?X:!1;return q.negate===(Z===$)}}function Oq($){return $.split("-").reduce((q,J)=>{return q+J[0].toUpperCase()+J.slice(1)})}function N3($){let q,J,X=/^-[^-]$/,Z=/^--[^-]/,z=$.split(/[ |,]+/).concat("guard");if(X.test(z[0]))q=z.shift();if(Z.test(z[0]))J=z.shift();if(!q&&X.test(z[0]))q=z.shift();if(!q&&Z.test(z[0]))q=J,J=z.shift();if(z[0].startsWith("-")){let Q=z[0],G=`option creation failed due to '${Q}' in option flags '${$}'`;if(/^-[^-][^-]/.test(Q))throw Error(`${G}
|
|
7
7
|
- a short flag is a single dash and a single character
|
|
8
8
|
- either use a single dash and a single character (for a short flag)
|
|
9
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(
|
|
10
|
-
- too many short flags`);if(
|
|
11
|
-
- too many long flags`);throw Error(`${
|
|
12
|
-
- unrecognised flag format`)}if(q===void 0&&
|
|
13
|
-
(Did you mean one of ${
|
|
14
|
-
(Did you mean ${
|
|
15
|
-
- specify the name in Command constructor or using .name()`);if(q=q||{},q.isDefault)this._defaultCommandName=$._name;if(q.noHelp||q.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,q){return new
|
|
16
|
-
Expecting one of '${
|
|
17
|
-
- already used by option '${q.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let q=(
|
|
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($,q,
|
|
19
|
-
- if '${
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(X.test(Q))throw Error(`${G}
|
|
10
|
+
- too many short flags`);if(Z.test(Q))throw Error(`${G}
|
|
11
|
+
- too many long flags`);throw Error(`${G}
|
|
12
|
+
- unrecognised flag format`)}if(q===void 0&&J===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:q,longFlag:J}}P3.Option=_q;P3.DualOptions=yq});var Tq=N((L3)=>{function I3($,q){if(Math.abs($.length-q.length)>3)return Math.max($.length,q.length);let J=[];for(let X=0;X<=$.length;X++)J[X]=[X];for(let X=0;X<=q.length;X++)J[0][X]=X;for(let X=1;X<=q.length;X++)for(let Z=1;Z<=$.length;Z++){let z=1;if($[Z-1]===q[X-1])z=0;else z=1;if(J[Z][X]=Math.min(J[Z-1][X]+1,J[Z][X-1]+1,J[Z-1][X-1]+z),Z>1&&X>1&&$[Z-1]===q[X-2]&&$[Z-2]===q[X-1])J[Z][X]=Math.min(J[Z][X],J[Z-2][X-2]+1)}return J[$.length][q.length]}function f3($,q){if(!q||q.length===0)return"";q=Array.from(new Set(q));let J=$.startsWith("--");if(J)$=$.slice(2),q=q.map((Q)=>Q.slice(2));let X=[],Z=3,z=0.4;if(q.forEach((Q)=>{if(Q.length<=1)return;let G=I3($,Q),B=Math.max($.length,Q.length);if((B-G)/B>z){if(G<Z)Z=G,X=[Q];else if(G===Z)X.push(Q)}}),X.sort((Q,G)=>Q.localeCompare(G)),J)X=X.map((Q)=>`--${Q}`);if(X.length>1)return`
|
|
13
|
+
(Did you mean one of ${X.join(", ")}?)`;if(X.length===1)return`
|
|
14
|
+
(Did you mean ${X[0]}?)`;return""}L3.suggestSimilar=f3});var Eq=N((T3)=>{var x3=Y$("node:events").EventEmitter,f0=Y$("node:child_process"),l=Y$("node:path"),C$=Y$("node:fs"),K=Y$("node:process"),{Argument:j3,humanReadableArgName:H3}=h$(),{CommanderError:L0}=P$(),{Help:O3,stripColor:_3}=S0(),{Option:kq,DualOptions:y3}=I0(),{suggestSimilar:Rq}=Tq();class x0 extends x3{constructor($){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=$||"",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:(q)=>K.stdout.write(q),writeErr:(q)=>K.stderr.write(q),outputError:(q,J)=>J(q),getOutHelpWidth:()=>K.stdout.isTTY?K.stdout.columns:void 0,getErrHelpWidth:()=>K.stderr.isTTY?K.stderr.columns:void 0,getOutHasColors:()=>w0()??(K.stdout.isTTY&&K.stdout.hasColors?.()),getErrHasColors:()=>w0()??(K.stderr.isTTY&&K.stderr.hasColors?.()),stripColor:(q)=>_3(q)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let q=this;q;q=q.parent)$.push(q);return $}command($,q,J){let X=q,Z=J;if(typeof X==="object"&&X!==null)Z=X,X=null;Z=Z||{};let[,z,Q]=$.match(/([^ ]+) *(.*)/),G=this.createCommand(z);if(X)G.description(X),G._executableHandler=!0;if(Z.isDefault)this._defaultCommandName=G._name;if(G._hidden=!!(Z.noHelp||Z.hidden),G._executableFile=Z.executableFile||null,Q)G.arguments(Q);if(this._registerCommand(G),G.parent=this,G.copyInheritedSettings(this),X)return this;return G}createCommand($){return new x0($)}createHelp(){return Object.assign(new O3,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...$},this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,q){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
|
|
15
|
+
- specify the name in Command constructor or using .name()`);if(q=q||{},q.isDefault)this._defaultCommandName=$._name;if(q.noHelp||q.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,q){return new j3($,q)}argument($,q,J,X){let Z=this.createArgument($,q);if(typeof J==="function")Z.default(X).argParser(J);else Z.default(J);return this.addArgument(Z),this}arguments($){return $.trim().split(/ +/).forEach((q)=>{this.argument(q)}),this}addArgument($){let q=this.registeredArguments.slice(-1)[0];if(q?.variadic)throw Error(`only the last argument can be variadic '${q.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,q){if(typeof $==="boolean"){if(this._addImplicitHelpCommand=$,$&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let J=$??"help [command]",[,X,Z]=J.match(/([^ ]+) *(.*)/),z=q??"display help for command",Q=this.createCommand(X);if(Q.helpOption(!1),Z)Q.arguments(Z);if(z)Q.description(z);if(this._addImplicitHelpCommand=!0,this._helpCommand=Q,$||q)this._initCommandGroup(Q);return this}addHelpCommand($,q){if(typeof $!=="object")return this.helpCommand($,q),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this._initCommandGroup($),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,q){let J=["preSubcommand","preAction","postAction"];if(!J.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
|
|
16
|
+
Expecting one of '${J.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(q);else this._lifeCycleHooks[$]=[q];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(q)=>{if(q.code!=="commander.executeSubCommandAsync")throw q};return this}_exit($,q,J){if(this._exitCallback)this._exitCallback(new L0($,q,J));K.exit($)}action($){let q=(J)=>{let X=this.registeredArguments.length,Z=J.slice(0,X);if(this._storeOptionsAsProperties)Z[X]=this;else Z[X]=this.opts();return Z.push(this),$.apply(this,Z)};return this._actionHandler=q,this}createOption($,q){return new kq($,q)}_callParseArg($,q,J,X){try{return $.parseArg(q,J)}catch(Z){if(Z.code==="commander.invalidArgument"){let z=`${X} ${Z.message}`;this.error(z,{exitCode:Z.exitCode,code:Z.code})}throw Z}}_registerOption($){let q=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(q){let J=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${J}'
|
|
17
|
+
- already used by option '${q.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let q=(X)=>{return[X.name()].concat(X.aliases())},J=q($).find((X)=>this._findCommand(X));if(J){let X=q(this._findCommand(J)).join("|"),Z=q($).join("|");throw Error(`cannot add command '${Z}' as already have command '${X}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let q=$.name(),J=$.attributeName();if($.negate){let Z=$.long.replace(/^--no-/,"--");if(!this._findOption(Z))this.setOptionValueWithSource(J,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(J,$.defaultValue,"default");let X=(Z,z,Q)=>{if(Z==null&&$.presetArg!==void 0)Z=$.presetArg;let G=this.getOptionValue(J);if(Z!==null&&$.parseArg)Z=this._callParseArg($,Z,G,z);else if(Z!==null&&$.variadic)Z=$._collectValue(Z,G);if(Z==null)if($.negate)Z=!1;else if($.isBoolean()||$.optional)Z=!0;else Z="";this.setOptionValueWithSource(J,Z,Q)};if(this.on("option:"+q,(Z)=>{let z=`error: option '${$.flags}' argument '${Z}' is invalid.`;X(Z,z,"cli")}),$.envVar)this.on("optionEnv:"+q,(Z)=>{let z=`error: option '${$.flags}' value '${Z}' from env '${$.envVar}' is invalid.`;X(Z,z,"env")});return this}_optionEx($,q,J,X,Z){if(typeof q==="object"&&q instanceof kq)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let z=this.createOption(q,J);if(z.makeOptionMandatory(!!$.mandatory),typeof X==="function")z.default(Z).argParser(X);else if(X instanceof RegExp){let Q=X;X=(G,B)=>{let Y=Q.exec(G);return Y?Y[0]:B},z.default(Z).argParser(X)}else z.default(X);return this.addOption(z)}option($,q,J,X){return this._optionEx({},$,q,J,X)}requiredOption($,q,J,X){return this._optionEx({mandatory:!0},$,q,J,X)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,q){return this.setOptionValueWithSource($,q,void 0)}setOptionValueWithSource($,q,J){if(this._storeOptionsAsProperties)this[$]=q;else this._optionValues[$]=q;return this._optionValueSources[$]=J,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let q;return this._getCommandAndAncestors().forEach((J)=>{if(J.getOptionValueSource($)!==void 0)q=J.getOptionValueSource($)}),q}_prepareUserArgs($,q){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(q=q||{},$===void 0&&q.from===void 0){if(K.versions?.electron)q.from="electron";let X=K.execArgv??[];if(X.includes("-e")||X.includes("--eval")||X.includes("-p")||X.includes("--print"))q.from="eval"}if($===void 0)$=K.argv;this.rawArgs=$.slice();let J;switch(q.from){case void 0:case"node":this._scriptPath=$[1],J=$.slice(2);break;case"electron":if(K.defaultApp)this._scriptPath=$[1],J=$.slice(2);else J=$.slice(1);break;case"user":J=$.slice(0);break;case"eval":J=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${q.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",J}parse($,q){this._prepareForParse();let J=this._prepareUserArgs($,q);return this._parseCommand([],J),this}async parseAsync($,q){this._prepareForParse();let J=this._prepareUserArgs($,q);return await this._parseCommand([],J),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw 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($,q,J){if(C$.existsSync($))return;let X=q?`searched for local subcommand relative to directory '${q}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Z=`'${$}' does not exist
|
|
19
|
+
- if '${J}' 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
|
-
- ${
|
|
21
|
+
- ${X}`;throw Error(Z)}_executeSubCommand($,q){q=q.slice();let J=!1,X=[".js",".ts",".tsx",".mjs",".cjs"];function Z(Y,W){let V=l.resolve(Y,W);if(C$.existsSync(V))return V;if(X.includes(l.extname(W)))return;let F=X.find((S)=>C$.existsSync(`${V}${S}`));if(F)return`${V}${F}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=$._executableFile||`${this._name}-${$._name}`,Q=this._executableDir||"";if(this._scriptPath){let Y;try{Y=C$.realpathSync(this._scriptPath)}catch{Y=this._scriptPath}Q=l.resolve(l.dirname(Y),Q)}if(Q){let Y=Z(Q,z);if(!Y&&!$._executableFile&&this._scriptPath){let W=l.basename(this._scriptPath,l.extname(this._scriptPath));if(W!==this._name)Y=Z(Q,`${W}-${$._name}`)}z=Y||z}J=X.includes(l.extname(z));let G;if(K.platform!=="win32")if(J)q.unshift(z),q=Aq(K.execArgv).concat(q),G=f0.spawn(K.argv[0],q,{stdio:"inherit"});else G=f0.spawn(z,q,{stdio:"inherit"});else this._checkForMissingExecutable(z,Q,$._name),q.unshift(z),q=Aq(K.execArgv).concat(q),G=f0.spawn(K.execPath,q,{stdio:"inherit"});if(!G.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((W)=>{K.on(W,()=>{if(G.killed===!1&&G.exitCode===null)G.kill(W)})});let B=this._exitCallback;G.on("close",(Y)=>{if(Y=Y??1,!B)K.exit(Y);else B(new L0(Y,"commander.executeSubCommandAsync","(close)"))}),G.on("error",(Y)=>{if(Y.code==="ENOENT")this._checkForMissingExecutable(z,Q,$._name);else if(Y.code==="EACCES")throw Error(`'${z}' not executable`);if(!B)K.exit(1);else{let W=new L0(1,"commander.executeSubCommandAsync","(error)");W.nestedError=Y,B(W)}}),this.runningCommand=G}_dispatchSubcommand($,q,J){let X=this._findCommand($);if(!X)this.help({error:!0});X._prepareForParse();let Z;return Z=this._chainOrCallSubCommandHook(Z,X,"preSubcommand"),Z=this._chainOrCall(Z,()=>{if(X._executableHandler)this._executeSubCommand(X,q.concat(J));else return X._parseCommand(q,J)}),Z}_dispatchHelpCommand($){if(!$)this.help();let q=this._findCommand($);if(q&&!q._executableHandler)q.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,q)=>{if($.required&&this.args[q]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(J,X,Z)=>{let z=X;if(X!==null&&J.parseArg){let Q=`error: command-argument value '${X}' is invalid for argument '${J.name()}'.`;z=this._callParseArg(J,X,Z,Q)}return z};this._checkNumberOfArguments();let q=[];this.registeredArguments.forEach((J,X)=>{let Z=J.defaultValue;if(J.variadic){if(X<this.args.length){if(Z=this.args.slice(X),J.parseArg)Z=Z.reduce((z,Q)=>{return $(J,Q,z)},J.defaultValue)}else if(Z===void 0)Z=[]}else if(X<this.args.length){if(Z=this.args[X],J.parseArg)Z=$(J,Z,J.defaultValue)}q[X]=Z}),this.processedArgs=q}_chainOrCall($,q){if($?.then&&typeof $.then==="function")return $.then(()=>q());return q()}_chainOrCallHooks($,q){let J=$,X=[];if(this._getCommandAndAncestors().reverse().filter((Z)=>Z._lifeCycleHooks[q]!==void 0).forEach((Z)=>{Z._lifeCycleHooks[q].forEach((z)=>{X.push({hookedCommand:Z,callback:z})})}),q==="postAction")X.reverse();return X.forEach((Z)=>{J=this._chainOrCall(J,()=>{return Z.callback(Z.hookedCommand,this)})}),J}_chainOrCallSubCommandHook($,q,J){let X=$;if(this._lifeCycleHooks[J]!==void 0)this._lifeCycleHooks[J].forEach((Z)=>{X=this._chainOrCall(X,()=>{return Z(this,q)})});return X}_parseCommand($,q){let J=this.parseOptions(q);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(J.operands),q=J.unknown,this.args=$.concat(q),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),q);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(q),this._dispatchSubcommand(this._defaultCommandName,$,q);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(J.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=()=>{if(J.unknown.length>0)this.unknownOption(J.unknown[0])},Z=`command:${this.name()}`;if(this._actionHandler){X(),this._processArguments();let z;if(z=this._chainOrCallHooks(z,"preAction"),z=this._chainOrCall(z,()=>this._actionHandler(this.processedArgs)),this.parent)z=this._chainOrCall(z,()=>{this.parent.emit(Z,$,q)});return z=this._chainOrCallHooks(z,"postAction"),z}if(this.parent?.listenerCount(Z))X(),this._processArguments(),this.parent.emit(Z,$,q);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,q);if(this.listenerCount("command:*"))this.emit("command:*",$,q);else if(this.commands.length)this.unknownCommand();else X(),this._processArguments()}else if(this.commands.length)X(),this.help({error:!0});else X(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((q)=>q._name===$||q._aliases.includes($))}_findOption($){return this.options.find((q)=>q.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((q)=>{if(q.mandatory&&$.getOptionValue(q.attributeName())===void 0)$.missingMandatoryOptionValue(q)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((J)=>{let X=J.attributeName();if(this.getOptionValue(X)===void 0)return!1;return this.getOptionValueSource(X)!=="default"});$.filter((J)=>J.conflictsWith.length>0).forEach((J)=>{let X=$.find((Z)=>J.conflictsWith.includes(Z.attributeName()));if(X)this._conflictingOption(J,X)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let q=[],J=[],X=q;function Z(Y){return Y.length>1&&Y[0]==="-"}let z=(Y)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(Y))return!1;return!this._getCommandAndAncestors().some((W)=>W.options.map((V)=>V.short).some((V)=>/^-\d$/.test(V)))},Q=null,G=null,B=0;while(B<$.length||G){let Y=G??$[B++];if(G=null,Y==="--"){if(X===J)X.push(Y);X.push(...$.slice(B));break}if(Q&&(!Z(Y)||z(Y))){this.emit(`option:${Q.name()}`,Y);continue}if(Q=null,Z(Y)){let W=this._findOption(Y);if(W){if(W.required){let V=$[B++];if(V===void 0)this.optionMissingArgument(W);this.emit(`option:${W.name()}`,V)}else if(W.optional){let V=null;if(B<$.length&&(!Z($[B])||z($[B])))V=$[B++];this.emit(`option:${W.name()}`,V)}else this.emit(`option:${W.name()}`);Q=W.variadic?W:null;continue}}if(Y.length>2&&Y[0]==="-"&&Y[1]!=="-"){let W=this._findOption(`-${Y[1]}`);if(W){if(W.required||W.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${W.name()}`,Y.slice(2));else this.emit(`option:${W.name()}`),G=`-${Y.slice(2)}`;continue}}if(/^--[^=]+=/.test(Y)){let W=Y.indexOf("="),V=this._findOption(Y.slice(0,W));if(V&&(V.required||V.optional)){this.emit(`option:${V.name()}`,Y.slice(W+1));continue}}if(X===q&&Z(Y)&&!(this.commands.length===0&&z(Y)))X=J;if((this._enablePositionalOptions||this._passThroughOptions)&&q.length===0&&J.length===0){if(this._findCommand(Y)){q.push(Y),J.push(...$.slice(B));break}else if(this._getHelpCommand()&&Y===this._getHelpCommand().name()){q.push(Y,...$.slice(B));break}else if(this._defaultCommandName){J.push(Y,...$.slice(B));break}}if(this._passThroughOptions){X.push(Y,...$.slice(B));break}X.push(Y)}return{operands:q,unknown:J}}opts(){if(this._storeOptionsAsProperties){let $={},q=this.options.length;for(let J=0;J<q;J++){let X=this.options[J].attributeName();$[X]=X===this._versionOptionName?this._version:this[X]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,q)=>Object.assign($,q.opts()),{})}error($,q){if(this._outputConfiguration.outputError(`${$}
|
|
22
22
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
23
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
24
|
-
`),this.outputHelp({error:!0});let
|
|
25
|
-
`),this._exit(0,"commander.version",$)}),this}description($,q){if($===void 0&&q===void 0)return this._description;if(this._description=$,q)this._argsDescription=q;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let q=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)q=this.commands[this.commands.length-1];if($===q._name)throw Error("Command alias can't be the same as its name");let
|
|
26
|
-
Expecting one of '${
|
|
27
|
-
`)}),this}_outputHelpIfRequested($){let q=this._getHelpOption();if(q&&$.find((
|
|
28
|
-
`,[f$]:"\f",[_q]:"\r",[E]:'"',[M0]:"\\"};function K($){return $>=v&&$<=k$}function G0($){return $>=w0&&$<=u2||$>=G$&&$<=f$||$>=v&&$<=k$}function l2($){return $===A2||$===v}function p2($){return $>=v&&$<=b2}function a2($){return $>=w0&&$<=j$||$>=G$&&$<=yq||$>=v&&$<=k$||$===R||$===E||$===O||$===T}function o2($){return $>=w0&&$<=j$||$>=G$&&$<=yq||$>=v&&$<=k$||$===O||$===T}var P=Symbol("type"),Q$=Symbol("declared"),r2=Object.prototype.hasOwnProperty,e2=Object.defineProperty,$8={configurable:!0,enumerable:!0,writable:!0,value:void 0};function u($,q){if(r2.call($,q))return!0;if(q==="__proto__")e2($,"__proto__",$8);return!1}var S0=Symbol("inline-table");function jq(){return Object.defineProperties({},{[P]:{value:S0}})}function q8($){if($===null||typeof $!=="object")return!1;return $[P]===S0}var K0=Symbol("table");function n(){return Object.defineProperties({},{[P]:{value:K0},[Q$]:{value:!1,writable:!0}})}function z$($){if($===null||typeof $!=="object")return!1;return $[P]===K0}var Rq=Symbol("content-type"),F0=Symbol("inline-list");function kq($){return Object.defineProperties([],{[P]:{value:F0},[Rq]:{value:$}})}function Hq($){if($===null||typeof $!=="object")return!1;return $[P]===F0}var N0=Symbol("list");function X8(){return Object.defineProperties([],{[P]:{value:N0}})}function U0($){if($===null||typeof $!=="object")return!1;return $[P]===N0}var Tq;try{let utilInspect=eval("require('util').inspect");Tq=utilInspect.custom}catch($){}var P0=Tq||"inspect";class Aq{constructor($){try{this.value=global.BigInt.asIntN(64,$)}catch(q){this.value=null}Object.defineProperty(this,P,{value:H$})}isNaN(){return this.value===null}toString(){return String(this.value)}[P0](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}}var H$=Symbol("integer");function d($){let q=Number($);if(Object.is(q,-0))q=0;if(global.BigInt&&!Number.isSafeInteger(q))return new Aq($);else return Object.defineProperties(new Number(q),{isNaN:{value:function(){return isNaN(this)}},[P]:{value:H$},[P0]:{value:()=>`[Integer: ${$}]`}})}function W0($){if($===null||typeof $!=="object")return!1;return $[P]===H$}var D0=Symbol("float");function Oq($){return Object.defineProperties(new Number($),{[P]:{value:D0},[P0]:{value:()=>`[Float: ${$}]`}})}function B0($){if($===null||typeof $!=="object")return!1;return $[P]===D0}function Eq($){let q=typeof $;if(q==="object"){if($===null)return"null";if($ instanceof Date)return"datetime";if(P in $)switch($[P]){case S0:return"inline-table";case F0:return"inline-list";case K0:return"table";case N0:return"list";case D0:return"float";case H$:return"integer"}}return q}function bq($){class q extends ${constructor(){super();this.ctx=this.obj=n()}atEndOfWord(){return this.char===t||this.char===S||this.char===F||this.atEndOfLine()}atEndOfLine(){return this.char===$.END||this.char===N||this.char===D}parseStart(){if(this.char===$.END)return null;else if(this.char===f0)return this.call(this.parseTableOrList);else if(this.char===t)return this.call(this.parseComment);else if(this.char===N||this.char===F||this.char===S||this.char===D)return null;else if(a2(this.char))return this.callNow(this.parseAssignStatement);else throw this.error(new U(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===F||this.char===S||this.char===D)return null;else if(this.char===t)return this.goto(this.parseComment);else if(this.char===$.END||this.char===N)return this.return();else throw this.error(new U("Unexpected character, expected only whitespace or comments till end of line"))}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(X){let Z=this.ctx,Y=X.key.pop();for(let z of X.key){if(u(Z,z)&&(!z$(Z[z])||Z[z][Q$]))throw this.error(new U("Can't redefine existing key"));Z=Z[z]=Z[z]||n()}if(u(Z,Y))throw this.error(new U("Can't redefine existing key"));if(W0(X.value)||B0(X.value))Z[Y]=X.value.valueOf();else Z[Y]=X.value;return this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(X){if(this.state.resultTable)this.state.resultTable.push(X);else this.state.resultTable=[X];return this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===H)return this.next(this.parseAssignKeywordPostDot);else if(this.char!==F&&this.char!==S)return this.goto(this.parseAssignEqual)}parseAssignKeywordPostDot(){if(this.char!==F&&this.char!==S)return this.callNow(this.parseKeyword,this.recordAssignKeyword)}parseAssignEqual(){if(this.char===C2)return this.next(this.parseAssignPreValue);else throw this.error(new U('Invalid character, expected "="'))}parseAssignPreValue(){if(this.char===F||this.char===S)return null;else return this.callNow(this.parseValue,this.recordAssignValue)}recordAssignValue(X){return this.returnNow({key:this.state.resultTable,value:X})}parseComment(){do if(this.char===$.END||this.char===N)return this.return();while(this.nextChar())}parseTableOrList(){if(this.char===f0)this.next(this.parseList);else return this.goto(this.parseTable)}parseTable(){return this.ctx=this.obj,this.goto(this.parseTableNext)}parseTableNext(){if(this.char===F||this.char===S)return null;else return this.callNow(this.parseKeyword,this.parseTableMore)}parseTableMore(X){if(this.char===F||this.char===S)return null;else if(this.char===Y$){if(u(this.ctx,X)&&(!z$(this.ctx[X])||this.ctx[X][Q$]))throw this.error(new U("Can't redefine existing key"));else this.ctx=this.ctx[X]=this.ctx[X]||n(),this.ctx[Q$]=!0;return this.next(this.parseWhitespaceToEOL)}else if(this.char===H){if(!u(this.ctx,X))this.ctx=this.ctx[X]=n();else if(z$(this.ctx[X]))this.ctx=this.ctx[X];else if(U0(this.ctx[X]))this.ctx=this.ctx[X][this.ctx[X].length-1];else throw this.error(new U("Can't redefine existing key"));return this.next(this.parseTableNext)}else throw this.error(new U("Unexpected character, expected whitespace, . or ]"))}parseList(){return this.ctx=this.obj,this.goto(this.parseListNext)}parseListNext(){if(this.char===F||this.char===S)return null;else return this.callNow(this.parseKeyword,this.parseListMore)}parseListMore(X){if(this.char===F||this.char===S)return null;else if(this.char===Y$){if(!u(this.ctx,X))this.ctx[X]=X8();if(Hq(this.ctx[X]))throw this.error(new U("Can't extend an inline array"));else if(U0(this.ctx[X])){let Z=n();this.ctx[X].push(Z),this.ctx=Z}else throw this.error(new U("Can't redefine an existing key"));return this.next(this.parseListEnd)}else if(this.char===H){if(!u(this.ctx,X))this.ctx=this.ctx[X]=n();else if(Hq(this.ctx[X]))throw this.error(new U("Can't extend an inline array"));else if(q8(this.ctx[X]))throw this.error(new U("Can't extend an inline table"));else if(U0(this.ctx[X]))this.ctx=this.ctx[X][this.ctx[X].length-1];else if(z$(this.ctx[X]))this.ctx=this.ctx[X];else throw this.error(new U("Can't redefine an existing key"));return this.next(this.parseListNext)}else throw this.error(new U("Unexpected character, expected whitespace, . or ]"))}parseListEnd(X){if(this.char===Y$)return this.next(this.parseWhitespaceToEOL);else throw this.error(new U("Unexpected character, expected whitespace, . or ]"))}parseValue(){if(this.char===$.END)throw this.error(new U("Key without value"));else if(this.char===E)return this.next(this.parseDoubleString);if(this.char===R)return this.next(this.parseSingleString);else if(this.char===T||this.char===L$)return this.goto(this.parseNumberSign);else if(this.char===Dq)return this.next(this.parseInf);else if(this.char===J$)return this.next(this.parseNan);else if(K(this.char))return this.goto(this.parseNumberOrDateTime);else if(this.char===V0||this.char===f$)return this.goto(this.parseBoolean);else if(this.char===f0)return this.call(this.parseInlineList,this.recordValue);else if(this.char===n2)return this.call(this.parseInlineTable,this.recordValue);else throw this.error(new U("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}recordValue(X){return this.returnNow(X)}parseInf(){if(this.char===J$)return this.next(this.parseInf2);else throw this.error(new U('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseInf2(){if(this.char===f$)if(this.state.buf==="-")return this.return(-1/0);else return this.return(1/0);else throw this.error(new U('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseNan(){if(this.char===G$)return this.next(this.parseNan2);else throw this.error(new U('Unexpected character, expected "nan"'))}parseNan2(){if(this.char===J$)return this.return(NaN);else throw this.error(new U('Unexpected character, expected "nan"'))}parseKeyword(){if(this.char===E)return this.next(this.parseBasicString);else if(this.char===R)return this.next(this.parseLiteralString);else return this.goto(this.parseBareKey)}parseBareKey(){do if(this.char===$.END)throw this.error(new U("Key ended without value"));else if(o2(this.char))this.consume();else if(this.state.buf.length===0)throw this.error(new U("Empty bare keys are not allowed"));else return this.returnNow();while(this.nextChar())}parseSingleString(){if(this.char===R)return this.next(this.parseLiteralMultiStringMaybe);else return this.goto(this.parseLiteralString)}parseLiteralString(){do if(this.char===R)return this.return();else if(this.atEndOfLine())throw this.error(new U("Unterminated string"));else if(this.char===x$||this.char<=I$&&this.char!==S)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}parseLiteralMultiStringMaybe(){if(this.char===R)return this.next(this.parseLiteralMultiString);else return this.returnNow()}parseLiteralMultiString(){if(this.char===D)return null;else if(this.char===N)return this.next(this.parseLiteralMultiStringContent);else return this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiStringContent(){do if(this.char===R)return this.next(this.parseLiteralMultiEnd);else if(this.char===$.END)throw this.error(new U("Unterminated multi-line string"));else if(this.char===x$||this.char<=I$&&this.char!==S&&this.char!==N&&this.char!==D)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}parseLiteralMultiEnd(){if(this.char===R)return this.next(this.parseLiteralMultiEnd2);else return this.state.buf+="'",this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiEnd2(){if(this.char===R)return this.return();else return this.state.buf+="''",this.goto(this.parseLiteralMultiStringContent)}parseDoubleString(){if(this.char===E)return this.next(this.parseMultiStringMaybe);else return this.goto(this.parseBasicString)}parseBasicString(){do if(this.char===M0)return this.call(this.parseEscape,this.recordEscapeReplacement);else if(this.char===E)return this.return();else if(this.atEndOfLine())throw this.error(new U("Unterminated string"));else if(this.char===x$||this.char<=I$&&this.char!==S)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}recordEscapeReplacement(X){return this.state.buf+=X,this.goto(this.parseBasicString)}parseMultiStringMaybe(){if(this.char===E)return this.next(this.parseMultiString);else return this.returnNow()}parseMultiString(){if(this.char===D)return null;else if(this.char===N)return this.next(this.parseMultiStringContent);else return this.goto(this.parseMultiStringContent)}parseMultiStringContent(){do if(this.char===M0)return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement);else if(this.char===E)return this.next(this.parseMultiEnd);else if(this.char===$.END)throw this.error(new U("Unterminated multi-line string"));else if(this.char===x$||this.char<=I$&&this.char!==S&&this.char!==N&&this.char!==D)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}errorControlCharInString(){let X="\\u00";if(this.char<16)X+="0";return X+=this.char.toString(16),this.error(new U(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${X} instead`))}recordMultiEscapeReplacement(X){return this.state.buf+=X,this.goto(this.parseMultiStringContent)}parseMultiEnd(){if(this.char===E)return this.next(this.parseMultiEnd2);else return this.state.buf+='"',this.goto(this.parseMultiStringContent)}parseMultiEnd2(){if(this.char===E)return this.return();else return this.state.buf+='""',this.goto(this.parseMultiStringContent)}parseMultiEscape(){if(this.char===D||this.char===N)return this.next(this.parseMultiTrim);else if(this.char===F||this.char===S)return this.next(this.parsePreMultiTrim);else return this.goto(this.parseEscape)}parsePreMultiTrim(){if(this.char===F||this.char===S)return null;else if(this.char===D||this.char===N)return this.next(this.parseMultiTrim);else throw this.error(new U("Can't escape whitespace"))}parseMultiTrim(){if(this.char===N||this.char===F||this.char===S||this.char===D)return null;else return this.returnNow()}parseEscape(){if(this.char in xq)return this.return(xq[this.char]);else if(this.char===Iq)return this.call(this.parseSmallUnicode,this.parseUnicodeReturn);else if(this.char===c2)return this.call(this.parseLargeUnicode,this.parseUnicodeReturn);else throw this.error(new U("Unknown escape character: "+this.char))}parseUnicodeReturn(X){try{let Z=parseInt(X,16);if(Z>=d2&&Z<=s2)throw this.error(new U("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));return this.returnNow(String.fromCodePoint(Z))}catch(Z){throw this.error(U.wrap(Z))}}parseSmallUnicode(){if(!G0(this.char))throw this.error(new U("Invalid character in unicode sequence, expected hex"));else if(this.consume(),this.state.buf.length>=4)return this.return()}parseLargeUnicode(){if(!G0(this.char))throw this.error(new U("Invalid character in unicode sequence, expected hex"));else if(this.consume(),this.state.buf.length>=8)return this.return()}parseNumberSign(){return this.consume(),this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){if(this.char===Dq)return this.next(this.parseInf);else if(this.char===J$)return this.next(this.parseNan);else return this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}parseNumberIntegerStart(){if(this.char===v)return this.consume(),this.next(this.parseNumberIntegerExponentOrDecimal);else return this.goto(this.parseNumberInteger)}parseNumberIntegerExponentOrDecimal(){if(this.char===H)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===Z$||this.char===i)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(d(this.state.buf))}parseNumberInteger(){if(K(this.char))this.consume();else if(this.char===O)return this.call(this.parseNoUnder);else if(this.char===Z$||this.char===i)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===H)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else{let X=d(this.state.buf);if(X.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(X)}}parseNoUnder(){if(this.char===O||this.char===H||this.char===Z$||this.char===i)throw this.error(new U("Unexpected character, expected digit"));else if(this.atEndOfWord())throw this.error(new U("Incomplete number"));return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===O||this.char===H)throw this.error(new U("Unexpected character, expected digit"));else if(this.atEndOfWord())throw this.error(new U("Incomplete number"));return this.returnNow()}parseNumberFloat(){if(this.char===O)return this.call(this.parseNoUnder,this.parseNumberFloat);else if(K(this.char))this.consume();else if(this.char===Z$||this.char===i)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(Oq(this.state.buf))}parseNumberExponentSign(){if(K(this.char))return this.goto(this.parseNumberExponent);else if(this.char===T||this.char===L$)this.consume(),this.call(this.parseNoUnder,this.parseNumberExponent);else throw this.error(new U("Unexpected character, expected -, + or digit"))}parseNumberExponent(){if(K(this.char))this.consume();else if(this.char===O)return this.call(this.parseNoUnder);else return this.returnNow(Oq(this.state.buf))}parseNumberOrDateTime(){if(this.char===v)return this.consume(),this.next(this.parseNumberBaseOrDateTime);else return this.goto(this.parseNumberOrDateTimeOnly)}parseNumberOrDateTimeOnly(){if(this.char===O)return this.call(this.parseNoUnder,this.parseNumberInteger);else if(K(this.char)){if(this.consume(),this.state.buf.length>4)this.next(this.parseNumberInteger)}else if(this.char===Z$||this.char===i)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===H)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===T)return this.goto(this.parseDateTime);else if(this.char===m)return this.goto(this.parseOnlyTimeHour);else return this.returnNow(d(this.state.buf))}parseDateTimeOnly(){if(this.state.buf.length<4)if(K(this.char))return this.consume();else if(this.char===m)return this.goto(this.parseOnlyTimeHour);else throw this.error(new U("Expected digit while parsing year part of a date"));else if(this.char===T)return this.goto(this.parseDateTime);else throw this.error(new U("Expected hyphen (-) while parsing year part of date"))}parseNumberBaseOrDateTime(){if(this.char===hq)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin);else if(this.char===t2)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct);else if(this.char===i2)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex);else if(this.char===H)return this.goto(this.parseNumberInteger);else if(K(this.char))return this.goto(this.parseDateTimeOnly);else return this.returnNow(d(this.state.buf))}parseIntegerHex(){if(G0(this.char))this.consume();else if(this.char===O)return this.call(this.parseNoUnderHexOctBinLiteral);else{let X=d(this.state.buf);if(X.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(X)}}parseIntegerOct(){if(p2(this.char))this.consume();else if(this.char===O)return this.call(this.parseNoUnderHexOctBinLiteral);else{let X=d(this.state.buf);if(X.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(X)}}parseIntegerBin(){if(l2(this.char))this.consume();else if(this.char===O)return this.call(this.parseNoUnderHexOctBinLiteral);else{let X=d(this.state.buf);if(X.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(X)}}parseDateTime(){if(this.state.buf.length<4)throw this.error(new U("Years less than 1000 must be zero padded to four characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===T){if(this.state.buf.length<2)throw this.error(new U("Months less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseDateDay)}else if(K(this.char))this.consume();else throw this.error(new U("Incomplete datetime"))}parseDateDay(){if(this.char===v2||this.char===F){if(this.state.buf.length<2)throw this.error(new U("Days less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseStartTimeHour)}else if(this.atEndOfWord())return this.returnNow(Fq(this.state.result+"-"+this.state.buf));else if(K(this.char))this.consume();else throw this.error(new U("Incomplete datetime"))}parseStartTimeHour(){if(this.atEndOfWord())return this.returnNow(Fq(this.state.result));else return this.goto(this.parseTimeHour)}parseTimeHour(){if(this.char===m){if(this.state.buf.length<2)throw this.error(new U("Hours less than 10 must be zero padded to two characters"));return this.state.result+="T"+this.state.buf,this.state.buf="",this.next(this.parseTimeMin)}else if(K(this.char))this.consume();else throw this.error(new U("Incomplete datetime"))}parseTimeMin(){if(this.state.buf.length<2&&K(this.char))this.consume();else if(this.state.buf.length===2&&this.char===m)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeSec);else throw this.error(new U("Incomplete datetime"))}parseTimeSec(){if(K(this.char)){if(this.consume(),this.state.buf.length===2)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeZoneOrFraction)}else throw this.error(new U("Incomplete datetime"))}parseOnlyTimeHour(){if(this.char===m){if(this.state.buf.length<2)throw this.error(new U("Hours less than 10 must be zero padded to two characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeMin)}else throw this.error(new U("Incomplete time"))}parseOnlyTimeMin(){if(this.state.buf.length<2&&K(this.char))this.consume();else if(this.state.buf.length===2&&this.char===m)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeSec);else throw this.error(new U("Incomplete time"))}parseOnlyTimeSec(){if(K(this.char)){if(this.consume(),this.state.buf.length===2)return this.next(this.parseOnlyTimeFractionMaybe)}else throw this.error(new U("Incomplete time"))}parseOnlyTimeFractionMaybe(){if(this.state.result+=":"+this.state.buf,this.char===H)this.state.buf="",this.next(this.parseOnlyTimeFraction);else return this.return(Nq(this.state.result))}parseOnlyTimeFraction(){if(K(this.char))this.consume();else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new U("Expected digit in milliseconds"));return this.returnNow(Nq(this.state.result+"."+this.state.buf))}else throw this.error(new U("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneOrFraction(){if(this.char===H)this.consume(),this.next(this.parseDateTimeFraction);else if(this.char===T||this.char===L$)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===j$)return this.consume(),this.return(Q0(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(Kq(this.state.result+this.state.buf));else throw this.error(new U("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseDateTimeFraction(){if(K(this.char))this.consume();else if(this.state.buf.length===1)throw this.error(new U("Expected digit in milliseconds"));else if(this.char===T||this.char===L$)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===j$)return this.consume(),this.return(Q0(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(Kq(this.state.result+this.state.buf));else throw this.error(new U("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneHour(){if(K(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else throw this.error(new U("Unexpected character in datetime, expected digit"))}parseTimeZoneSep(){if(this.char===m)this.consume(),this.next(this.parseTimeZoneMin);else throw this.error(new U("Unexpected character in datetime, expected colon"))}parseTimeZoneMin(){if(K(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.return(Q0(this.state.result+this.state.buf))}else throw this.error(new U("Unexpected character in datetime, expected digit"))}parseBoolean(){if(this.char===V0)return this.consume(),this.next(this.parseTrue_r);else if(this.char===f$)return this.consume(),this.next(this.parseFalse_a)}parseTrue_r(){if(this.char===_q)return this.consume(),this.next(this.parseTrue_u);else throw this.error(new U("Invalid boolean, expected true or false"))}parseTrue_u(){if(this.char===Iq)return this.consume(),this.next(this.parseTrue_e);else throw this.error(new U("Invalid boolean, expected true or false"))}parseTrue_e(){if(this.char===i)return this.return(!0);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_a(){if(this.char===G$)return this.consume(),this.next(this.parseFalse_l);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_l(){if(this.char===g2)return this.consume(),this.next(this.parseFalse_s);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_s(){if(this.char===m2)return this.consume(),this.next(this.parseFalse_e);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_e(){if(this.char===i)return this.return(!1);else throw this.error(new U("Invalid boolean, expected true or false"))}parseInlineList(){if(this.char===F||this.char===S||this.char===D||this.char===N)return null;else if(this.char===$.END)throw this.error(new U("Unterminated inline array"));else if(this.char===t)return this.call(this.parseComment);else if(this.char===Y$)return this.return(this.state.resultArr||kq());else return this.callNow(this.parseValue,this.recordInlineListValue)}recordInlineListValue(X){if(this.state.resultArr){let Z=this.state.resultArr[Rq],Y=Eq(X);if(Z!==Y)throw this.error(new U(`Inline lists must be a single type, not a mix of ${Z} and ${Y}`))}else this.state.resultArr=kq(Eq(X));if(B0(X)||W0(X))this.state.resultArr.push(X.valueOf());else this.state.resultArr.push(X);return this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===F||this.char===S||this.char===D||this.char===N)return null;else if(this.char===t)return this.call(this.parseComment);else if(this.char===Pq)return this.next(this.parseInlineList);else if(this.char===Y$)return this.goto(this.parseInlineList);else throw this.error(new U("Invalid character, expected whitespace, comma (,) or close bracket (])"))}parseInlineTable(){if(this.char===F||this.char===S)return null;else if(this.char===$.END||this.char===t||this.char===N||this.char===D)throw this.error(new U("Unterminated inline array"));else if(this.char===Lq)return this.return(this.state.resultTable||jq());else{if(!this.state.resultTable)this.state.resultTable=jq();return this.callNow(this.parseAssign,this.recordInlineTableValue)}}recordInlineTableValue(X){let Z=this.state.resultTable,Y=X.key.pop();for(let z of X.key){if(u(Z,z)&&(!z$(Z[z])||Z[z][Q$]))throw this.error(new U("Can't redefine existing key"));Z=Z[z]=Z[z]||n()}if(u(Z,Y))throw this.error(new U("Can't redefine existing key"));if(W0(X.value)||B0(X.value))Z[Y]=X.value.valueOf();else Z[Y]=X.value;return this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===F||this.char===S)return null;else if(this.char===$.END||this.char===t||this.char===N||this.char===D)throw this.error(new U("Unterminated inline array"));else if(this.char===Pq)return this.next(this.parseInlineTable);else if(this.char===Lq)return this.goto(this.parseInlineTable);else throw this.error(new U("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}return q}});var E$=w((V3,uq)=>{uq.exports=Z8;function Z8($,q){if($.pos==null||$.line==null)return $;let X=$.message;if(X+=` at row ${$.line+1}, col ${$.col+1}, pos ${$.pos}:
|
|
29
|
-
`,q&&q.split){let
|
|
30
|
-
`,
|
|
31
|
-
`}else
|
|
32
|
-
`}}return $.message=
|
|
33
|
-
`,$}});var
|
|
34
|
-
`)}function
|
|
24
|
+
`),this.outputHelp({error:!0});let J=q||{},X=J.exitCode||1,Z=J.code||"commander.error";this._exit(X,Z,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in K.env){let q=$.attributeName();if(this.getOptionValue(q)===void 0||["default","config","env"].includes(this.getOptionValueSource(q)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,K.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new y3(this.options),q=(J)=>{return this.getOptionValue(J)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(J))};this.options.filter((J)=>J.implied!==void 0&&q(J.attributeName())&&$.valueFromOption(this.getOptionValue(J.attributeName()),J)).forEach((J)=>{Object.keys(J.implied).filter((X)=>!q(X)).forEach((X)=>{this.setOptionValueWithSource(X,J.implied[X],"implied")})})}missingArgument($){let q=`error: missing required argument '${$}'`;this.error(q,{code:"commander.missingArgument"})}optionMissingArgument($){let q=`error: option '${$.flags}' argument missing`;this.error(q,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let q=`error: required option '${$.flags}' not specified`;this.error(q,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,q){let J=(z)=>{let Q=z.attributeName(),G=this.getOptionValue(Q),B=this.options.find((W)=>W.negate&&Q===W.attributeName()),Y=this.options.find((W)=>!W.negate&&Q===W.attributeName());if(B&&(B.presetArg===void 0&&G===!1||B.presetArg!==void 0&&G===B.presetArg))return B;return Y||z},X=(z)=>{let Q=J(z),G=Q.attributeName();if(this.getOptionValueSource(G)==="env")return`environment variable '${Q.envVar}'`;return`option '${Q.flags}'`},Z=`error: ${X($)} cannot be used with ${X(q)}`;this.error(Z,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let q="";if($.startsWith("--")&&this._showSuggestionAfterError){let X=[],Z=this;do{let z=Z.createHelp().visibleOptions(Z).filter((Q)=>Q.long).map((Q)=>Q.long);X=X.concat(z),Z=Z.parent}while(Z&&!Z._enablePositionalOptions);q=Rq($,X)}let J=`error: unknown option '${$}'${q}`;this.error(J,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let q=this.registeredArguments.length,J=q===1?"":"s",Z=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${q} argument${J} but got ${$.length}.`;this.error(Z,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],q="";if(this._showSuggestionAfterError){let X=[];this.createHelp().visibleCommands(this).forEach((Z)=>{if(X.push(Z.name()),Z.alias())X.push(Z.alias())}),q=Rq($,X)}let J=`error: unknown command '${$}'${q}`;this.error(J,{code:"commander.unknownCommand"})}version($,q,J){if($===void 0)return this._version;this._version=$,q=q||"-V, --version",J=J||"output the version number";let X=this.createOption(q,J);return this._versionOptionName=X.attributeName(),this._registerOption(X),this.on("option:"+X.name(),()=>{this._outputConfiguration.writeOut(`${$}
|
|
25
|
+
`),this._exit(0,"commander.version",$)}),this}description($,q){if($===void 0&&q===void 0)return this._description;if(this._description=$,q)this._argsDescription=q;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let q=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)q=this.commands[this.commands.length-1];if($===q._name)throw Error("Command alias can't be the same as its name");let J=this.parent?._findCommand($);if(J){let X=[J.name()].concat(J.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${X}'`)}return q._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((q)=>this.alias(q)),this}usage($){if($===void 0){if(this._usage)return this._usage;let q=this.registeredArguments.map((J)=>{return H3(J)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?q:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}helpGroup($){if($===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=$,this}commandsGroup($){if($===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=$,this}optionsGroup($){if($===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=$,this}_initOptionGroup($){if(this._defaultOptionGroup&&!$.helpGroupHeading)$.helpGroup(this._defaultOptionGroup)}_initCommandGroup($){if(this._defaultCommandGroup&&!$.helpGroup())$.helpGroup(this._defaultCommandGroup)}nameFromFilename($){return this._name=l.basename($,l.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let q=this.createHelp(),J=this._getOutputContext($);q.prepareContext({error:J.error,helpWidth:J.helpWidth,outputHasColors:J.hasColors});let X=q.formatHelp(this,q);if(J.hasColors)return X;return this._outputConfiguration.stripColor(X)}_getOutputContext($){$=$||{};let q=!!$.error,J,X,Z;if(q)J=(Q)=>this._outputConfiguration.writeErr(Q),X=this._outputConfiguration.getErrHasColors(),Z=this._outputConfiguration.getErrHelpWidth();else J=(Q)=>this._outputConfiguration.writeOut(Q),X=this._outputConfiguration.getOutHasColors(),Z=this._outputConfiguration.getOutHelpWidth();return{error:q,write:(Q)=>{if(!X)Q=this._outputConfiguration.stripColor(Q);return J(Q)},hasColors:X,helpWidth:Z}}outputHelp($){let q;if(typeof $==="function")q=$,$=void 0;let J=this._getOutputContext($),X={error:J.error,write:J.write,command:this};this._getCommandAndAncestors().reverse().forEach((z)=>z.emit("beforeAllHelp",X)),this.emit("beforeHelp",X);let Z=this.helpInformation({error:J.error});if(q){if(Z=q(Z),typeof Z!=="string"&&!Buffer.isBuffer(Z))throw Error("outputHelp callback must return a string or a Buffer")}if(J.write(Z),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",X),this._getCommandAndAncestors().forEach((z)=>z.emit("afterAllHelp",X))}helpOption($,q){if(typeof $==="boolean"){if($){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption($??"-h, --help",q??"display help for command"),$||q)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this._initOptionGroup($),this}help($){this.outputHelp($);let q=Number(K.exitCode??0);if(q===0&&$&&typeof $!=="function"&&$.error)q=1;this._exit(q,"commander.help","(outputHelp)")}addHelpText($,q){let J=["beforeAll","before","after","afterAll"];if(!J.includes($))throw Error(`Unexpected value for position to addHelpText.
|
|
26
|
+
Expecting one of '${J.join("', '")}'`);let X=`${$}Help`;return this.on(X,(Z)=>{let z;if(typeof q==="function")z=q({error:Z.error,command:Z.command});else z=q;if(z)Z.write(`${z}
|
|
27
|
+
`)}),this}_outputHelpIfRequested($){let q=this._getHelpOption();if(q&&$.find((X)=>q.is(X)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Aq($){return $.map((q)=>{if(!q.startsWith("--inspect"))return q;let J,X="127.0.0.1",Z="9229",z;if((z=q.match(/^(--inspect(-brk)?)$/))!==null)J=z[1];else if((z=q.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(J=z[1],/^\d+$/.test(z[3]))Z=z[3];else X=z[3];else if((z=q.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)J=z[1],X=z[3],Z=z[4];if(J&&Z!=="0")return`${J}=${X}:${parseInt(Z)+1}`;return q})}function w0(){if(K.env.NO_COLOR||K.env.FORCE_COLOR==="0"||K.env.FORCE_COLOR==="false")return!1;if(K.env.FORCE_COLOR||K.env.CLICOLOR_FORCE!==void 0)return!0;return}T3.Command=x0;T3.useColor=w0});var uq=N((b3)=>{var{Argument:bq}=h$(),{Command:j0}=Eq(),{CommanderError:A3,InvalidArgumentError:hq}=P$(),{Help:E3}=S0(),{Option:Cq}=I0();b3.program=new j0;b3.createCommand=($)=>new j0($);b3.createOption=($,q)=>new Cq($,q);b3.createArgument=($,q)=>new bq($,q);b3.Command=j0;b3.Option=Cq;b3.Argument=bq;b3.Help=E3;b3.CommanderError=A3;b3.InvalidArgumentError=hq;b3.InvalidOptionArgumentError=hq});var dq=N((j4,mq)=>{class e extends Error{constructor($,q,J){super("[ParserError] "+$,q,J);if(this.name="ParserError",this.code="ParserError",Error.captureStackTrace)Error.captureStackTrace(this,e)}}class y0{constructor($){this.parser=$,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}}class g${constructor(){this.pos=0,this.col=0,this.line=0,this.obj={},this.ctx=this.obj,this.stack=[],this._buf="",this.char=null,this.ii=0,this.state=new y0(this.parseStart)}parse($){if($.length===0||$.length==null)return;this._buf=String($),this.ii=-1,this.char=-1;let q;while(q===!1||this.nextChar())q=this.runOne();this._buf=null}nextChar(){if(this.char===10)++this.line,this.col=-1;return++this.ii,this.char=this._buf.codePointAt(this.ii),++this.pos,++this.col,this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=1114112;let $;do $=this.state.parser,this.runOne();while(this.state.parser!==$);return this.ctx=null,this.state=null,this._buf=null,this.obj}next($){if(typeof $!=="function")throw new e("Tried to set state to non-existent state: "+JSON.stringify($));this.state.parser=$}goto($){return this.next($),this.runOne()}call($,q){if(q)this.next(q);this.stack.push(this.state),this.state=new y0($)}callNow($,q){return this.call($,q),this.runOne()}return($){if(this.stack.length===0)throw this.error(new e("Stack underflow"));if($===void 0)$=this.state.buf;this.state=this.stack.pop(),this.state.returned=$}returnNow($){return this.return($),this.runOne()}consume(){if(this.char===1114112)throw this.error(new e("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error($){return $.line=this.line,$.col=this.col,$.pos=this.pos,$}parseStart(){throw new e("Must declare a parseStart method")}}g$.END=1114112;g$.Error=e;mq.exports=g$});var nq=N((H4,lq)=>{lq.exports=($)=>{let q=new Date($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var c$=N((O4,iq)=>{iq.exports=($,q)=>{q=String(q);while(q.length<$)q="0"+q;return q}});var sq=N((_4,pq)=>{var V$=c$();class tq extends Date{constructor($){super($+"Z");this.isFloating=!0}toISOString(){let $=`${this.getUTCFullYear()}-${V$(2,this.getUTCMonth()+1)}-${V$(2,this.getUTCDate())}`,q=`${V$(2,this.getUTCHours())}:${V$(2,this.getUTCMinutes())}:${V$(2,this.getUTCSeconds())}.${V$(3,this.getUTCMilliseconds())}`;return`${$}T${q}`}}pq.exports=($)=>{let q=new tq($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var eq=N((y4,rq)=>{var aq=c$(),s3=global.Date;class oq extends s3{constructor($){super($);this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${aq(2,this.getUTCMonth()+1)}-${aq(2,this.getUTCDate())}`}}rq.exports=($)=>{let q=new oq($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var J2=N((T4,q2)=>{var m$=c$();class $2 extends Date{constructor($){super(`0000-01-01T${$}Z`);this.isTime=!0}toISOString(){return`${m$(2,this.getUTCHours())}:${m$(2,this.getUTCMinutes())}:${m$(2,this.getUTCSeconds())}.${m$(3,this.getUTCMilliseconds())}`}}q2.exports=($)=>{let q=new $2($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var s$=N((w2,_$)=>{_$.exports=L2(dq());_$.exports.makeParserClass=L2;class U extends Error{constructor($){super($);if(this.name="TomlError",Error.captureStackTrace)Error.captureStackTrace(this,U);this.fromTOML=!0,this.wrapped=null}}U.wrap=($)=>{let q=new U($.message);return q.code=$.code,q.wrapped=$,q};_$.exports.TomlError=U;var T0=nq(),X2=sq(),Z2=eq(),z2=J2(),P=9,_=10,R=13,d$=31,w=32,c=34,$$=35,n=39,l$=43,Q2=44,i=45,u=46,s=48,a3=49,o3=55,t$=57,q$=58,r3=61,u0=65,f$=69,e3=70,$6=84,q6=85,i$=90,v=95,O$=97,N2=98,J$=101,H$=102,G2=105,J6=108,x$=110,X6=111,P2=114,Z6=115,h0=116,Y2=117,z6=120,D2=122,Q6=123,W2=125,k0=91,C0=92,L$=93,n$=127,G6=55296,Y6=57343,B2={[N2]:"\b",[h0]:"\t",[x$]:`
|
|
28
|
+
`,[H$]:"\f",[P2]:"\r",[c]:'"',[C0]:"\\"};function f($){return $>=s&&$<=t$}function R0($){return $>=u0&&$<=e3||$>=O$&&$<=H$||$>=s&&$<=t$}function W6($){return $===a3||$===s}function B6($){return $>=s&&$<=o3}function U6($){return $>=u0&&$<=i$||$>=O$&&$<=D2||$>=s&&$<=t$||$===n||$===c||$===v||$===i}function V6($){return $>=u0&&$<=i$||$>=O$&&$<=D2||$>=s&&$<=t$||$===v||$===i}var y=Symbol("type"),j$=Symbol("declared"),M6=Object.prototype.hasOwnProperty,K6=Object.defineProperty,F6={configurable:!0,enumerable:!0,writable:!0,value:void 0};function p($,q){if(M6.call($,q))return!0;if(q==="__proto__")K6($,"__proto__",F6);return!1}var v0=Symbol("inline-table");function U2(){return Object.defineProperties({},{[y]:{value:v0}})}function N6($){if($===null||typeof $!=="object")return!1;return $[y]===v0}var g0=Symbol("table");function X$(){return Object.defineProperties({},{[y]:{value:g0},[j$]:{value:!1,writable:!0}})}function w$($){if($===null||typeof $!=="object")return!1;return $[y]===g0}var S2=Symbol("content-type"),c0=Symbol("inline-list");function V2($){return Object.defineProperties([],{[y]:{value:c0},[S2]:{value:$}})}function M2($){if($===null||typeof $!=="object")return!1;return $[y]===c0}var m0=Symbol("list");function P6(){return Object.defineProperties([],{[y]:{value:m0}})}function A0($){if($===null||typeof $!=="object")return!1;return $[y]===m0}var I2;try{let utilInspect=eval("require('util').inspect");I2=utilInspect.custom}catch($){}var d0=I2||"inspect";class f2{constructor($){try{this.value=global.BigInt.asIntN(64,$)}catch(q){this.value=null}Object.defineProperty(this,y,{value:p$})}isNaN(){return this.value===null}toString(){return String(this.value)}[d0](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}}var p$=Symbol("integer");function Z$($){let q=Number($);if(Object.is(q,-0))q=0;if(global.BigInt&&!Number.isSafeInteger(q))return new f2($);else return Object.defineProperties(new Number(q),{isNaN:{value:function(){return isNaN(this)}},[y]:{value:p$},[d0]:{value:()=>`[Integer: ${$}]`}})}function E0($){if($===null||typeof $!=="object")return!1;return $[y]===p$}var l0=Symbol("float");function K2($){return Object.defineProperties(new Number($),{[y]:{value:l0},[d0]:{value:()=>`[Float: ${$}]`}})}function b0($){if($===null||typeof $!=="object")return!1;return $[y]===l0}function F2($){let q=typeof $;if(q==="object"){if($===null)return"null";if($ instanceof Date)return"datetime";if(y in $)switch($[y]){case v0:return"inline-table";case c0:return"inline-list";case g0:return"table";case m0:return"list";case l0:return"float";case p$:return"integer"}}return q}function L2($){class q extends ${constructor(){super();this.ctx=this.obj=X$()}atEndOfWord(){return this.char===$$||this.char===P||this.char===w||this.atEndOfLine()}atEndOfLine(){return this.char===$.END||this.char===_||this.char===R}parseStart(){if(this.char===$.END)return null;else if(this.char===k0)return this.call(this.parseTableOrList);else if(this.char===$$)return this.call(this.parseComment);else if(this.char===_||this.char===w||this.char===P||this.char===R)return null;else if(U6(this.char))return this.callNow(this.parseAssignStatement);else throw this.error(new U(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===w||this.char===P||this.char===R)return null;else if(this.char===$$)return this.goto(this.parseComment);else if(this.char===$.END||this.char===_)return this.return();else throw this.error(new U("Unexpected character, expected only whitespace or comments till end of line"))}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(J){let X=this.ctx,Z=J.key.pop();for(let z of J.key){if(p(X,z)&&(!w$(X[z])||X[z][j$]))throw this.error(new U("Can't redefine existing key"));X=X[z]=X[z]||X$()}if(p(X,Z))throw this.error(new U("Can't redefine existing key"));if(E0(J.value)||b0(J.value))X[Z]=J.value.valueOf();else X[Z]=J.value;return this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(J){if(this.state.resultTable)this.state.resultTable.push(J);else this.state.resultTable=[J];return this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===u)return this.next(this.parseAssignKeywordPostDot);else if(this.char!==w&&this.char!==P)return this.goto(this.parseAssignEqual)}parseAssignKeywordPostDot(){if(this.char!==w&&this.char!==P)return this.callNow(this.parseKeyword,this.recordAssignKeyword)}parseAssignEqual(){if(this.char===r3)return this.next(this.parseAssignPreValue);else throw this.error(new U('Invalid character, expected "="'))}parseAssignPreValue(){if(this.char===w||this.char===P)return null;else return this.callNow(this.parseValue,this.recordAssignValue)}recordAssignValue(J){return this.returnNow({key:this.state.resultTable,value:J})}parseComment(){do if(this.char===$.END||this.char===_)return this.return();while(this.nextChar())}parseTableOrList(){if(this.char===k0)this.next(this.parseList);else return this.goto(this.parseTable)}parseTable(){return this.ctx=this.obj,this.goto(this.parseTableNext)}parseTableNext(){if(this.char===w||this.char===P)return null;else return this.callNow(this.parseKeyword,this.parseTableMore)}parseTableMore(J){if(this.char===w||this.char===P)return null;else if(this.char===L$){if(p(this.ctx,J)&&(!w$(this.ctx[J])||this.ctx[J][j$]))throw this.error(new U("Can't redefine existing key"));else this.ctx=this.ctx[J]=this.ctx[J]||X$(),this.ctx[j$]=!0;return this.next(this.parseWhitespaceToEOL)}else if(this.char===u){if(!p(this.ctx,J))this.ctx=this.ctx[J]=X$();else if(w$(this.ctx[J]))this.ctx=this.ctx[J];else if(A0(this.ctx[J]))this.ctx=this.ctx[J][this.ctx[J].length-1];else throw this.error(new U("Can't redefine existing key"));return this.next(this.parseTableNext)}else throw this.error(new U("Unexpected character, expected whitespace, . or ]"))}parseList(){return this.ctx=this.obj,this.goto(this.parseListNext)}parseListNext(){if(this.char===w||this.char===P)return null;else return this.callNow(this.parseKeyword,this.parseListMore)}parseListMore(J){if(this.char===w||this.char===P)return null;else if(this.char===L$){if(!p(this.ctx,J))this.ctx[J]=P6();if(M2(this.ctx[J]))throw this.error(new U("Can't extend an inline array"));else if(A0(this.ctx[J])){let X=X$();this.ctx[J].push(X),this.ctx=X}else throw this.error(new U("Can't redefine an existing key"));return this.next(this.parseListEnd)}else if(this.char===u){if(!p(this.ctx,J))this.ctx=this.ctx[J]=X$();else if(M2(this.ctx[J]))throw this.error(new U("Can't extend an inline array"));else if(N6(this.ctx[J]))throw this.error(new U("Can't extend an inline table"));else if(A0(this.ctx[J]))this.ctx=this.ctx[J][this.ctx[J].length-1];else if(w$(this.ctx[J]))this.ctx=this.ctx[J];else throw this.error(new U("Can't redefine an existing key"));return this.next(this.parseListNext)}else throw this.error(new U("Unexpected character, expected whitespace, . or ]"))}parseListEnd(J){if(this.char===L$)return this.next(this.parseWhitespaceToEOL);else throw this.error(new U("Unexpected character, expected whitespace, . or ]"))}parseValue(){if(this.char===$.END)throw this.error(new U("Key without value"));else if(this.char===c)return this.next(this.parseDoubleString);if(this.char===n)return this.next(this.parseSingleString);else if(this.char===i||this.char===l$)return this.goto(this.parseNumberSign);else if(this.char===G2)return this.next(this.parseInf);else if(this.char===x$)return this.next(this.parseNan);else if(f(this.char))return this.goto(this.parseNumberOrDateTime);else if(this.char===h0||this.char===H$)return this.goto(this.parseBoolean);else if(this.char===k0)return this.call(this.parseInlineList,this.recordValue);else if(this.char===Q6)return this.call(this.parseInlineTable,this.recordValue);else throw this.error(new U("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}recordValue(J){return this.returnNow(J)}parseInf(){if(this.char===x$)return this.next(this.parseInf2);else throw this.error(new U('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseInf2(){if(this.char===H$)if(this.state.buf==="-")return this.return(-1/0);else return this.return(1/0);else throw this.error(new U('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseNan(){if(this.char===O$)return this.next(this.parseNan2);else throw this.error(new U('Unexpected character, expected "nan"'))}parseNan2(){if(this.char===x$)return this.return(NaN);else throw this.error(new U('Unexpected character, expected "nan"'))}parseKeyword(){if(this.char===c)return this.next(this.parseBasicString);else if(this.char===n)return this.next(this.parseLiteralString);else return this.goto(this.parseBareKey)}parseBareKey(){do if(this.char===$.END)throw this.error(new U("Key ended without value"));else if(V6(this.char))this.consume();else if(this.state.buf.length===0)throw this.error(new U("Empty bare keys are not allowed"));else return this.returnNow();while(this.nextChar())}parseSingleString(){if(this.char===n)return this.next(this.parseLiteralMultiStringMaybe);else return this.goto(this.parseLiteralString)}parseLiteralString(){do if(this.char===n)return this.return();else if(this.atEndOfLine())throw this.error(new U("Unterminated string"));else if(this.char===n$||this.char<=d$&&this.char!==P)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}parseLiteralMultiStringMaybe(){if(this.char===n)return this.next(this.parseLiteralMultiString);else return this.returnNow()}parseLiteralMultiString(){if(this.char===R)return null;else if(this.char===_)return this.next(this.parseLiteralMultiStringContent);else return this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiStringContent(){do if(this.char===n)return this.next(this.parseLiteralMultiEnd);else if(this.char===$.END)throw this.error(new U("Unterminated multi-line string"));else if(this.char===n$||this.char<=d$&&this.char!==P&&this.char!==_&&this.char!==R)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}parseLiteralMultiEnd(){if(this.char===n)return this.next(this.parseLiteralMultiEnd2);else return this.state.buf+="'",this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiEnd2(){if(this.char===n)return this.return();else return this.state.buf+="''",this.goto(this.parseLiteralMultiStringContent)}parseDoubleString(){if(this.char===c)return this.next(this.parseMultiStringMaybe);else return this.goto(this.parseBasicString)}parseBasicString(){do if(this.char===C0)return this.call(this.parseEscape,this.recordEscapeReplacement);else if(this.char===c)return this.return();else if(this.atEndOfLine())throw this.error(new U("Unterminated string"));else if(this.char===n$||this.char<=d$&&this.char!==P)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}recordEscapeReplacement(J){return this.state.buf+=J,this.goto(this.parseBasicString)}parseMultiStringMaybe(){if(this.char===c)return this.next(this.parseMultiString);else return this.returnNow()}parseMultiString(){if(this.char===R)return null;else if(this.char===_)return this.next(this.parseMultiStringContent);else return this.goto(this.parseMultiStringContent)}parseMultiStringContent(){do if(this.char===C0)return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement);else if(this.char===c)return this.next(this.parseMultiEnd);else if(this.char===$.END)throw this.error(new U("Unterminated multi-line string"));else if(this.char===n$||this.char<=d$&&this.char!==P&&this.char!==_&&this.char!==R)throw this.errorControlCharInString();else this.consume();while(this.nextChar())}errorControlCharInString(){let J="\\u00";if(this.char<16)J+="0";return J+=this.char.toString(16),this.error(new U(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${J} instead`))}recordMultiEscapeReplacement(J){return this.state.buf+=J,this.goto(this.parseMultiStringContent)}parseMultiEnd(){if(this.char===c)return this.next(this.parseMultiEnd2);else return this.state.buf+='"',this.goto(this.parseMultiStringContent)}parseMultiEnd2(){if(this.char===c)return this.return();else return this.state.buf+='""',this.goto(this.parseMultiStringContent)}parseMultiEscape(){if(this.char===R||this.char===_)return this.next(this.parseMultiTrim);else if(this.char===w||this.char===P)return this.next(this.parsePreMultiTrim);else return this.goto(this.parseEscape)}parsePreMultiTrim(){if(this.char===w||this.char===P)return null;else if(this.char===R||this.char===_)return this.next(this.parseMultiTrim);else throw this.error(new U("Can't escape whitespace"))}parseMultiTrim(){if(this.char===_||this.char===w||this.char===P||this.char===R)return null;else return this.returnNow()}parseEscape(){if(this.char in B2)return this.return(B2[this.char]);else if(this.char===Y2)return this.call(this.parseSmallUnicode,this.parseUnicodeReturn);else if(this.char===q6)return this.call(this.parseLargeUnicode,this.parseUnicodeReturn);else throw this.error(new U("Unknown escape character: "+this.char))}parseUnicodeReturn(J){try{let X=parseInt(J,16);if(X>=G6&&X<=Y6)throw this.error(new U("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));return this.returnNow(String.fromCodePoint(X))}catch(X){throw this.error(U.wrap(X))}}parseSmallUnicode(){if(!R0(this.char))throw this.error(new U("Invalid character in unicode sequence, expected hex"));else if(this.consume(),this.state.buf.length>=4)return this.return()}parseLargeUnicode(){if(!R0(this.char))throw this.error(new U("Invalid character in unicode sequence, expected hex"));else if(this.consume(),this.state.buf.length>=8)return this.return()}parseNumberSign(){return this.consume(),this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){if(this.char===G2)return this.next(this.parseInf);else if(this.char===x$)return this.next(this.parseNan);else return this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}parseNumberIntegerStart(){if(this.char===s)return this.consume(),this.next(this.parseNumberIntegerExponentOrDecimal);else return this.goto(this.parseNumberInteger)}parseNumberIntegerExponentOrDecimal(){if(this.char===u)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===f$||this.char===J$)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(Z$(this.state.buf))}parseNumberInteger(){if(f(this.char))this.consume();else if(this.char===v)return this.call(this.parseNoUnder);else if(this.char===f$||this.char===J$)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===u)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else{let J=Z$(this.state.buf);if(J.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(J)}}parseNoUnder(){if(this.char===v||this.char===u||this.char===f$||this.char===J$)throw this.error(new U("Unexpected character, expected digit"));else if(this.atEndOfWord())throw this.error(new U("Incomplete number"));return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===v||this.char===u)throw this.error(new U("Unexpected character, expected digit"));else if(this.atEndOfWord())throw this.error(new U("Incomplete number"));return this.returnNow()}parseNumberFloat(){if(this.char===v)return this.call(this.parseNoUnder,this.parseNumberFloat);else if(f(this.char))this.consume();else if(this.char===f$||this.char===J$)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(K2(this.state.buf))}parseNumberExponentSign(){if(f(this.char))return this.goto(this.parseNumberExponent);else if(this.char===i||this.char===l$)this.consume(),this.call(this.parseNoUnder,this.parseNumberExponent);else throw this.error(new U("Unexpected character, expected -, + or digit"))}parseNumberExponent(){if(f(this.char))this.consume();else if(this.char===v)return this.call(this.parseNoUnder);else return this.returnNow(K2(this.state.buf))}parseNumberOrDateTime(){if(this.char===s)return this.consume(),this.next(this.parseNumberBaseOrDateTime);else return this.goto(this.parseNumberOrDateTimeOnly)}parseNumberOrDateTimeOnly(){if(this.char===v)return this.call(this.parseNoUnder,this.parseNumberInteger);else if(f(this.char)){if(this.consume(),this.state.buf.length>4)this.next(this.parseNumberInteger)}else if(this.char===f$||this.char===J$)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===u)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===i)return this.goto(this.parseDateTime);else if(this.char===q$)return this.goto(this.parseOnlyTimeHour);else return this.returnNow(Z$(this.state.buf))}parseDateTimeOnly(){if(this.state.buf.length<4)if(f(this.char))return this.consume();else if(this.char===q$)return this.goto(this.parseOnlyTimeHour);else throw this.error(new U("Expected digit while parsing year part of a date"));else if(this.char===i)return this.goto(this.parseDateTime);else throw this.error(new U("Expected hyphen (-) while parsing year part of date"))}parseNumberBaseOrDateTime(){if(this.char===N2)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin);else if(this.char===X6)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct);else if(this.char===z6)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex);else if(this.char===u)return this.goto(this.parseNumberInteger);else if(f(this.char))return this.goto(this.parseDateTimeOnly);else return this.returnNow(Z$(this.state.buf))}parseIntegerHex(){if(R0(this.char))this.consume();else if(this.char===v)return this.call(this.parseNoUnderHexOctBinLiteral);else{let J=Z$(this.state.buf);if(J.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(J)}}parseIntegerOct(){if(B6(this.char))this.consume();else if(this.char===v)return this.call(this.parseNoUnderHexOctBinLiteral);else{let J=Z$(this.state.buf);if(J.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(J)}}parseIntegerBin(){if(W6(this.char))this.consume();else if(this.char===v)return this.call(this.parseNoUnderHexOctBinLiteral);else{let J=Z$(this.state.buf);if(J.isNaN())throw this.error(new U("Invalid number"));else return this.returnNow(J)}}parseDateTime(){if(this.state.buf.length<4)throw this.error(new U("Years less than 1000 must be zero padded to four characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===i){if(this.state.buf.length<2)throw this.error(new U("Months less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseDateDay)}else if(f(this.char))this.consume();else throw this.error(new U("Incomplete datetime"))}parseDateDay(){if(this.char===$6||this.char===w){if(this.state.buf.length<2)throw this.error(new U("Days less than 10 must be zero padded to two characters"));return this.state.result+="-"+this.state.buf,this.state.buf="",this.next(this.parseStartTimeHour)}else if(this.atEndOfWord())return this.returnNow(Z2(this.state.result+"-"+this.state.buf));else if(f(this.char))this.consume();else throw this.error(new U("Incomplete datetime"))}parseStartTimeHour(){if(this.atEndOfWord())return this.returnNow(Z2(this.state.result));else return this.goto(this.parseTimeHour)}parseTimeHour(){if(this.char===q$){if(this.state.buf.length<2)throw this.error(new U("Hours less than 10 must be zero padded to two characters"));return this.state.result+="T"+this.state.buf,this.state.buf="",this.next(this.parseTimeMin)}else if(f(this.char))this.consume();else throw this.error(new U("Incomplete datetime"))}parseTimeMin(){if(this.state.buf.length<2&&f(this.char))this.consume();else if(this.state.buf.length===2&&this.char===q$)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeSec);else throw this.error(new U("Incomplete datetime"))}parseTimeSec(){if(f(this.char)){if(this.consume(),this.state.buf.length===2)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeZoneOrFraction)}else throw this.error(new U("Incomplete datetime"))}parseOnlyTimeHour(){if(this.char===q$){if(this.state.buf.length<2)throw this.error(new U("Hours less than 10 must be zero padded to two characters"));return this.state.result=this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeMin)}else throw this.error(new U("Incomplete time"))}parseOnlyTimeMin(){if(this.state.buf.length<2&&f(this.char))this.consume();else if(this.state.buf.length===2&&this.char===q$)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeSec);else throw this.error(new U("Incomplete time"))}parseOnlyTimeSec(){if(f(this.char)){if(this.consume(),this.state.buf.length===2)return this.next(this.parseOnlyTimeFractionMaybe)}else throw this.error(new U("Incomplete time"))}parseOnlyTimeFractionMaybe(){if(this.state.result+=":"+this.state.buf,this.char===u)this.state.buf="",this.next(this.parseOnlyTimeFraction);else return this.return(z2(this.state.result))}parseOnlyTimeFraction(){if(f(this.char))this.consume();else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new U("Expected digit in milliseconds"));return this.returnNow(z2(this.state.result+"."+this.state.buf))}else throw this.error(new U("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneOrFraction(){if(this.char===u)this.consume(),this.next(this.parseDateTimeFraction);else if(this.char===i||this.char===l$)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===i$)return this.consume(),this.return(T0(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(X2(this.state.result+this.state.buf));else throw this.error(new U("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseDateTimeFraction(){if(f(this.char))this.consume();else if(this.state.buf.length===1)throw this.error(new U("Expected digit in milliseconds"));else if(this.char===i||this.char===l$)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===i$)return this.consume(),this.return(T0(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(X2(this.state.result+this.state.buf));else throw this.error(new U("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneHour(){if(f(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else throw this.error(new U("Unexpected character in datetime, expected digit"))}parseTimeZoneSep(){if(this.char===q$)this.consume(),this.next(this.parseTimeZoneMin);else throw this.error(new U("Unexpected character in datetime, expected colon"))}parseTimeZoneMin(){if(f(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.return(T0(this.state.result+this.state.buf))}else throw this.error(new U("Unexpected character in datetime, expected digit"))}parseBoolean(){if(this.char===h0)return this.consume(),this.next(this.parseTrue_r);else if(this.char===H$)return this.consume(),this.next(this.parseFalse_a)}parseTrue_r(){if(this.char===P2)return this.consume(),this.next(this.parseTrue_u);else throw this.error(new U("Invalid boolean, expected true or false"))}parseTrue_u(){if(this.char===Y2)return this.consume(),this.next(this.parseTrue_e);else throw this.error(new U("Invalid boolean, expected true or false"))}parseTrue_e(){if(this.char===J$)return this.return(!0);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_a(){if(this.char===O$)return this.consume(),this.next(this.parseFalse_l);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_l(){if(this.char===J6)return this.consume(),this.next(this.parseFalse_s);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_s(){if(this.char===Z6)return this.consume(),this.next(this.parseFalse_e);else throw this.error(new U("Invalid boolean, expected true or false"))}parseFalse_e(){if(this.char===J$)return this.return(!1);else throw this.error(new U("Invalid boolean, expected true or false"))}parseInlineList(){if(this.char===w||this.char===P||this.char===R||this.char===_)return null;else if(this.char===$.END)throw this.error(new U("Unterminated inline array"));else if(this.char===$$)return this.call(this.parseComment);else if(this.char===L$)return this.return(this.state.resultArr||V2());else return this.callNow(this.parseValue,this.recordInlineListValue)}recordInlineListValue(J){if(this.state.resultArr){let X=this.state.resultArr[S2],Z=F2(J);if(X!==Z)throw this.error(new U(`Inline lists must be a single type, not a mix of ${X} and ${Z}`))}else this.state.resultArr=V2(F2(J));if(b0(J)||E0(J))this.state.resultArr.push(J.valueOf());else this.state.resultArr.push(J);return this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===w||this.char===P||this.char===R||this.char===_)return null;else if(this.char===$$)return this.call(this.parseComment);else if(this.char===Q2)return this.next(this.parseInlineList);else if(this.char===L$)return this.goto(this.parseInlineList);else throw this.error(new U("Invalid character, expected whitespace, comma (,) or close bracket (])"))}parseInlineTable(){if(this.char===w||this.char===P)return null;else if(this.char===$.END||this.char===$$||this.char===_||this.char===R)throw this.error(new U("Unterminated inline array"));else if(this.char===W2)return this.return(this.state.resultTable||U2());else{if(!this.state.resultTable)this.state.resultTable=U2();return this.callNow(this.parseAssign,this.recordInlineTableValue)}}recordInlineTableValue(J){let X=this.state.resultTable,Z=J.key.pop();for(let z of J.key){if(p(X,z)&&(!w$(X[z])||X[z][j$]))throw this.error(new U("Can't redefine existing key"));X=X[z]=X[z]||X$()}if(p(X,Z))throw this.error(new U("Can't redefine existing key"));if(E0(J.value)||b0(J.value))X[Z]=J.value.valueOf();else X[Z]=J.value;return this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===w||this.char===P)return null;else if(this.char===$.END||this.char===$$||this.char===_||this.char===R)throw this.error(new U("Unterminated inline array"));else if(this.char===Q2)return this.next(this.parseInlineTable);else if(this.char===W2)return this.goto(this.parseInlineTable);else throw this.error(new U("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}return q}});var a$=N((k4,x2)=>{x2.exports=D6;function D6($,q){if($.pos==null||$.line==null)return $;let J=$.message;if(J+=` at row ${$.line+1}, col ${$.col+1}, pos ${$.pos}:
|
|
29
|
+
`,q&&q.split){let X=q.split(/\n/),Z=String(Math.min(X.length,$.line+3)).length,z=" ";while(z.length<Z)z+=" ";for(let Q=Math.max(0,$.line-1);Q<Math.min(X.length,$.line+2);++Q){let G=String(Q+1);if(G.length<Z)G=" "+G;if($.line===Q){J+=G+"> "+X[Q]+`
|
|
30
|
+
`,J+=z+" ";for(let B=0;B<$.col;++B)J+=" ";J+=`^
|
|
31
|
+
`}else J+=G+": "+X[Q]+`
|
|
32
|
+
`}}return $.message=J+`
|
|
33
|
+
`,$}});var H2=N((R4,j2)=>{j2.exports=f6;var S6=s$(),I6=a$();function f6($){if(global.Buffer&&global.Buffer.isBuffer($))$=$.toString("utf8");let q=new S6;try{return q.parse($),q.finish()}catch(J){throw I6(J,$)}}});var y2=N((A4,_2)=>{_2.exports=w6;var L6=s$(),O2=a$();function w6($,q){if(!q)q={};let J=0,X=q.blocksize||40960,Z=new L6;return new Promise((Q,G)=>{setImmediate(z,J,X,Q,G)});function z(Q,G,B,Y){if(Q>=$.length)try{return B(Z.finish())}catch(W){return Y(O2(W,$))}try{Z.parse($.slice(Q,Q+G)),setImmediate(z,Q+G,G,B,Y)}catch(W){Y(O2(W,$))}}}});var R2=N((E4,k2)=>{k2.exports=j6;var x6=Y$("stream"),T2=s$();function j6($){if($)return H6($);else return O6($)}function H6($){let q=new T2;return $.setEncoding("utf8"),new Promise((J,X)=>{let Z,z=!1,Q=!1;function G(){if(z=!0,Z)return;try{J(q.finish())}catch(W){X(W)}}function B(W){Q=!0,X(W)}$.once("end",G),$.once("error",B),Y();function Y(){Z=!0;let W;while((W=$.read())!==null)try{q.parse(W)}catch(V){return B(V)}if(Z=!1,z)return G();if(Q)return;$.once("readable",Y)}})}function O6(){let $=new T2;return new x6.Transform({objectMode:!0,transform(q,J,X){try{$.parse(q.toString(J))}catch(Z){this.emit("error",Z)}X()},flush(q){try{this.push($.finish())}catch(J){this.emit("error",J)}q()}})}});var A2=N((b4,y$)=>{y$.exports=H2();y$.exports.async=y2();y$.exports.stream=R2();y$.exports.prettyError=a$()});var c2=N((h4,t0)=>{t0.exports=_6;t0.exports.value=i0;function _6($){if($===null)throw z$("null");if($===void 0)throw z$("undefined");if(typeof $!=="object")throw z$(typeof $);if(typeof $.toJSON==="function")$=$.toJSON();if($==null)return null;let q=A($);if(q!=="table")throw z$(q);return n0("","",$)}function z$($){return Error("Can only stringify objects, not "+$)}function y6(){return Error("Array values can't have mixed types")}function E2($){return Object.keys($).filter((q)=>b2($[q]))}function T6($){return Object.keys($).filter((q)=>!b2($[q]))}function o$($){let q=Array.isArray($)?[]:Object.prototype.hasOwnProperty.call($,"__proto__")?{["__proto__"]:void 0}:{};for(let J of Object.keys($))if($[J]&&typeof $[J].toJSON==="function"&&!("toISOString"in $[J]))q[J]=$[J].toJSON();else q[J]=$[J];return q}function n0($,q,J){J=o$(J);var X,Z;X=E2(J),Z=T6(J);var z=[],Q=q||"";if(X.forEach((B)=>{var Y=A(J[B]);if(Y!=="undefined"&&Y!=="null")z.push(Q+r$(B)+" = "+u2(J[B],!0))}),z.length>0)z.push("");var G=$&&X.length>0?q+" ":"";return Z.forEach((B)=>{z.push(c6($,G,B,J[B]))}),z.join(`
|
|
34
|
+
`)}function b2($){switch(A($)){case"undefined":case"null":case"integer":case"nan":case"float":case"boolean":case"string":case"datetime":return!0;case"array":return $.length===0||A($[0])!=="table";case"table":return Object.keys($).length===0;default:return!1}}function A($){if($===void 0)return"undefined";else if($===null)return"null";else if(typeof $==="bigint"||Number.isInteger($)&&!Object.is($,-0))return"integer";else if(typeof $==="number")return"float";else if(typeof $==="boolean")return"boolean";else if(typeof $==="string")return"string";else if("toISOString"in $)return isNaN($)?"undefined":"datetime";else if(Array.isArray($))return"array";else return"table"}function r$($){var q=String($);if(/^[-A-Za-z0-9_]+$/.test(q))return q;else return h2(q)}function h2($){return'"'+C2($).replace(/"/g,"\\\"")+'"'}function k6($){return"'"+$+"'"}function R6($,q){while(q.length<$)q="0"+q;return q}function C2($){return $.replace(/\\/g,"\\\\").replace(/[\b]/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/([\u0000-\u001f\u007f])/,(q)=>"\\u"+R6(4,q.codePointAt(0).toString(16)))}function A6($){let q=$.split(/\n/).map((J)=>{return C2(J).replace(/"(?="")/g,"\\\"")}).join(`
|
|
35
35
|
`);if(q.slice(-1)==='"')q+="\\\n";return`"""
|
|
36
|
-
`+q+'"""'}function
|
|
37
|
-
`+
|
|
36
|
+
`+q+'"""'}function u2($,q){let J=A($);if(J==="string"){if(q&&/\n/.test($))J="string-multiline";else if(!/[\b\t\n\f\r']/.test($)&&/"/.test($))J="string-literal"}return i0($,J)}function i0($,q){if(!q)q=A($);switch(q){case"string-multiline":return A6($);case"string":return h2($);case"string-literal":return k6($);case"integer":return v2($);case"float":return E6($);case"boolean":return b6($);case"datetime":return h6($);case"array":return v6($.filter((J)=>A(J)!=="null"&&A(J)!=="undefined"&&A(J)!=="nan"));case"table":return g6($);default:throw z$(q)}}function v2($){return String($).replace(/\B(?=(\d{3})+(?!\d))/g,"_")}function E6($){if($===1/0)return"inf";else if($===-1/0)return"-inf";else if(Object.is($,NaN))return"nan";else if(Object.is($,-0))return"-0.0";var q=String($).split("."),J=q[0],X=q[1]||0;return v2(J)+"."+X}function b6($){return String($)}function h6($){return $.toISOString()}function C6($){return $==="float"||$==="integer"}function u6($){var q=A($[0]);if($.every((J)=>A(J)===q))return q;if($.every((J)=>C6(A(J))))return"float";return"mixed"}function g2($){let q=u6($);if(q==="mixed")throw y6();return q}function v6($){$=o$($);let q=g2($);var J="[",X=$.map((Z)=>i0(Z,q));if(X.join(", ").length>60||/\n/.test(X))J+=`
|
|
37
|
+
`+X.join(`,
|
|
38
38
|
`)+`
|
|
39
|
-
`;else
|
|
40
|
-
`;
|
|
41
|
-
`,
|
|
42
|
-
`;return z+I0(Y+".",q,Z)}});var j0=w((E8)=>{E8.parse=sq();E8.stringify=q1()});var r0=s$(o0(),1),{program:c6,createCommand:g6,createArgument:t6,createOption:m6,CommanderError:e0,InvalidArgumentError:i6,InvalidOptionArgumentError:n6,Command:x,Argument:d6,Option:s6,Help:l6}=r0.default;var X0=/^[a-z][a-z0-9-]{0,62}$/;var C={Success:0,AgentError:1,UserError:2,HookBlocked:3,BackendUnavailable:4,Interrupted:130};class X$ extends Error{code;constructor($,q,X){super(q,X);this.name="KmanError",this.code=$}}class B extends X${constructor($,q){super(C.UserError,$,q);this.name="UserError"}}class c extends X${constructor($,q){super(C.BackendUnavailable,$,q);this.name="BackendUnavailableError"}}import{mkdir as A$,readdir as g8,rename as t8,rm as m8,stat as i8,writeFile as Q1}from"node:fs/promises";import{join as b$}from"node:path";import{homedir as y2}from"node:os";import{join as o}from"node:path";function R2(){let $=process.env.KMAN_HOME;return $&&$.length>0?$:o(y2(),".kman")}function Z0(){return o(R2(),"agents")}function k($){return o(Z0(),$)}function K$($){return o(k($),"agent.toml")}function $q($,q="soul.md"){return o(k($),q)}function y($){return o(k($),"skills")}var Y0=["ask","auto","yolo"],z0=["text","json","stream-json"],qq={permission_mode:"ask",output_format:"text"};function F$($,q={}){return{name:$,description:q.description,runtime:{default:q.runtime?.default??"claude-code",...q.runtime?.model!==void 0?{model:q.runtime.model}:{}},soul:{prompt_file:q.soul?.prompt_file??"soul.md"},defaults:{max_turns:q.defaults?.max_turns,permission_mode:q.defaults?.permission_mode??qq.permission_mode,output_format:q.defaults?.output_format??qq.output_format},runtimeOverrides:q.runtimeOverrides??{}}}var X1=s$(j0(),1);import{readFile as y8}from"node:fs/promises";function e($){if(!X0.test($))throw new B(`Invalid agent name "${$}". Must match ${X0.source} (lowercase kebab-case, 1–63 chars).`)}function y$($){if(e($.name),!$.runtime||typeof $.runtime.default!=="string")throw new B(`Profile "${$.name}" is missing runtime.default.`);let q=$.defaults.permission_mode;if(q!==void 0&&!Y0.includes(q))throw new B(`Profile "${$.name}" has invalid permission_mode "${q}". Expected one of: ${Y0.join(", ")}.`);let X=$.defaults.output_format;if(X!==void 0&&!z0.includes(X))throw new B(`Profile "${$.name}" has invalid output_format "${X}". Expected one of: ${z0.join(", ")}.`);if($.defaults.max_turns!==void 0&&(!Number.isInteger($.defaults.max_turns)||$.defaults.max_turns<=0))throw new B(`Profile "${$.name}" has invalid max_turns ${$.defaults.max_turns}. Expected positive integer.`)}function R8($,q){if(typeof q!=="object"||q===null)throw new B(`Profile "${$}" is not a valid TOML object.`);let X=q,Z=typeof X.description==="string"?X.description:void 0,Y=X.runtime??{},z=typeof Y.default==="string"?Y.default:"claude-code",J=typeof Y.model==="string"?Y.model:void 0,Q={};for(let[L,b]of Object.entries(Y)){if(L==="default"||L==="model")continue;if(typeof b==="object"&&b!==null&&!Array.isArray(b)){let p=b,M$={};if(typeof p.permission_mode_raw==="string")M$.permission_mode_raw=p.permission_mode_raw;if(Array.isArray(p.extra_args))M$.extra_args=p.extra_args.filter((R1)=>typeof R1==="string");if(typeof p.model==="string")M$.model=p.model;Q[L]=M$}}let W=X.soul??{},f=typeof W.prompt_file==="string"?W.prompt_file:"soul.md",G=X.defaults??{},V={max_turns:typeof G.max_turns==="number"?G.max_turns:void 0,permission_mode:typeof G.permission_mode==="string"?G.permission_mode:void 0,output_format:typeof G.output_format==="string"?G.output_format:void 0},j=F$($,{description:Z,runtime:{default:z,...J!==void 0?{model:J}:{}},soul:{prompt_file:f},defaults:V,runtimeOverrides:Q});return y$(j),j}async function l($){let q=K$($),X;try{X=await y8(q,"utf8")}catch(Y){if(Y.code==="ENOENT")throw new B(`Agent "${$}" not found at ${q}.`);throw new B(`Failed to read profile for "${$}": ${Y.message}`,{cause:Y})}let Z;try{Z=X1.default.parse(X)}catch(Y){throw new B(`Failed to parse ${q}: ${Y.message}`,{cause:Y})}return R8($,{...Z,name:$})}var Z1=s$(j0(),1);import{writeFile as T8,mkdir as A8}from"node:fs/promises";import{dirname as b8}from"node:path";function C8($){y$($);let q={name:$.name};if($.description!==void 0)q.description=$.description;let X={default:$.runtime.default};if($.runtime.model!==void 0)X.model=$.runtime.model;for(let[Y,z]of Object.entries($.runtimeOverrides)){let J={};if(z.permission_mode_raw!==void 0)J.permission_mode_raw=z.permission_mode_raw;if(z.extra_args!==void 0)J.extra_args=[...z.extra_args];if(z.model!==void 0)J.model=z.model;if(Object.keys(J).length>0)X[Y]=J}q.runtime=X,q.soul={prompt_file:$.soul.prompt_file};let Z={};if($.defaults.max_turns!==void 0)Z.max_turns=$.defaults.max_turns;if($.defaults.permission_mode!==void 0)Z.permission_mode=$.defaults.permission_mode;if($.defaults.output_format!==void 0)Z.output_format=$.defaults.output_format;return q.defaults=Z,Z1.default.stringify(q)}async function k0($){let q=K$($.name);await A8(b8(q),{recursive:!0});let X=C8($);return await T8(q,X,"utf8"),q}import{readFile as u8}from"node:fs/promises";import{isAbsolute as v8,join as c8}from"node:path";async function R$($,q={}){let X=k($.name),Z=v8($.soul.prompt_file)?$.soul.prompt_file:c8(X,$.soul.prompt_file),Y="";try{Y=await u8(Z,"utf8")}catch(b){if(b.code==="ENOENT")Y="";else throw new B(`Failed to read soul prompt at ${Z}: ${b.message}`,{cause:b})}let z=q.backend??$.runtime.default,J=$.runtimeOverrides[z]??{},Q=q.model??J.model??$.runtime.model,W=q.permission??$.defaults.permission_mode??"ask",f=q.outputFormat??(q.stream?"stream-json":$.defaults.output_format??"text"),G=q.stream===!0||f==="stream-json",V=[...J.extra_args??[],...q.runtimeFlags??[]],j={...q.env};return{profile:$,agentDir:X,soulPrompt:Y,backend:z,...Q!==void 0?{model:Q}:{},permission:W,outputFormat:f,...$.defaults.max_turns!==void 0?{maxTurns:$.defaults.max_turns}:{},cwd:q.cwd??process.cwd(),extraArgs:V,...J.permission_mode_raw!==void 0?{permissionModeRaw:J.permission_mode_raw}:{},env:j,...q.task!==void 0?{task:q.task}:{},stream:G}}async function Y1($,q){return J1($,q,"run")}async function z1($,q){return J1($,q,"chat")}async function J1($,q,X){if(q.soulPrompt.trim().length>0&&!$.capabilities.supportsAppendSystemPrompt)throw new c(`Backend "${$.name}" does not support append-system-prompt; cannot inject soul.md.`);let Z;try{Z=X==="run"?await $.spawn(q):await $.chat(q)}catch(z){if(z.code==="ENOENT")throw new c(`Backend "${$.name}" binary not found on PATH. Install it before running.`,{cause:z});throw z}let Y=(z)=>{if(!Z.killed)Z.kill(z)};process.on("SIGINT",Y),process.on("SIGTERM",Y);try{return await new Promise((z,J)=>{Z.on("error",(Q)=>{if(Q.code==="ENOENT")J(new c(`Backend "${$.name}" binary not found on PATH. Install it before running.`,{cause:Q}));else J(Q)}),Z.on("exit",(Q,W)=>{if(W==="SIGINT"||W==="SIGTERM")z({exitCode:C.Interrupted});else z({exitCode:Q??0})})})}finally{process.off("SIGINT",Y),process.off("SIGTERM",Y)}}function T$(){return new Promise(($)=>{process.stdin.setEncoding("utf8");let q=(X)=>{process.stdin.off("data",q),process.stdin.pause(),$(X)};process.stdin.on("data",q)})}function f1(){let $=new x("agent").description("Agent lifecycle: create, list, show, delete, rename.");return $.command("create <name>").description("Create a new agent (~/.kman/agents/<name>/).").option("--runtime <backend>","Default backend (claude-code | copilot-cli).").option("--model <id>","Default model id.").option("--description <text>","Free-form description.").option("--soul <text>","Initial soul prompt content.").action(async(q,X)=>{e(q);let Z=k(q);if(await C$(Z))throw new B(`Agent "${q}" already exists at ${Z}.`);await A$(Z,{recursive:!0}),await A$(b$(Z,"skills"),{recursive:!0}),await A$(b$(Z,"hooks"),{recursive:!0}),await A$(b$(Z,"scripts"),{recursive:!0});let Y={};if(X.description)Y.description=X.description;if(X.runtime)Y.runtime={default:X.runtime};if(X.model)Y.runtime={...Y.runtime??{default:"claude-code"},model:X.model};let z=F$(q,Y);await k0(z);let J=X.soul??`# ${q}
|
|
39
|
+
`;else J+=" "+X.join(", ")+(X.length>0?" ":"");return J+"]"}function g6($){$=o$($);var q=[];return Object.keys($).forEach((J)=>{q.push(r$(J)+" = "+u2($[J],!1))}),"{ "+q.join(", ")+(q.length>0?" ":"")+"}"}function c6($,q,J,X){var Z=A(X);if(Z==="array")return m6($,q,J,X);else if(Z==="table")return d6($,q,J,X);else throw z$(Z)}function m6($,q,J,X){X=o$(X),g2(X);var Z=A(X[0]);if(Z!=="table")throw z$(Z);var z=$+r$(J),Q="";return X.forEach((G)=>{if(Q.length>0)Q+=`
|
|
40
|
+
`;Q+=q+"[["+z+`]]
|
|
41
|
+
`,Q+=n0(z+".",q,G)}),Q}function d6($,q,J,X){var Z=$+r$(J),z="";if(E2(X).length>0)z+=q+"["+Z+`]
|
|
42
|
+
`;return z+n0(Z+".",q,X)}});var p0=N((l6)=>{l6.parse=A2();l6.stringify=c2()});var vq=P0(uq(),1),{program:X4,createCommand:Z4,createArgument:z4,createOption:Q4,CommanderError:gq,InvalidArgumentError:G4,InvalidOptionArgumentError:Y4,Command:O,Argument:W4,Option:B4,Help:U4}=vq.default;var H0=/^[a-z][a-z0-9-]{0,62}$/;var b={Success:0,AgentError:1,UserError:2,HookBlocked:3,BackendUnavailable:4,Interrupted:130};class D$ extends Error{code;constructor($,q,J){super(q,J);this.name="KmanError",this.code=$}}class M extends D${constructor($,q){super(b.UserError,$,q);this.name="UserError"}}class r extends D${constructor($,q){super(b.BackendUnavailable,$,q);this.name="BackendUnavailableError"}}var W$={name:"@unliftedq/kman",version:"0.0.3",description:"Multi-agent management tool — a CLI that manages a roster of named agent profiles on top of existing agent runtimes (claude-code, copilot-cli, ...).",keywords:["agent","agents","multi-agent","claude","claude-code","copilot","copilot-cli","ai","cli","kman"],homepage:"https://github.com/unliftedq/kman#readme",repository:{type:"git",url:"git+https://github.com/unliftedq/kman.git"},bugs:{url:"https://github.com/unliftedq/kman/issues"},license:"Apache-2.0",author:"Qiao Wang <wangqiao11@hotmail.com>",type:"module",bin:{kman:"dist/main.js"},main:"./dist/main.js",files:["dist/main.js","README.md","LICENSE"],engines:{node:">=18"},publishConfig:{access:"public"},scripts:{start:"bun run ./src/main.ts",build:"bun run ./scripts/build.ts",typecheck:"tsc -b",test:"bun test",clean:"rm -rf dist .tsbuild .turbo *.tsbuildinfo",prepublishOnly:"bun run build"},devDependencies:{"@kman/backend-claude-code":"workspace:*","@kman/backend-copilot-cli":"workspace:*","@kman/core":"workspace:*","@kman/mcp-server":"workspace:*","@kman/skills":"workspace:*","@kman/types":"workspace:*",commander:"^14.0.3",typescript:"^5.6.0"}};import{mkdir as K$,readFile as $q,readdir as P8,rename as e2,rm as D8,stat as S8,symlink as I8,writeFile as t}from"node:fs/promises";import{join as T}from"node:path";import{homedir as p3}from"node:os";import{join as B$}from"node:path";function S$(){let $=process.env.KMAN_HOME;return $&&$.length>0?$:B$(p3(),".kman")}function I$(){return B$(S$(),"agents")}function I($){return B$(I$(),$)}function u$($){return B$(I($),"agent.toml")}function U$($,q="soul.md"){return B$(I($),q)}function C($){return B$(I($),"skills")}var O0=["ask","auto","yolo"],_0=["text","json","stream-json"],cq={permission_mode:"ask",output_format:"text"};function v$($,q={}){return{name:$,description:q.description,runtime:{default:q.runtime?.default??"claude-code",...q.runtime?.model!==void 0?{model:q.runtime.model}:{}},soul:{prompt_file:q.soul?.prompt_file??"soul.md"},defaults:{max_turns:q.defaults?.max_turns,permission_mode:q.defaults?.permission_mode??cq.permission_mode,output_format:q.defaults?.output_format??cq.output_format},runtimeOverrides:q.runtimeOverrides??{}}}var m2=P0(p0(),1);import{readFile as t6}from"node:fs/promises";function M$($){if(!H0.test($))throw new M(`Invalid agent name "${$}". Must match ${H0.source} (lowercase kebab-case, 1–63 chars).`)}function e$($){if(M$($.name),!$.runtime||typeof $.runtime.default!=="string")throw new M(`Profile "${$.name}" is missing runtime.default.`);let q=$.defaults.permission_mode;if(q!==void 0&&!O0.includes(q))throw new M(`Profile "${$.name}" has invalid permission_mode "${q}". Expected one of: ${O0.join(", ")}.`);let J=$.defaults.output_format;if(J!==void 0&&!_0.includes(J))throw new M(`Profile "${$.name}" has invalid output_format "${J}". Expected one of: ${_0.join(", ")}.`);if($.defaults.max_turns!==void 0&&(!Number.isInteger($.defaults.max_turns)||$.defaults.max_turns<=0))throw new M(`Profile "${$.name}" has invalid max_turns ${$.defaults.max_turns}. Expected positive integer.`)}function p6($,q){if(typeof q!=="object"||q===null)throw new M(`Profile "${$}" is not a valid TOML object.`);let J=q,X=typeof J.description==="string"?J.description:void 0,Z=J.runtime??{},z=typeof Z.default==="string"?Z.default:"claude-code",Q=typeof Z.model==="string"?Z.model:void 0,G={};for(let[S,H]of Object.entries(Z)){if(S==="default"||S==="model")continue;if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let d=H,G$={};if(typeof d.permission_mode_raw==="string")G$.permission_mode_raw=d.permission_mode_raw;if(Array.isArray(d.extra_args))G$.extra_args=d.extra_args.filter((b$)=>typeof b$==="string");if(typeof d.model==="string")G$.model=d.model;G[S]=G$}}let B=J.soul??{},Y=typeof B.prompt_file==="string"?B.prompt_file:"soul.md",W=J.defaults??{},V={max_turns:typeof W.max_turns==="number"?W.max_turns:void 0,permission_mode:typeof W.permission_mode==="string"?W.permission_mode:void 0,output_format:typeof W.output_format==="string"?W.output_format:void 0},F=v$($,{description:X,runtime:{default:z,...Q!==void 0?{model:Q}:{}},soul:{prompt_file:Y},defaults:V,runtimeOverrides:G});return e$(F),F}async function h($){let q=u$($),J;try{J=await t6(q,"utf8")}catch(Z){if(Z.code==="ENOENT")throw new M(`Agent "${$}" not found at ${q}.`);throw new M(`Failed to read profile for "${$}": ${Z.message}`,{cause:Z})}let X;try{X=m2.default.parse(J)}catch(Z){throw new M(`Failed to parse ${q}: ${Z.message}`,{cause:Z})}return p6($,{...X,name:$})}var d2=P0(p0(),1);import{writeFile as s6,mkdir as a6}from"node:fs/promises";import{dirname as o6}from"node:path";function r6($){e$($);let q={name:$.name};if($.description!==void 0)q.description=$.description;let J={default:$.runtime.default};if($.runtime.model!==void 0)J.model=$.runtime.model;for(let[Z,z]of Object.entries($.runtimeOverrides)){let Q={};if(z.permission_mode_raw!==void 0)Q.permission_mode_raw=z.permission_mode_raw;if(z.extra_args!==void 0)Q.extra_args=[...z.extra_args];if(z.model!==void 0)Q.model=z.model;if(Object.keys(Q).length>0)J[Z]=Q}q.runtime=J,q.soul={prompt_file:$.soul.prompt_file};let X={};if($.defaults.max_turns!==void 0)X.max_turns=$.defaults.max_turns;if($.defaults.permission_mode!==void 0)X.permission_mode=$.defaults.permission_mode;if($.defaults.output_format!==void 0)X.output_format=$.defaults.output_format;return q.defaults=X,d2.default.stringify(q)}async function s0($){let q=u$($.name);await a6(o6(q),{recursive:!0});let J=r6($);return await s6(q,J,"utf8"),q}import{readFile as e6}from"node:fs/promises";import{isAbsolute as $8,join as q8}from"node:path";async function $0($,q={}){let J=I($.name),X=$8($.soul.prompt_file)?$.soul.prompt_file:q8(J,$.soul.prompt_file),Z="";try{Z=await e6(X,"utf8")}catch(H){if(H.code==="ENOENT")Z="";else throw new M(`Failed to read soul prompt at ${X}: ${H.message}`,{cause:H})}let z=q.backend??$.runtime.default,Q=$.runtimeOverrides[z]??{},G=q.model??Q.model??$.runtime.model,B=q.permission??$.defaults.permission_mode??"ask",Y=q.outputFormat??(q.stream?"stream-json":$.defaults.output_format??"text"),W=q.stream===!0||Y==="stream-json",V=[...Q.extra_args??[],...q.runtimeFlags??[]],F={...q.env};return{profile:$,agentDir:J,soulPrompt:Z,backend:z,...G!==void 0?{model:G}:{},permission:B,outputFormat:Y,...$.defaults.max_turns!==void 0?{maxTurns:$.defaults.max_turns}:{},cwd:q.cwd??process.cwd(),extraArgs:V,...Q.permission_mode_raw!==void 0?{permissionModeRaw:Q.permission_mode_raw}:{},env:F,...q.task!==void 0?{task:q.task}:{},stream:W}}async function l2($,q){return i2($,q,"run")}async function n2($,q){return i2($,q,"chat")}async function i2($,q,J){if(q.soulPrompt.trim().length>0&&!$.capabilities.supportsAppendSystemPrompt)throw new r(`Backend "${$.name}" does not support append-system-prompt; cannot inject soul.md.`);let X;try{X=J==="run"?await $.spawn(q):await $.chat(q)}catch(z){if(z.code==="ENOENT")throw new r(`Backend "${$.name}" binary not found on PATH. Install it before running.`,{cause:z});throw z}let Z=(z)=>{if(!X.killed)X.kill(z)};process.on("SIGINT",Z),process.on("SIGTERM",Z);try{return await new Promise((z,Q)=>{X.on("error",(G)=>{if(G.code==="ENOENT")Q(new r(`Backend "${$.name}" binary not found on PATH. Install it before running.`,{cause:G}));else Q(G)}),X.on("exit",(G,B)=>{if(B==="SIGINT"||B==="SIGTERM")z({exitCode:b.Interrupted});else z({exitCode:G??0})})})}finally{process.off("SIGINT",Z),process.off("SIGTERM",Z)}}var t2={ok:0,info:1,warn:2,error:3};function a0($){let q="ok";for(let J of $.sections)for(let X of J.checks)if(t2[X.severity]>t2[q])q=X.severity;return q}import{spawn as J8}from"node:child_process";var q0=[{name:"claude-code",defaultBin:"claude",envOverride:"KMAN_CLAUDE_BIN"},{name:"copilot-cli",defaultBin:"copilot",envOverride:"KMAN_COPILOT_BIN"}];function X8($){if($.envOverride){let q=process.env[$.envOverride];if(q&&q.length>0)return q}return $.defaultBin}async function Z8($,q=15000){return new Promise((J)=>{let X="",Z="",z=!1,Q=(Y)=>{if(z)return;z=!0,J(Y)},G;try{G=J8($,["--version"],{stdio:["ignore","pipe","pipe"],shell:!1})}catch(Y){let W=Y;Q({ok:!1,errorCode:W.code,errorMessage:W.message});return}let B=setTimeout(()=>{if(G.exitCode===null&&G.signalCode===null)G.kill("SIGTERM");setTimeout(()=>{if(G.exitCode===null&&G.signalCode===null)G.kill("SIGKILL")},250).unref(),Q({ok:!1,errorCode:"ETIMEDOUT",errorMessage:`${$} --version timed out`})},q).unref();G.stdout?.on("data",(Y)=>{X+=Y.toString("utf8")}),G.stderr?.on("data",(Y)=>{Z+=Y.toString("utf8")}),G.on("error",(Y)=>{clearTimeout(B);let W=Y;Q({ok:!1,errorCode:W.code,errorMessage:W.message})}),G.on("exit",(Y)=>{clearTimeout(B);let V=(X||Z).trim().split(/\r?\n/).find((F)=>F.trim().length>0)??"";if(Y===0&&V.length>0)Q({ok:!0,version:V});else if(Y===0)Q({ok:!0,version:"(no output)"});else Q({ok:!1,errorCode:`EXIT_${Y??"NULL"}`,errorMessage:V||`${$} --version exited ${Y}`})})})}async function J0($){let q=X8($),J=await Z8(q),X=$.envOverride&&process.env[$.envOverride]?` (via ${$.envOverride})`:"";if(!J.ok){let Z=J.errorCode==="ENOENT";return[{id:`backend.${$.name}.binary`,label:`${$.name} binary`,severity:"error",message:Z?`"${q}" not found${X}.`:`"${q}" failed${X}: ${J.errorMessage??J.errorCode??"unknown error"}`,detail:Z?$.envOverride?`Install the ${$.name} CLI, or set ${$.envOverride} to the desired path.`:`Install the ${$.name} CLI, or ensure "${q}" is on PATH.`:void 0}]}return[{id:`backend.${$.name}.binary`,label:`${$.name} binary`,severity:"ok",message:`"${q}" on PATH${X}.`},{id:`backend.${$.name}.version`,label:`${$.name} version`,severity:"ok",message:J.version??"(unknown)"}]}import{readdir as p2,readFile as s2,stat as o0}from"node:fs/promises";import{isAbsolute as z8,join as r0,resolve as Q8}from"node:path";var G8=["git","node","npm","npx","bun","sh","bash","zsh","env","rm","mv","cp","ls","cat","echo","kman","claude","copilot","python","python3","pip","pip3"],Y8=process.platform==="win32";async function e0($){try{return await o0($),!0}catch(q){if(q.code==="ENOENT")return!1;throw q}}async function W8($){try{let q=await h($);return{profile:q,checks:[{id:"profile.readable",label:"agent.toml",severity:"ok",message:`parsed (runtime=${q.runtime.default}${q.runtime.model?`, model=${q.runtime.model}`:""}).`}]}}catch(q){return{profile:null,checks:[{id:"profile.readable",label:"agent.toml",severity:"error",message:q.message}]}}}async function B8($){let q=$.soul.prompt_file,J=z8(q)?q:U$($.name,q);try{let X=await o0(J);if(!X.isFile())return{id:"soul.file",label:"soul prompt",severity:"error",message:`${J} exists but is not a file.`};if(X.size===0)return{id:"soul.file",label:"soul prompt",severity:"warn",message:`${J} is empty.`};return{id:"soul.file",label:"soul prompt",severity:"ok",message:`${J} (${X.size} bytes).`}}catch(X){let Z=X;if(Z.code==="ENOENT")return{id:"soul.file",label:"soul prompt",severity:"warn",message:`${J} missing; backend will run with no soul prompt.`};return{id:"soul.file",label:"soul prompt",severity:"error",message:Z.message}}}async function U8($){let q=r0(I($),".mcp.json"),J;try{J=await e0(q)}catch(Y){return[{id:"mcp.present",label:".mcp.json",severity:"error",message:Y.message}]}if(!J)return[{id:"mcp.present",label:".mcp.json",severity:"info",message:"not present; MCP servers disabled for this agent."}];let X;try{X=await s2(q,"utf8")}catch(Y){return[{id:"mcp.readable",label:".mcp.json",severity:"error",message:Y.message}]}let Z;try{Z=JSON.parse(X)}catch(Y){return[{id:"mcp.json",label:".mcp.json",severity:"error",message:`invalid JSON: ${Y.message}`,detail:`Edit ${q} and ensure it is valid JSON.`}]}if(typeof Z!=="object"||Z===null)return[{id:"mcp.shape",label:".mcp.json",severity:"error",message:"top-level value must be an object."}];let z=Z.mcpServers,Q=[];if(typeof z!=="object"||z===null||Array.isArray(z))return Q.push({id:"mcp.shape",label:".mcp.json",severity:"error",message:'missing "mcpServers" object.'}),Q;let G=Object.entries(z);if(G.length===0)return Q.push({id:"mcp.servers",label:".mcp.json",severity:"info",message:"no MCP servers configured."}),Q;let B=0;for(let[Y,W]of G){if(typeof W!=="object"||W===null){Q.push({id:`mcp.server.${Y}.shape`,label:`mcpServers.${Y}`,severity:"error",message:"entry must be an object."}),B++;continue}let V=W.command;if(typeof V!=="string"||V.length===0)Q.push({id:`mcp.server.${Y}.command`,label:`mcpServers.${Y}`,severity:"error",message:'"command" must be a non-empty string.'}),B++}return Q.unshift({id:"mcp.servers",label:".mcp.json",severity:B>0?"error":"ok",message:`${G.length} server(s) declared${B>0?`, ${B} invalid`:""}.`}),Q}function*V8($){if(typeof $!=="object"||$===null)return;let q=$.hooks;if(typeof q!=="object"||q===null)return;for(let J of Object.values(q)){if(!Array.isArray(J))continue;for(let X of J){if(typeof X!=="object"||X===null)continue;let Z=typeof X.matcher==="string"?X.matcher:void 0,z=X.hooks;if(!Array.isArray(z))continue;for(let Q of z){if(typeof Q!=="object"||Q===null)continue;let G=Q.command;if(typeof G==="string"&&G.length>0)yield Z===void 0?{command:G}:{matcher:Z,command:G}}}}}function M8($){let J=$.trim().match(/(?:\$\{CLAUDE_PLUGIN_ROOT\}|\$CLAUDE_PLUGIN_ROOT)(["'`]?)([^\s"';|&<>]*)/);if(!J)return null;let X=J[2]??"";return X=X.replace(/^[\\/]+/,""),X.length>0?X:null}async function K8($){let q=r0(I($),"hooks","hooks.json"),J;try{J=await e0(q)}catch(B){return[{id:"hooks.present",label:"hooks/hooks.json",severity:"error",message:B.message}]}if(!J)return[{id:"hooks.present",label:"hooks/hooks.json",severity:"info",message:"not present."}];let X;try{X=await s2(q,"utf8")}catch(B){return[{id:"hooks.readable",label:"hooks/hooks.json",severity:"error",message:B.message}]}let Z;try{Z=JSON.parse(X)}catch(B){return[{id:"hooks.json",label:"hooks/hooks.json",severity:"error",message:`invalid JSON: ${B.message}`}]}let z=[],Q=I($),G=Array.from(V8(Z));if(G.length===0)return z.push({id:"hooks.entries",label:"hooks/hooks.json",severity:"info",message:"no command hooks declared."}),z;z.push({id:"hooks.entries",label:"hooks/hooks.json",severity:"ok",message:`${G.length} command hook(s) declared.`});for(let[B,Y]of G.entries()){let W=M8(Y.command),V=`hook[${B}]${Y.matcher?` matcher=${Y.matcher}`:""}`;if(!W){z.push({id:`hooks.${B}.script`,label:V,severity:"info",message:"inline command (no ${CLAUDE_PLUGIN_ROOT} reference); skipped."});continue}let F=Q8(Q,W);try{let S=await o0(F);if(!S.isFile()){z.push({id:`hooks.${B}.script`,label:V,severity:"error",message:`${F} exists but is not a file.`});continue}if(Y8){z.push({id:`hooks.${B}.script`,label:V,severity:"ok",message:`${W} present (executable bit not checked on Windows).`});continue}if((S.mode&73)===0)z.push({id:`hooks.${B}.script`,label:V,severity:"error",message:`${W} is not executable.`,detail:`Run: chmod +x ${F}`});else z.push({id:`hooks.${B}.script`,label:V,severity:"ok",message:`${W} executable.`})}catch(S){let H=S;z.push({id:`hooks.${B}.script`,label:V,severity:"error",message:H.code==="ENOENT"?`${W} missing.`:H.message})}}return z}async function F8($){let q=r0(I($),"bin"),J;try{J=await p2(q,{withFileTypes:!0})}catch(G){let B=G;if(B.code==="ENOENT")return[{id:"bin.present",label:"bin/",severity:"info",message:"not present."}];return[{id:"bin.readable",label:"bin/",severity:"error",message:B.message}]}let X=J.filter((G)=>G.isFile()||G.isSymbolicLink()).map((G)=>G.name);if(X.length===0)return[{id:"bin.entries",label:"bin/",severity:"info",message:"empty."}];let Z=(G)=>G.replace(/\.(sh|bat|cmd|exe|ps1)$/i,""),z=X.filter((G)=>G8.includes(Z(G))),Q=[{id:"bin.entries",label:"bin/",severity:"ok",message:`${X.length} entr${X.length===1?"y":"ies"}.`}];if(z.length>0)Q.push({id:"bin.shadowing",label:"bin/ shadowing",severity:"warn",message:`may shadow system commands: ${z.join(", ")}.`,detail:"Rename bin/ entries to use an agent-specific prefix (see DESIGN §4.5)."});return Q}async function N8($){let q=C($),J;try{J=await p2(q,{withFileTypes:!0})}catch(Z){let z=Z;if(z.code==="ENOENT")return[{id:"skills.present",label:"skills/",severity:"info",message:"not present."}];return[{id:"skills.readable",label:"skills/",severity:"error",message:z.message}]}let X=J.filter((Z)=>Z.isDirectory()).map((Z)=>Z.name);return[{id:"skills.count",label:"skills/",severity:"ok",message:X.length===0?"no skills installed.":`${X.length} installed: ${X.join(", ")}.`}]}async function a2($){let q=I($),J;try{J=await e0(q)}catch(Q){return[{id:"agent.exists",label:"agent directory",severity:"error",message:Q.message}]}if(!J)return[{id:"agent.exists",label:"agent directory",severity:"error",message:`${q} does not exist.`,detail:`Run: kman agent create ${$}`}];let X=[],{checks:Z,profile:z}=await W8($);if(X.push(...Z),z)X.push(await B8(z));if(X.push(...await U8($)),X.push(...await K8($)),X.push(...await F8($)),X.push(...await N8($)),z){let Q=q0.find((G)=>G.name===z.runtime.default);if(!Q)X.push({id:"agent.backend.known",label:`runtime=${z.runtime.default}`,severity:"warn",message:`no built-in probe for backend "${z.runtime.default}".`});else{let G=await J0(Q);for(let B of G)X.push({...B,id:`agent.${B.id}`})}}return X}async function o2($={}){let q=[];q.push({title:"Environment",checks:[{id:"env.kman_home",label:"KMAN_HOME",severity:"ok",message:S$()},{id:"env.platform",label:"platform",severity:"ok",message:`${process.platform} ${process.arch} (node ${process.version})`}]});let J=$.backends??q0,X=await Promise.all(J.map((Z)=>J0(Z)));if(q.push({title:"Backends",checks:X.flat()}),$.agent){let Z=await a2($.agent);q.push({title:`Agent: ${$.agent}`,checks:Z})}return{sections:q,generatedAt:new Date().toISOString()}}function r2(){return new Promise(($)=>{process.stdin.setEncoding("utf8");let q=(J)=>{process.stdin.off("data",q),process.stdin.pause(),$(J)};process.stdin.on("data",q)})}function $1(){let $=new O("agent").description("Agent lifecycle: create, list, show, delete, rename.");return $.command("create <name>").description("Create a new agent at ~/.kman/agents/<name>/.").option("--runtime <runtime>","Default agent runtime (claude-code | copilot-cli).").option("--model <id>","Default model id.").option("--description <text>",'What the agent is for or specializes in — a short label, e.g. "C# code review".').option("--soul <text>","Initial soul prompt body — how the agent thinks and behaves. Written to soul.md.").action(async(q,J)=>{M$(q);let X=I(q);if(await a(X))throw new M(`Agent "${q}" already exists at ${X}.`);await K$(X,{recursive:!0}),await K$(T(X,"agents"),{recursive:!0}),await K$(T(X,"skills"),{recursive:!0}),await K$(T(X,"hooks"),{recursive:!0}),await K$(T(X,"scripts"),{recursive:!0}),await K$(T(X,".claude-plugin"),{recursive:!0});let Z={};if(J.description)Z.description=J.description;if(J.runtime)Z.runtime={default:J.runtime};if(J.model)Z.runtime={...Z.runtime??{default:"claude-code"},model:J.model};let z=v$(q,Z);await s0(z);let Q=J.soul??`# ${q}
|
|
43
43
|
|
|
44
44
|
You are ${q}. Replace this file with your agent's system prompt.
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
`),process.stdout.write(`
|
|
55
|
-
`)
|
|
56
|
-
`);let Z
|
|
57
|
-
`)}),$.command("
|
|
58
|
-
`)
|
|
59
|
-
`)
|
|
60
|
-
`)
|
|
61
|
-
|
|
62
|
-
`)
|
|
63
|
-
`);
|
|
64
|
-
`)}
|
|
65
|
-
`),process.stdout.write(`
|
|
66
|
-
`),
|
|
67
|
-
`),
|
|
68
|
-
|
|
69
|
-
|
|
45
|
+
`,G=J.description?`description: ${J.description}
|
|
46
|
+
`:"",B=`---
|
|
47
|
+
name: ${q}
|
|
48
|
+
${G}---
|
|
49
|
+
|
|
50
|
+
${Q}`;await t(U$(q,z.soul.prompt_file),B,"utf8"),await x8(X,q,B);let Y={name:q,agents:"agents/"},W={name:q,agents:[`./agents/${q}.md`]};if(J.description)Y.description=J.description,W.description=J.description;await t(T(X,"plugin.json"),JSON.stringify(Y,null,2)+`
|
|
51
|
+
`,"utf8"),await t(T(X,".claude-plugin","plugin.json"),JSON.stringify(W,null,2)+`
|
|
52
|
+
`,"utf8"),await t(T(X,".mcp.json"),JSON.stringify({mcpServers:{}},null,2)+`
|
|
53
|
+
`,"utf8"),process.stdout.write(`Created agent "${q}" at ${X}
|
|
54
|
+
`)}),$.command("list").description("List all agents.").action(async()=>{let q=I$(),J;try{J=await P8(q,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT"){process.stdout.write(`(no agents)
|
|
55
|
+
`);return}throw Z}let X=J.filter((Z)=>Z.isDirectory()).map((Z)=>Z.name).sort();if(X.length===0){process.stdout.write(`(no agents)
|
|
56
|
+
`);return}for(let Z of X)process.stdout.write(`${Z}
|
|
57
|
+
`)}),$.command("show <name>").description("Show an agent's profile and on-disk paths.").action(async(q)=>{let J=await h(q);if(process.stdout.write(`name: ${J.name}
|
|
58
|
+
`),J.description)process.stdout.write(`description: ${J.description}
|
|
59
|
+
`);if(process.stdout.write(`directory: ${I(J.name)}
|
|
60
|
+
`),process.stdout.write(`runtime: ${J.runtime.default}`),J.runtime.model)process.stdout.write(` (model=${J.runtime.model})`);if(process.stdout.write(`
|
|
61
|
+
`),process.stdout.write(`soul: ${J.soul.prompt_file}
|
|
62
|
+
`),process.stdout.write(`defaults: permission=${J.defaults.permission_mode??"ask"} `),process.stdout.write(`output=${J.defaults.output_format??"text"}`),J.defaults.max_turns!==void 0)process.stdout.write(` max_turns=${J.defaults.max_turns}`);process.stdout.write(`
|
|
63
|
+
`);let X=Object.keys(J.runtimeOverrides);if(X.length>0)process.stdout.write(`overrides: ${X.join(", ")}
|
|
64
|
+
`)}),$.command("delete <name>").description("Delete an agent's directory and all its contents.").option("--yes","Skip the confirmation prompt.").action(async(q,J)=>{M$(q);let X=I(q);if(!await a(X))throw new M(`Agent "${q}" not found.`);if(!J.yes){if(!process.stdin.isTTY)throw new M(`Pass --yes to delete "${q}" non-interactively.`);process.stdout.write(`Delete agent "${q}" at ${X}? [y/N] `);let Z=await r2();if(!/^y(es)?$/i.test(Z.trim())){process.stdout.write(`Aborted.
|
|
65
|
+
`);return}}await D8(X,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${X}
|
|
66
|
+
`)}),$.command("rename <from> <to>").description("Rename an agent.").action(async(q,J)=>{M$(q),M$(J);let X=I(q),Z=I(J);if(!await a(X))throw new M(`Agent "${q}" not found.`);if(await a(Z))throw new M(`Agent "${J}" already exists.`);await e2(X,Z);let z=await h(J);await s0({...z,name:J});let Q=T(Z,"agents",`${q}.md`),G=T(Z,"agents",`${J}.md`);if(await a(Q))await e2(Q,G);await f8(T(Z,"plugin.json"),J),await L8(T(Z,".claude-plugin","plugin.json"),J),await w8(T(Z,z.soul.prompt_file),J),process.stdout.write(`Renamed ${q} → ${J}
|
|
67
|
+
`)}),$}async function a($){try{return await S8($),!0}catch{return!1}}async function f8($,q){if(!await a($))return;let J=await $q($,"utf8"),X=JSON.parse(J);X.name=q,await t($,JSON.stringify(X,null,2)+`
|
|
68
|
+
`,"utf8")}async function L8($,q){if(!await a($))return;let J=await $q($,"utf8"),X=JSON.parse(J);X.name=q,X.agents=[`./agents/${q}.md`],await t($,JSON.stringify(X,null,2)+`
|
|
69
|
+
`,"utf8")}async function w8($,q){if(!await a($))return;let J=await $q($,"utf8");if(!J.startsWith("---")){let B=`---
|
|
70
|
+
name: ${q}
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
`;await t($,B+J,"utf8");return}let X=J.indexOf(`
|
|
74
|
+
---`,3);if(X<0)return;let Z=J.slice(0,X),z=J.slice(X),Q=Z.replace(/^name:.*$/m,`name: ${q}`),G=/^name:/m.test(Q)?Q:Q.replace(/^---\n/,`---
|
|
75
|
+
name: ${q}
|
|
76
|
+
`);await t($,G+z,"utf8")}async function x8($,q,J){let X=T($,"agents",`${q}.md`);try{await I8(T("..","soul.md"),X,"file")}catch(Z){let z=Z;if(process.platform==="win32"&&(z.code==="EPERM"||z.code==="UNKNOWN")){await t(X,J,"utf8"),process.stderr.write(`kman: could not create a symlink on Windows (needs Developer Mode or admin); wrote a static copy at agents/${q}.md instead. Edits to soul.md will not `+`propagate — keep them in sync manually, or enable Developer Mode and recreate.
|
|
77
|
+
`);return}throw Z}}import{isAbsolute as j8,resolve as H8}from"node:path";var O8=/^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)(?:\/([^@\s]+))?(?:@(.+))?$/,_8=new Set(["anthropic-skills"]);function X0($,q){let J=$.trim();if(J.length===0)throw new M("Source cannot be empty.");if(J.startsWith(".")||J.startsWith("/")||J.startsWith("~")||J.startsWith("file://")||/^[A-Za-z]:[\\/]/.test(J)||j8(J)){let Q=J.startsWith("file://")?J.slice(7):J;if(Q.startsWith("~"))Q=Q.replace(/^~/,process.env.HOME??process.env.USERPROFILE??"~");return{kind:"local",path:H8(Q),...q?{ref:q}:{}}}let X=J.match(/^https?:\/\/github\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?(?:\/tree\/([^/]+))?(?:\/(.+))?$/);if(X){let[,Q="",G="",B,Y]=X,W={kind:"github",owner:Q,repo:G};if(Y)W.subpath=qq(Y);let V=q??B;if(V)W.ref=V;return W}let Z=J.match(/^https?:\/\/gitlab\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?(?:\/-\/tree\/([^/]+))?(?:\/(.+))?$/);if(Z){let[,Q="",G="",B,Y]=Z,W={kind:"gitlab",owner:Q,repo:G};if(Y)W.subpath=qq(Y);let V=q??B;if(V)W.ref=V;return W}if(J.startsWith("git+")||J.startsWith("ssh://")||/^git@[^:]+:/.test(J)||J.endsWith(".git")){let Q={kind:"git",url:J.startsWith("git+")?J.slice(4):J};if(q)Q.ref=q;return Q}let z=J.match(O8);if(z){let[,Q="",G="",B,Y]=z,W={kind:"github",owner:Q,repo:G};if(B)W.subpath=qq(B);let V=q??Y;if(V)W.ref=V;return W}if(!J.includes("/")&&_8.has(J)){let Q={kind:"well-known",name:J};if(q)Q.ref=q;return Q}throw new M(`Unrecognized source "${$}". Use a local path, GitHub/GitLab URL, owner/repo[/path][@ref], git URL, or well-known name.`)}function qq($){let q=$.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");if(q.length===0)throw new M("Empty source subpath after sanitization.");let J=q.split("/");for(let X of J)if(X===".."||X==="."||X.length===0)throw new M(`Invalid source subpath segment "${X}" in "${$}".`);return J.join("/")}import{readdir as J1,stat as y8}from"node:fs/promises";import{basename as Jq,join as T$,relative as Xq}from"node:path";var T8=["","skills",".claude/skills"],k8=4,X1=new Set(["node_modules",".git",".turbo","dist","build",".cache"]);async function Z0($,q){let J=q?T$($,q):$;if(!(await Zq(J))?.isDirectory())throw new M(`Source path does not exist or is not a directory: ${J}`);let Z=[];if(await zq(J))return Z.push({name:Jq(J),dir:J,relPath:Xq($,J)||"."}),Z;for(let z of T8){let Q=z?T$(J,z):J;if(!(await Zq(Q))?.isDirectory())continue;let B=await R8(Q);for(let Y of B)Z.push({name:Jq(Y),dir:Y,relPath:Xq($,Y)});if(Z.length>0)return q1(Z)}if(await Z1(J,0,$,Z),Z.length===0)throw new M(`No SKILL.md found anywhere under ${J}.`);return q1(Z)}async function R8($){let q;try{q=await J1($,{withFileTypes:!0})}catch{return[]}let J=[];for(let X of q){if(!X.isDirectory()||X1.has(X.name))continue;let Z=T$($,X.name);if(await zq(Z))J.push(Z)}return J}async function Z1($,q,J,X){if(q>k8)return;let Z;try{Z=await J1($,{withFileTypes:!0})}catch{return}if(await zq($)){X.push({name:Jq($),dir:$,relPath:Xq(J,$)||"."});return}for(let z of Z){if(!z.isDirectory()||X1.has(z.name))continue;await Z1(T$($,z.name),q+1,J,X)}}async function zq($){return!!(await Zq(T$($,"SKILL.md")))?.isFile()}async function Zq($){try{return await y8($)}catch{return null}}function q1($){let q=new Set,J=[];for(let X of $){if(q.has(X.dir))continue;q.add(X.dir),J.push(X)}return J}import{cp as W1,mkdir as u8,stat as v8}from"node:fs/promises";import{join as g8}from"node:path";import{readFile as A8,writeFile as E8,stat as b8}from"node:fs/promises";import{join as h8}from"node:path";var C8=".kman-skill.json";function Qq($){return h8($,C8)}async function z0($){try{let q=await A8(Qq($),"utf8");return JSON.parse(q)}catch(q){if(q.code==="ENOENT")return null;throw q}}async function z1($,q){await E8(Qq($),JSON.stringify(q,null,2)+`
|
|
78
|
+
`,"utf8")}async function Q1($){try{return(await b8(Qq($))).mtime}catch{return null}}function G1($){switch($.kind){case"local":return $.path;case"github":return $.subpath?`${$.owner}/${$.repo}/${$.subpath}`:`${$.owner}/${$.repo}`;case"gitlab":return $.subpath?`gitlab:${$.owner}/${$.repo}/${$.subpath}`:`gitlab:${$.owner}/${$.repo}`;case"git":return $.url;case"well-known":return $.name}}function Y1($){switch($.kind){case"github":return`https://github.com/${$.owner}/${$.repo}`;case"gitlab":return`https://gitlab.com/${$.owner}/${$.repo}`;case"git":return $.url;default:return}}async function Q0($){let q=$.installName??$.skill.name,J=g8(C($.agent),q),X=await c8(J);if(X&&!$.force)throw new M(`Skill "${q}" already exists at ${J}. Use --force to overwrite.`);if(await u8(C($.agent),{recursive:!0}),X)await W1($.skill.dir,J,{recursive:!0,force:!0});else await W1($.skill.dir,J,{recursive:!0});let Z={source:G1($.source),installed_at:new Date().toISOString()},z=Y1($.source);if(z)Z.source_url=z;if("ref"in $.source&&$.source.ref)Z.ref=$.source.ref;return await z1(J,Z),{installedPath:J,manifest:Z}}async function c8($){try{return await v8($),!0}catch{return!1}}import{readdir as t8,stat as p8}from"node:fs/promises";import{join as B1}from"node:path";import{spawn as m8}from"node:child_process";import{mkdtemp as d8,rm as l8}from"node:fs/promises";import{tmpdir as n8}from"node:os";import{join as i8}from"node:path";async function Y0($){switch($.kind){case"local":return{rootDir:$.path,subpath:$.subpath,cleanup:async()=>{}};case"github":return G0(`https://github.com/${$.owner}/${$.repo}.git`,$.ref,$.subpath);case"gitlab":return G0(`https://gitlab.com/${$.owner}/${$.repo}.git`,$.ref,$.subpath);case"git":return G0($.url,$.ref,$.subpath);case"well-known":{let J={"anthropic-skills":"https://github.com/anthropics/skills.git"}[$.name];if(!J)throw new M(`Unknown well-known skill source "${$.name}".`);return G0(J,$.ref,void 0)}default:{let q=$;throw new M("Unsupported source kind.")}}}async function G0($,q,J){let X=await d8(i8(n8(),"kman-skill-"));if(await k$(["clone","--depth","1",$,X]),q)try{await k$(["fetch","--depth","1","origin",q],X),await k$(["checkout","FETCH_HEAD"],X)}catch{await k$(["fetch","--unshallow"],X).catch(()=>{}),await k$(["checkout",q],X)}return{rootDir:X,subpath:J,cleanup:()=>l8(X,{recursive:!0,force:!0})}}function k$($,q){return new Promise((J,X)=>{let Z=m8("git",$,{cwd:q,stdio:["ignore","pipe","pipe"]}),z="";Z.stderr?.on("data",(Q)=>{z+=Q.toString()}),Z.on("error",(Q)=>{if(Q.code==="ENOENT")X(new r("git not found on PATH; cannot fetch skill sources."));else X(Q)}),Z.on("exit",(Q)=>{if(Q===0)J();else X(new M(`git ${$.join(" ")} failed: ${z.trim()}`))})})}async function U1($){let q=B1(C($.agent),$.skill),J=await z0(q);if(!J)throw new M(`Skill "${$.skill}" has no .kman-skill.json manifest; cannot update. Use "skills remove" then "skills add".`);if(!$.force){let z=await Q1(q);if(z){let Q=await s8(q);if(Q&&Q.getTime()>z.getTime()+1000)throw new M(`Skill "${$.skill}" has local modifications newer than the manifest. Re-running update would overwrite them. Pass --force or "skills remove" first.`)}}let X=X0(J.source,J.ref),Z=await Y0(X);try{let z=await Z0(Z.rootDir,Z.subpath),Q=z.find((B)=>B.name===$.skill)??z[0];if(!Q)throw new M(`No skill named "${$.skill}" in source ${J.source}.`);let{installedPath:G}=await Q0({agent:$.agent,source:X,skill:Q,installName:$.skill,force:!0});return{installedPath:G}}finally{await Z.cleanup()}}async function s8($){let q=null,J=[$];while(J.length>0){let X=J.pop(),Z;try{Z=await t8(X,{withFileTypes:!0})}catch{continue}for(let z of Z){let Q=B1(X,z.name);if(z.isDirectory()){J.push(Q);continue}if(z.name===".kman-skill.json")continue;try{let G=await p8(Q);if(!q||G.mtime>q)q=G.mtime}catch{}}}return q}import{rm as a8,stat as o8}from"node:fs/promises";import{join as r8}from"node:path";async function V1($,q){let J=r8(C($),q);try{if(!(await o8(J)).isDirectory())throw new M(`Skill path is not a directory: ${J}`)}catch(X){if(X.code==="ENOENT")throw new M(`Skill "${q}" not found for agent "${$}".`);throw X}return await a8(J,{recursive:!0,force:!0}),J}import{readdir as e8}from"node:fs/promises";import{join as $J}from"node:path";async function W0($){let q=C($),J;try{J=await e8(q,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT")return[];throw Z}let X=[];for(let Z of J){if(!Z.isDirectory())continue;let z=$J(q,Z.name),Q=await z0(z);X.push({name:Z.name,dir:z,manifest:Q})}return X.sort((Z,z)=>Z.name.localeCompare(z.name))}function M1($){let q=[],J;for(let X=0;X<$.length;X++){let Z=$[X];if(Z==="-a"||Z==="--agent"){let z=$[X+1];if(z===void 0||z.startsWith("-"))throw new M(`Missing value for ${Z}.`);Gq(J),J=z,X++;continue}if(Z.startsWith("--agent=")){Gq(J),J=Z.slice(8);continue}if(Z.startsWith("-a=")){Gq(J),J=Z.slice(3);continue}q.push(Z)}return{rest:q,agent:J}}function Gq($){if($!==void 0)throw new M("--agent specified more than once.")}function m(){let $=process.env.KMAN_SELECTED_AGENT;if(!$)throw new M("Missing required --agent <name>. Agent-scoped commands need a target agent.");return $}function K1(){return process.env.KMAN_SELECTED_AGENT||void 0}import{emitKeypressEvents as qJ}from"node:readline";function JJ($){let q=$.selected.length;if(q===0)return;$.cursor=($.cursor-1+q)%q}function XJ($){let q=$.selected.length;if(q===0)return;$.cursor=($.cursor+1)%q}function ZJ($){if($.selected.length===0)return;$.selected[$.cursor]=!$.selected[$.cursor]}function zJ($){let q=$.selected.length>0&&$.selected.every(Boolean);$.selected.fill(!q)}var k="\x1B[",D={hideCursor:`${k}?25l`,showCursor:`${k}?25h`,clearDown:`${k}J`,moveToCol1:`${k}1G`,up:($)=>$>0?`${k}${$}A`:"",dim:($)=>`${k}2m${$}${k}22m`,bold:($)=>`${k}1m${$}${k}22m`,cyan:($)=>`${k}36m${$}${k}39m`,green:($)=>`${k}32m${$}${k}39m`,red:($)=>`${k}31m${$}${k}39m`};function QJ($,q,J,X){let Z=[];Z.push(`${D.bold("?")} ${$} ${D.dim("(↑/↓ navigate · space toggle · a select all · enter confirm · esc cancel)")}`);for(let[z,Q]of q.entries()){let G=z===J.cursor,B=J.selected[z],Y=G?D.cyan("❯"):" ",W=B?D.green("●"):D.dim("○"),V=G?D.cyan(Q.label):Q.label,F=Q.hint?` ${D.dim(Q.hint)}`:"";Z.push(`${Y} ${W} ${V}${F}`)}if(X)Z.push(D.red(X));return{text:Z.join(`
|
|
79
|
+
`)+`
|
|
80
|
+
`,lineCount:Z.length}}async function F1($){let{items:q,message:J}=$;if(q.length===0)return[];let X=$.requireOne!==!1,Z=new Set($.initialSelected??[]),z={cursor:0,selected:q.map((F)=>Z.has(F.value))},Q=process.stdout,G=process.stdin,B=G.isRaw===!0,Y=0,W="";function V(){if(Y>0)Q.write(D.moveToCol1),Q.write(D.up(Y)),Q.write(D.clearDown);let F=QJ(J,q,z,W);Q.write(F.text),Y=F.lineCount}return new Promise((F,S)=>{function H(){G.off("keypress",fq);try{if(!B&&G.isTTY)G.setRawMode(!1)}catch{}G.pause(),Q.write(D.showCursor)}function d(){Q.write(D.moveToCol1),Q.write(D.up(Y)),Q.write(D.clearDown)}function G$(){H(),d();let N$=q.filter((o,E)=>z.selected[E]);Q.write(`${D.bold("✓")} ${J} ${D.dim("—")} ${D.green(N$.map((o)=>o.label).join(", "))}
|
|
81
|
+
`),F(N$.map((o)=>o.value))}function b$(){H(),d(),Q.write(`${D.red("✗")} ${J} ${D.dim("(cancelled)")}
|
|
82
|
+
`),S(new M("Selection cancelled."))}function fq(N$,o){let E=o.name;if(o.ctrl&&E==="c")return b$();if(E==="escape"||E==="q")return b$();if(E==="up"||E==="k")return JJ(z),W="",V();if(E==="down"||E==="j")return XJ(z),W="",V();if(E==="space")return ZJ(z),W="",V();if(E==="a")return zJ(z),W="",V();if(E==="return"){if(X&&z.selected.every((p1)=>!p1))return W="! Select at least one item, or press Esc to cancel.",V();return G$()}}try{if(qJ(G),G.isTTY)G.setRawMode(!0);G.resume(),Q.write(D.hideCursor),G.on("keypress",fq),V()}catch(N$){H(),S(N$)}})}function N1(){let $=new O("skills").description("Per-agent skills management (add | list | show | update | remove).");return $.command("add").description("Install one or more skills from a source.").requiredOption("--source <source>","Source (path, owner/repo[/path][@ref], URL, or well-known name).").option("--skill <name>","Skill name to install (repeatable).",GJ,[]).option("--all","Install every skill discovered in the source.").option("--ref <ref>","Pin a branch, tag, or commit.").option("--force","Overwrite an existing skill of the same name.").action(async(q)=>{let J=m(),X=X0(q.source,q.ref),Z=await Y0(X);try{let z=await Z0(Z.rootDir,Z.subpath),Q=await YJ(z,q.skill.length>0?q.skill:void 0,q.all===!0);for(let G of Q){let B=await Q0({agent:J,source:X,skill:G,force:q.force===!0});process.stdout.write(`Installed ${G.name} → ${B.installedPath}
|
|
83
|
+
`)}}finally{await Z.cleanup()}}),$.command("list").description("List installed skills for an agent.").action(async()=>{let q=m(),J=await W0(q);if(J.length===0){process.stdout.write(`(no skills installed for ${q})
|
|
84
|
+
`);return}for(let X of J){let Z=X.manifest?.source??"local",z=X.manifest?.ref?`@${X.manifest.ref}`:"";process.stdout.write(`${X.name} ${Z}${z}
|
|
85
|
+
`)}}),$.command("show").description("Show details for an installed skill.").requiredOption("--skill <name>","Skill name.").action(async(q)=>{let J=m(),Z=(await W0(J)).find((z)=>z.name===q.skill);if(!Z)throw new M(`Skill "${q.skill}" not installed for agent "${J}".`);if(process.stdout.write(`name: ${Z.name}
|
|
86
|
+
`),process.stdout.write(`directory: ${Z.dir}
|
|
87
|
+
`),Z.manifest){if(process.stdout.write(`source: ${Z.manifest.source}
|
|
88
|
+
`),Z.manifest.source_url)process.stdout.write(`source_url: ${Z.manifest.source_url}
|
|
89
|
+
`);if(Z.manifest.ref)process.stdout.write(`ref: ${Z.manifest.ref}
|
|
90
|
+
`);process.stdout.write(`installed_at: ${Z.manifest.installed_at}
|
|
70
91
|
`)}else process.stdout.write(`(no manifest — local skill, detached)
|
|
71
|
-
`)}),$.command("update").description("Re-fetch an installed skill from its recorded source.").option("--skill <name>","Skill name to update.").option("--all","Update every installed skill.").option("--force","Bypass local-modification safety check.").action(async(q)=>{let
|
|
72
|
-
`)}}),$.command("remove").description("Remove an installed skill.").requiredOption("--skill <name>","Skill name.").action(async(q)=>{let
|
|
73
|
-
`)}),$}function
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
92
|
+
`)}),$.command("update").description("Re-fetch an installed skill from its recorded source.").option("--skill <name>","Skill name to update.").option("--all","Update every installed skill.").option("--force","Bypass local-modification safety check.").action(async(q)=>{let J=m();if(!q.skill&&!q.all)throw new M("Pass --skill <name> or --all.");let X=q.all?(await W0(J)).filter((Z)=>!!Z.manifest).map((Z)=>Z.name):[q.skill];for(let Z of X){let z=await U1({agent:J,skill:Z,force:q.force===!0});process.stdout.write(`Updated ${Z} → ${z.installedPath}
|
|
93
|
+
`)}}),$.command("remove").description("Remove an installed skill.").requiredOption("--skill <name>","Skill name.").action(async(q)=>{let J=m(),X=await V1(J,q.skill);process.stdout.write(`Removed ${X}
|
|
94
|
+
`)}),$}function GJ($,q){return[...q,$]}async function YJ($,q,J){if($.length===0)throw new M("No SKILL.md found in source.");if(q&&q.length>0){let X=$.filter((Z)=>q.includes(Z.name));if(X.length===0)throw new M(`Requested skills not found in source. Available: ${$.map((Z)=>Z.name).join(", ")}.`);return X}if(J)return $;if($.length===1)return $;if(process.stdin.isTTY&&process.stdout.isTTY)return WJ($);throw new M(`Source contains multiple skills. Pass --skill <name> (repeatable) or --all. Discovered: ${$.map((X)=>X.name).join(", ")}.`)}async function WJ($){return F1({message:`Select skills to install (${$.length} discovered)`,items:$.map((q)=>({value:q,label:q.name,hint:q.relPath}))})}import{spawn as BJ}from"node:child_process";function F$($,q){let J={...process.env,...$.env},X={cwd:$.cwd,env:J,stdio:"inherit",shell:!1,...q.options};return BJ(q.command,q.args,X)}var UJ={ask:"default",auto:"acceptEdits",yolo:"bypassPermissions"};class P1{name="claude-code";capabilities={supportClaudeCodePlugin:!0,supportsAppendSystemPrompt:!0,supportsNativeResume:!0};binary;constructor($){this.binary=$??process.env.KMAN_CLAUDE_BIN??"claude"}mapPermission($){return UJ[$]??"default"}async spawn($,q){let J=this.buildArgs($,!1);return F$($,{command:this.binary,args:J})}async chat($,q){let J=this.buildArgs($,!0);return F$($,{command:this.binary,args:J})}buildArgs($,q){let J=[];if(J.push("--plugin-dir",$.agentDir),J.push("--agent",`${$.profile.name}:${$.profile.name}`),$.model)J.push("--model",$.model);let X=$.permissionModeRaw??this.mapPermission($.permission);if(J.push("--permission-mode",X),$.maxTurns!==void 0)J.push("--max-turns",String($.maxTurns));if(!q){if(J.push("--output-format",$.outputFormat),$.stream&&$.outputFormat==="stream-json")J.push("--include-partial-messages")}for(let Z of $.extraArgs)J.push(Z);if(!q&&$.task!==void 0)J.push("--print",$.task);return J}}function D1($){return new P1($)}var S1={ask:null,auto:"--allow-all-tools",yolo:"--yolo"};class I1{name="copilot-cli";capabilities={supportClaudeCodePlugin:!0,supportsAppendSystemPrompt:!0,supportsNativeResume:!0};binary;constructor($){this.binary=$??process.env.KMAN_COPILOT_BIN??"copilot"}mapPermission($){return S1[$]??"(default)"}async spawn($,q){let J=this.buildArgs($,!1);return F$($,{command:this.binary,args:J})}async chat($,q){let J=this.buildArgs($,!0);return F$($,{command:this.binary,args:J})}buildArgs($,q){let J=[];if(J.push("--plugin-dir",$.agentDir),J.push("--agent",`${$.profile.name}:${$.profile.name}`),$.permissionModeRaw===void 0){let X=S1[$.permission];if(X)J.push(X)}if($.model)J.push("--model",$.model);if(!q){if($.outputFormat==="stream-json")J.push("--output-format","json","--stream","on");else if($.outputFormat==="json"||$.outputFormat==="text")J.push("--output-format",$.outputFormat)}for(let X of $.extraArgs)J.push(X);if(!q&&$.task!==void 0)J.push("-p",$.task);return J}}function f1($){return new I1($)}var L1={"claude-code":D1,"copilot-cli":f1};function B0($){let q=L1[$];if(!q)throw new M(`Unknown backend "${$}". Built-in backends: ${Object.keys(L1).join(", ")}.`);return q()}import{createInterface as SJ}from"node:readline";var L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603};class j extends Error{code;data;constructor($,q,J){super(q);if(this.code=$,J!==void 0)this.data=J}}import{readFile as VJ,readdir as MJ,stat as KJ}from"node:fs/promises";async function U0($){let q=I$(),J;try{J=await MJ(q,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT")return[];throw Z}let X=[];for(let Z of J){if(!Z.isDirectory())continue;if($&&Z.name===$)continue;try{let z=await h(Z.name);X.push({name:z.name,description:z.description,runtime:z.runtime.default,model:z.runtime.model})}catch{}}return X.sort((Z,z)=>Z.name.localeCompare(z.name)),X}async function V0($){let q=await h($),J="";try{J=await VJ(U$(q.name,q.soul.prompt_file),"utf8")}catch(X){if(X.code!=="ENOENT")throw X}return{profile:q,soul:J,directory:I(q.name)}}async function Yq($){try{return(await KJ(I($))).isDirectory()}catch{return!1}}import{spawn as FJ}from"node:child_process";async function w1($,q,J){let X=[...$.baseArgs,"-a",q.agent,"run","--task",q.task];if(q.runtime)X.push("--runtime",q.runtime);if(q.model)X.push("--model",q.model);if(q.permission)X.push("--permission",q.permission);if(q.outputFormat)X.push("--output",q.outputFormat);if(q.cwd)X.push("--cwd",q.cwd);let Z={...process.env};if(q.appendToRunChain){let z=Z.KMAN_RUN_CHAIN??"";Z.KMAN_RUN_CHAIN=z?`${z},${q.appendToRunChain}`:q.appendToRunChain}return new Promise((z,Q)=>{let G=FJ($.command,X,{stdio:["ignore","pipe","pipe"],env:Z,shell:!1}),B="",Y="";G.stdout?.setEncoding("utf8"),G.stderr?.setEncoding("utf8"),G.stdout?.on("data",(V)=>{B+=V}),G.stderr?.on("data",(V)=>{Y+=V});let W;if(J&&J>0)W=setTimeout(()=>{if(!G.killed)G.kill("SIGTERM")},J);G.on("error",(V)=>{if(W)clearTimeout(W);Q(V)}),G.on("exit",(V)=>{if(W)clearTimeout(W);z({exitCode:V??0,stdout:B,stderr:Y})})})}var x1={name:"kman_list_agents",description:"List kman-managed specialist agents available on this machine. Use first when a task may benefit from delegation. Returns each agent's name, description, default runtime, and default model; the local roster may change between conversations.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},j1={name:"kman_describe_agent",description:"Read one agent's full profile and soul prompt. Use after `kman_list_agents` to confirm fit when the roster summary is not enough or multiple agents look relevant.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent name (lowercase kebab-case)."}},required:["agent"],additionalProperties:!1}},H1={name:"kman_run_agent",description:"Run a one-shot task with a kman-managed peer agent and return its stdout. Use after choosing an agent from `kman_list_agents`. The task must be self-contained: the peer receives this text, not your conversation or scratch notes, so include relevant context, file paths, constraints, and done criteria. Sessions are not shared; self-delegation and delegation cycles are rejected.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Target agent name from `kman_list_agents`."},task:{type:"string",description:"Self-contained task description with the context, paths, constraints, and done criteria needed."},runtime:{type:"string",description:"Optional override for the agent's default runtime (claude-code | copilot-cli)."},model:{type:"string",description:"Optional override for the agent's default model."},permission:{type:"string",enum:["ask","auto","yolo"],description:"Permission level for the spawned backend."},cwd:{type:"string",description:"Working directory for the spawned runtime."}},required:["agent","task"],additionalProperties:!1}};function O1(){return[x1,j1,H1]}async function _1($,q,J){switch($){case x1.name:return NJ(J);case j1.name:return PJ(q);case H1.name:return DJ(q,J);default:throw new j(L.MethodNotFound,`Unknown tool: ${$}`)}}async function NJ($){let q=await U0($.selfAgent);return{content:[{type:"text",text:q.length===0?"No kman agents found at ~/.kman/agents/. Create one with `kman agent create <name>`.":JSON.stringify(q,null,2)}]}}async function PJ($){let q=Wq($,"agent");if(!await Yq(q))return Q$(`Agent "${q}" not found at ~/.kman/agents/${q}/.`);let J=await V0(q);return{content:[{type:"text",text:JSON.stringify({name:J.profile.name,description:J.profile.description,runtime:J.profile.runtime,soul:{prompt_file:J.profile.soul.prompt_file,contents:J.soul},defaults:J.profile.defaults,directory:J.directory},null,2)}]}}async function DJ($,q){let J=Wq($,"agent"),X=Wq($,"task");if(q.selfAgent&&J===q.selfAgent)return Q$(`Refusing to delegate to "${J}" — that is the agent currently running this MCP server. `+"Self-delegation would loop the agent forever.");let Z=process.env.KMAN_RUN_CHAIN,z=Z&&!Z.includes("${")?Z.split(",").filter(Boolean):[];if(z.includes(J))return Q$(`Refusing to delegate to "${J}" — cycle detected (chain so far: ${z.join(" → ")}).`);if(z.length>=8)return Q$(`Delegation depth limit reached (chain: ${z.join(" → ")}).`);if(!await Yq(J))return Q$(`Agent "${J}" not found at ~/.kman/agents/${J}/.`);let Q;try{Q=await w1(q.invocation,{agent:J,task:X,...typeof $.runtime==="string"?{runtime:$.runtime}:{},...typeof $.model==="string"?{model:$.model}:{},...typeof $.permission==="string"?{permission:$.permission}:{},...typeof $.cwd==="string"?{cwd:$.cwd}:{},appendToRunChain:q.selfAgent??J},q.runTimeoutMs)}catch(B){return Q$(`Failed to spawn kman subprocess: ${B.message}. Check that 'kman' is on PATH or set KMAN_BIN.`)}let G=Q.stdout.trim();if(Q.exitCode===0)return{content:[{type:"text",text:G.length>0?G:"(agent produced no output)"}]};return Q$(`Agent "${J}" exited with code ${Q.exitCode}.
|
|
95
|
+
`+(Q.stderr?`stderr:
|
|
96
|
+
${Q.stderr.trim()}
|
|
97
|
+
`:"")+(G?`stdout:
|
|
98
|
+
${G}`:""))}function Wq($,q){let J=$[q];if(typeof J!=="string"||J.length===0)throw new j(L.InvalidParams,`Missing or non-string argument: "${q}".`);return J}function Q$($){return{content:[{type:"text",text:$}],isError:!0}}var Bq={uri:"kman://agents",name:"Agent roster",description:"JSON list of every agent under ~/.kman/agents/.",mimeType:"application/json"},y1={uriTemplate:"kman://agents/{name}",name:"Agent profile",description:"Per-agent profile + soul prompt as a single JSON document.",mimeType:"application/json"};function T1(){return[Bq]}function k1(){return[y1]}async function R1($,q){if($===Bq.uri){let X=await U0(q.selfAgent);return{uri:$,mimeType:Bq.mimeType,text:JSON.stringify(X,null,2)}}let J=/^kman:\/\/agents\/([a-z][a-z0-9-]{0,62})$/.exec($);if(J&&J[1]){let X=J[1];if(q.selfAgent&&X===q.selfAgent)throw new j(L.InvalidParams,`Resource ${$} is hidden: agent "${X}" hosts this MCP server.`);let Z=await V0(X);return{uri:$,mimeType:y1.mimeType,text:JSON.stringify({name:Z.profile.name,description:Z.profile.description,runtime:Z.profile.runtime,soul:{prompt_file:Z.profile.soul.prompt_file,contents:Z.soul},defaults:Z.profile.defaults,directory:Z.directory},null,2)}}throw new j(L.InvalidParams,`Unknown resource URI: ${$}`)}var Uq={name:"find-agent",description:"Find the best kman-managed agent for a task and explain the choice.",arguments:[{name:"task",description:"Short natural-language goal.",required:!0}]},Vq={name:"list-agents",description:"List the available kman-managed agents in a readable summary.",arguments:[]},Mq={name:"delegate-task",description:"Run a task with a specific kman-managed agent and summarize the result.",arguments:[{name:"agent",description:"Target agent name (lowercase kebab-case).",required:!0},{name:"task",description:"Self-contained task for the peer agent.",required:!0}]},Kq={name:"second-opinion",description:"Ask a peer agent for an independent take on an analysis, review, or trade-off.",arguments:[{name:"agent",description:"Peer agent name.",required:!0},{name:"topic",description:"Topic plus your current analysis for context.",required:!0}]};function A1(){return[Vq,Uq,Mq,Kq]}function E1($,q){switch($){case Vq.name:return{description:Vq.description,messages:[{role:"user",content:{type:"text",text:"Call kman_list_agents and summarize the available agents in a compact, readable list. Include each agent's name, description, default runtime, and model when present."}}]};case Uq.name:{let J=R$(q,"task");return{description:Uq.description,messages:[{role:"user",content:{type:"text",text:`Task: ${J}
|
|
99
|
+
|
|
100
|
+
Call kman_list_agents, choose the single best-fit agent, and explain the choice in one sentence. If the roster summary is not enough, call kman_describe_agent for the top candidate(s) before deciding. Ask me before dispatching with kman_run_agent.`}}]}}case Mq.name:{let J=R$(q,"agent"),X=R$(q,"task");return{description:Mq.description,messages:[{role:"user",content:{type:"text",text:`Run this task with the kman-managed agent "${J}":
|
|
80
101
|
|
|
81
|
-
|
|
82
|
-
|
|
102
|
+
${X}
|
|
103
|
+
|
|
104
|
+
Call kman_run_agent with agent="${J}". Summarize the result in your own words and flag anything the agent could not complete.`}}]}}case Kq.name:{let J=R$(q,"agent"),X=R$(q,"topic");return{description:Kq.description,messages:[{role:"user",content:{type:"text",text:`Get a second opinion from the kman-managed agent "${J}" on:
|
|
105
|
+
|
|
106
|
+
${X}
|
|
107
|
+
|
|
108
|
+
First call kman_describe_agent to confirm the agent is a good fit. If so, call kman_run_agent with enough context for an independent take; do not just forward my wording verbatim. Compare their view to mine and tell me where you net out.`}}]}}default:throw new j(L.InvalidParams,`Unknown prompt: ${$}`)}}function R$($,q){let J=$[q];if(typeof J!=="string"||J.length===0)throw new j(L.InvalidParams,`Missing required argument: "${q}".`);return J}var IJ="2024-11-05",fJ="This MCP server (kman) exposes locally managed specialist agents. Each agent has its own soul prompt, skills, and backend.\n\nWhen a user request may benefit from a specialist (code review, refactoring, research, test writing, doc rewrites, niche-domain analysis), consider delegating:\n\n 1. Call `kman_list_agents` to see the current local roster.\n 2. If needed, call `kman_describe_agent` to confirm fit from the agent's profile and soul prompt.\n 3. Call `kman_run_agent` with the agent name and a self-contained task. The response is the agent's stdout; incorporate it into your own answer and cite the agent by name.\n\nIf no agent fits, do the work yourself. Each `kman_run_agent` call is a fresh one-shot run; sessions are not shared and the peer cannot see your conversation or scratch notes. Self-delegation and cycles are blocked server-side.\n\nFor reusable workflows, four prompts are available for hosts to surface as slash commands: `list-agents` (show the roster), `find-agent` (choose a specialist), `delegate-task` (hand a task off), and `second-opinion` (independent review).";function b1($={}){let q=$.input??process.stdin,J=$.output??process.stdout,X={invocation:{command:$.invocation?.command??process.execPath,baseArgs:$.invocation?.baseArgs??(process.argv[1]?[process.argv[1]]:[])},runTimeoutMs:$.runTimeoutMs??600000,...$.selfAgent?{selfAgent:$.selfAgent}:{}},Z=SJ({input:q,crlfDelay:1/0}),z=(B)=>{J.write(JSON.stringify(B)+`
|
|
109
|
+
`)},Q=new Set;return{done:new Promise((B)=>{Z.on("line",(Y)=>{let W=Y.trim();if(!W)return;let V=LJ(W,X,z).catch(()=>{return});Q.add(V),V.finally(()=>Q.delete(V))}),Z.on("close",()=>{Promise.allSettled(Array.from(Q)).then(()=>B())})}),stop:()=>Z.close()}}async function LJ($,q,J){let X;try{X=JSON.parse($)}catch{J({jsonrpc:"2.0",id:null,error:{code:L.ParseError,message:"Invalid JSON."}});return}if(typeof X!=="object"||X===null){J({jsonrpc:"2.0",id:null,error:{code:L.InvalidRequest,message:"Not a JSON object."}});return}let Z=X,z="id"in Z?Z.id:null;if(Z.jsonrpc!=="2.0"||typeof Z.method!=="string"){if("id"in Z)J({jsonrpc:"2.0",id:z,error:{code:L.InvalidRequest,message:"Not JSON-RPC 2.0."}});return}let Q="id"in Z;try{let G=await wJ(Z.method,Z.params,q);if(Q&&G!==void 0)J({jsonrpc:"2.0",id:z,result:G})}catch(G){if(!Q)return;if(G instanceof j)J({jsonrpc:"2.0",id:z,error:{code:G.code,message:G.message,...G.data!==void 0?{data:G.data}:{}}});else J({jsonrpc:"2.0",id:z,error:{code:L.InternalError,message:G.message}})}}async function wJ($,q,J){switch($){case"initialize":return{protocolVersion:IJ,capabilities:{tools:{listChanged:!1},resources:{listChanged:!1,subscribe:!1},prompts:{listChanged:!1}},serverInfo:{name:"kman",version:xJ()},instructions:fJ};case"notifications/initialized":case"notifications/cancelled":case"notifications/roots/list_changed":return;case"ping":return{};case"tools/list":return{tools:O1()};case"tools/call":{let X=Fq(q),Z=typeof X.name==="string"?X.name:"",z=X.arguments??{};if(!Z)throw new j(L.InvalidParams,'tools/call requires "name".');return _1(Z,z,J)}case"resources/list":return{resources:T1()};case"resources/templates/list":return{resourceTemplates:k1()};case"resources/read":{let X=Fq(q),Z=typeof X.uri==="string"?X.uri:"";if(!Z)throw new j(L.InvalidParams,'resources/read requires "uri".');return{contents:[await R1(Z,{...J.selfAgent?{selfAgent:J.selfAgent}:{}})]}}case"prompts/list":return{prompts:A1()};case"prompts/get":{let X=Fq(q),Z=typeof X.name==="string"?X.name:"",z=X.arguments??{};if(!Z)throw new j(L.InvalidParams,'prompts/get requires "name".');return E1(Z,z)}default:throw new j(L.MethodNotFound,`Method not implemented: ${$}`)}}function Fq($){if(typeof $!=="object"||$===null||Array.isArray($))throw new j(L.InvalidParams,"params must be an object.");return $}function xJ(){return process.env.KMAN_VERSION??"0.0.0"}import{mkdir as jJ,writeFile as HJ,readFile as OJ}from"node:fs/promises";import{dirname as _J}from"node:path";import{join as yJ}from"node:path";function TJ(){return yJ(S$(),"runtime","mcp-config.json")}async function h1($){let q=TJ();await jJ(_J(q),{recursive:!0});let J=[...$.kmanBaseArgs??[],"mcp","--self-from-env"],X={mcpServers:{kman:{command:$.kmanCommand,args:J,env:{KMAN_SELF_AGENT:"${KMAN_SELF_AGENT}",KMAN_RUN_CHAIN:"${KMAN_RUN_CHAIN}"}}}};return await kJ(q,JSON.stringify(X,null,2)+`
|
|
110
|
+
`),q}async function kJ($,q){try{if(await OJ($,"utf8")===q)return}catch{}await HJ($,q,"utf8")}import{mkdir as C1,readFile as RJ,writeFile as K0}from"node:fs/promises";import{homedir as Nq,platform as AJ}from"node:os";import{dirname as u1,join as M0,resolve as v1}from"node:path";var x="kman";function Pq($,q={}){let J={command:$.command,args:[...$.baseArgs,"mcp"],env:{KMAN_SELF_AGENT:"${KMAN_SELF_AGENT}",KMAN_RUN_CHAIN:"${KMAN_RUN_CHAIN}"}};if(q.copilotType)J.type="local";return J}async function g1($){let q;if($==="claude-code"||$==="claude")q=Dq("user");else if($==="copilot-cli"||$==="copilot")q=Sq();else return!1;try{let X=(await E$(q)).mcpServers;if(typeof X!=="object"||X===null)return!1;return Object.prototype.hasOwnProperty.call(X,x)}catch{return!1}}function c1(){let $=new O("mcp").description("Expose kman-managed agents to other agent runtimes over the Model Context Protocol.");return $.option("--self <name>","Hide this agent from listings (used by kman during auto-injection).").option("--self-from-env","Read the agent name to hide from the KMAN_SELF_AGENT env var. Used by the injected plugin so a single on-disk .mcp.json works for every agent.").option("--run-timeout <ms>","Per-tool-call timeout in milliseconds (default 600000, 0 disables).",(q)=>Number.parseInt(q,10)).action(async(q)=>{let J=q.selfFromEnv?process.env.KMAN_SELF_AGENT:q.self,X=J&&!J.includes("${")?J:void 0;process.env.KMAN_VERSION=W$.version;let Z=A$();await b1({invocation:{command:Z.command,baseArgs:Z.baseArgs},...X?{selfAgent:X}:{},...q.runTimeout!==void 0?{runTimeoutMs:q.runTimeout}:{}}).done}),$.command("install <runtime>").description("Register the kman MCP server in an external runtime config (claude-code | copilot-cli).").option("--scope <scope>","user | project (claude-code only; default user).","user").option("--force",'Overwrite an existing "kman" entry if present.').action(async(q,J)=>{let X=A$();if(q==="claude-code"||q==="claude")await EJ(X,J.scope==="project"?"project":"user",J.force===!0);else if(q==="copilot-cli"||q==="copilot")await hJ(X,J.force===!0);else throw new M(`Unknown runtime "${q}". Use claude-code or copilot-cli.`)}),$.command("config").description("Print a JSON snippet that registers the kman MCP server (paste into any MCP host).").action(()=>{let q=A$(),J={mcpServers:{[x]:Pq(q)}};process.stdout.write(JSON.stringify(J,null,2)+`
|
|
111
|
+
`)}),$.command("uninstall <runtime>").description("Remove the kman MCP server from an external runtime config.").option("--scope <scope>","user | project (claude-code only; default user).","user").action(async(q,J)=>{if(q==="claude-code"||q==="claude")await bJ(J.scope==="project"?"project":"user");else if(q==="copilot-cli"||q==="copilot")await CJ();else throw new M(`Unknown runtime "${q}". Use claude-code or copilot-cli.`)}),$}function A$(){let $=process.env.KMAN_BIN;if($&&$.length>0)return{command:$,baseArgs:[]};let q=process.argv[1];if(q&&/[\\/]kman(\.(?:js|cjs|mjs))?$/.test(q)&&!q.endsWith(".ts"))return{command:"kman",baseArgs:[]};if(!q)return{command:"kman",baseArgs:[]};return{command:process.execPath,baseArgs:[v1(q)]}}async function EJ($,q,J){let X=Dq(q),Z=await E$(X),z=Z.mcpServers??{};if(z[x]&&!J)throw new M(`Claude Code config already has an MCP server named "${x}". Re-run with --force to overwrite.`);z[x]=Pq($),Z.mcpServers=z,await C1(u1(X),{recursive:!0}),await K0(X,JSON.stringify(Z,null,2)+`
|
|
112
|
+
`,"utf8"),process.stdout.write(`Registered "${x}" MCP server in ${X}
|
|
113
|
+
`)}async function bJ($){let q=Dq($),J=await E$(q),X=J.mcpServers??{};if(!X[x]){process.stdout.write(`No "${x}" entry in ${q}.
|
|
114
|
+
`);return}delete X[x],J.mcpServers=X,await K0(q,JSON.stringify(J,null,2)+`
|
|
115
|
+
`,"utf8"),process.stdout.write(`Removed "${x}" from ${q}
|
|
116
|
+
`)}async function hJ($,q){let J=Sq(),X=await E$(J),Z=X.mcpServers??{};if(Z[x]&&!q)throw new M(`Copilot CLI config already has an MCP server named "${x}". Re-run with --force to overwrite.`);Z[x]=Pq($,{copilotType:!0}),X.mcpServers=Z,await C1(u1(J),{recursive:!0}),await K0(J,JSON.stringify(X,null,2)+`
|
|
117
|
+
`,"utf8"),process.stdout.write(`Registered "${x}" MCP server in ${J}
|
|
118
|
+
`)}async function CJ(){let $=Sq(),q=await E$($),J=q.mcpServers??{};if(!J[x]){process.stdout.write(`No "${x}" entry in ${$}.
|
|
119
|
+
`);return}delete J[x],q.mcpServers=J,await K0($,JSON.stringify(q,null,2)+`
|
|
120
|
+
`,"utf8"),process.stdout.write(`Removed "${x}" from ${$}
|
|
121
|
+
`)}function Dq($){if($==="project")return v1(process.cwd(),".claude.json");return M0(Nq(),".claude.json")}function Sq(){if(AJ()==="win32"){let $=process.env.APPDATA??M0(Nq(),"AppData","Roaming");return M0($,"github-copilot","mcp_config.json")}return M0(Nq(),".config","github-copilot","mcp_config.json")}async function E$($){try{let q=await RJ($,"utf8");if(!q.trim())return{};let J=JSON.parse(q);if(typeof J!=="object"||J===null||Array.isArray(J))throw new M(`${$} is not a JSON object — refusing to edit.`);return J}catch(q){if(q.code==="ENOENT")return{};if(q instanceof M)throw q;if(q instanceof SyntaxError)throw new M(`${$} contains invalid JSON — refusing to edit: ${q.message}`);throw q}}async function F0($){if(process.env.KMAN_NO_MCP==="1")return $;let q=uJ($.backend);if(!q)return $;let J=await g1($.backend),X={...$.env,KMAN_SELF_AGENT:$.profile.name,KMAN_RUN_CHAIN:vJ(process.env.KMAN_RUN_CHAIN,$.profile.name),KMAN_SELECTED_AGENT:""};if(J)return{...$,env:X};let Z=A$(),z=await h1({kmanCommand:Z.command,kmanBaseArgs:Z.baseArgs});return{...$,extraArgs:[q,z,...$.extraArgs],env:X}}function uJ($){switch($){case"claude-code":return"--mcp-config";case"copilot-cli":return"--additional-mcp-config";default:return}}function vJ($,q){if(!$)return q;let J=$.split(",").filter(Boolean);if(J[J.length-1]===q)return $;return[...J,q].join(",")}function N0($){if($==="ask"||$==="auto"||$==="yolo")return $;throw new M(`Invalid --permission "${$}". Expected: ask | auto | yolo.`)}function m1($){if($==="text"||$==="json"||$==="stream-json")return $;throw new M(`Invalid --output "${$}". Expected: text | json | stream-json.`)}function d1(){return new O("run").description("Run an agent on a single task non-interactively.").option("--task <text>","Task for the agent to perform.").option("--runtime <runtime>","Override the agent's default runtime for this call.").option("--model <id>","Override the agent's default model for this call.").option("--permission <level>","Permission mode (ask | auto | yolo).").option("--runtime-flag <flag>","Pass a runtime-native flag straight through (repeatable).",gJ,[]).option("--output <format>","Output format (text | json | stream-json).").option("--stream","Stream incremental output; implies --output stream-json.").option("--cwd <path>","Working directory for the runtime process.").action(async($)=>{let q=m(),J=await h(q);if($.stream&&$.output&&$.output!=="stream-json")throw new M("--stream conflicts with --output of a different value.");let X=await $0(J,{...$.runtime?{backend:$.runtime}:{},...$.model?{model:$.model}:{},...$.permission?{permission:N0($.permission)}:{},...$.output?{outputFormat:m1($.output)}:{},...$.stream!==void 0?{stream:$.stream===!0}:{},...$.cwd?{cwd:$.cwd}:{},...$.task!==void 0?{task:$.task}:{},runtimeFlags:cJ($.runtimeFlag)}),Z=B0(X.backend),z=await F0(X),{exitCode:Q}=await l2(Z,z);process.exit(Q)})}function gJ($,q){return[...q,$]}function cJ($){let q=[];for(let J of $)if(J.includes("=")&&!J.startsWith("--")){let X=J.indexOf("="),Z=J.slice(0,X),z=J.slice(X+1);q.push(`--${Z}`,z)}else q.push(J);return q}function l1(){return new O("chat").description("Start an interactive session with an agent.").option("--runtime <runtime>","Override the agent's default runtime for this session.").option("--model <id>","Override the agent's default model for this session.").option("--permission <level>","Permission mode (ask | auto | yolo).").option("--runtime-flag <flag>","Pass a runtime-native flag straight through (repeatable).",mJ,[]).option("--cwd <path>","Working directory for the runtime process.").action(async($)=>{let q=m(),J=await h(q),X=await $0(J,{...$.runtime?{backend:$.runtime}:{},...$.model?{model:$.model}:{},...$.permission?{permission:N0($.permission)}:{},...$.cwd?{cwd:$.cwd}:{},runtimeFlags:dJ($.runtimeFlag)}),Z=B0(X.backend),z=await F0(X),{exitCode:Q}=await n2(Z,z);process.exit(Q)})}function mJ($,q){return[...q,$]}function dJ($){let q=[];for(let J of $)if(J.includes("=")&&!J.startsWith("--")){let X=J.indexOf("="),Z=J.slice(0,X),z=J.slice(X+1);q.push(`--${Z}`,z)}else q.push(J);return q}function n1(){return new O("version").description("Print kman CLI version.").action(()=>{process.stdout.write(`kman ${W$.version}
|
|
122
|
+
`)})}function i1(){return new O("doctor").description("Diagnose the environment and (optionally) an agent: runtime binaries, .mcp.json, hooks, bin/, skills.").option("--json","Emit the report as JSON to stdout.").option("-v, --verbose","Show detail / hint lines for ok checks too.").action(async($)=>{let q=K1(),J=await o2({...q?{agent:q}:{}});if($.json)process.stdout.write(JSON.stringify(J,null,2)+`
|
|
123
|
+
`);else process.stdout.write(iJ(J,$.verbose===!0));if(a0(J)==="error")process.exit(lJ(J));process.exit(b.Success)})}function lJ($){for(let q of $.sections)for(let J of q.checks){if(J.severity!=="error")continue;if(J.id.startsWith("backend.")||J.id.startsWith("agent.backend."))return b.BackendUnavailable}return b.UserError}var nJ={ok:"✓",info:"·",warn:"!",error:"✗"};function iJ($,q){let J=[];for(let z of $.sections){if(J.push(`== ${z.title} ==`),z.checks.length===0){J.push(" (no checks)"),J.push("");continue}for(let Q of z.checks)if(J.push(` ${nJ[Q.severity]} [${Q.severity}] ${Q.label}: ${Q.message}`),Q.detail&&(q||Q.severity==="warn"||Q.severity==="error"))J.push(` ${Q.detail}`);J.push("")}let X=a0($),Z=tJ($);return J.push(`overall: ${X} (${Z})`),J.map((z)=>z+`
|
|
124
|
+
`).join("")}function tJ($){let q={ok:0,info:0,warn:0,error:0};for(let J of $.sections)for(let X of J.checks)q[X.severity]++;return["ok","info","warn","error"].map((J)=>`${J}=${q[J]}`).join(" ")}function t1($){if($ instanceof D$){if($.message)process.stderr.write(`kman: ${$.message}
|
|
125
|
+
`);process.exit($.code)}if($ instanceof gq){let J=$.code==="commander.help"||$.code==="commander.helpDisplayed"||$.code==="commander.version"?0:b.UserError;process.exit(J)}let q=$ instanceof Error?$.message:String($);if(process.stderr.write(`kman: unexpected error: ${q}
|
|
126
|
+
`),process.env.KMAN_DEBUG&&$ instanceof Error&&$.stack)process.stderr.write($.stack+`
|
|
127
|
+
`);process.exit(b.AgentError)}var g=new O;g.name("kman").description("Multi-agent management tool.").version(W$.version,"-v, --version","Print kman CLI version.").helpOption("-h, --help","Show help.").showHelpAfterError().exitOverride();g.option("-a, --agent <name>","Target agent name (lowercase kebab-case). Required by agent-scoped subcommands.");g.addCommand($1());g.addCommand(N1());g.addCommand(d1());g.addCommand(l1());g.addCommand(n1());g.addCommand(i1());g.addCommand(c1());var Iq;try{let $=process.argv.slice(2),{rest:q,agent:J}=M1($);if(J!==void 0)process.env.KMAN_SELECTED_AGENT=J;Iq=q}catch($){t1($)}if(Iq.length===0)g.outputHelp(),process.exit(b.UserError);try{await g.parseAsync(Iq,{from:"user"})}catch($){t1($)}
|