@unliftedq/kman 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,82 +1,153 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as g1}from"node:module";var T1=Object.create;var{getPrototypeOf:A1,defineProperty:A0,getOwnPropertyNames:b1}=Object;var C1=Object.prototype.hasOwnProperty;function u1($){return this[$]}var v1,c1,s$=($,q,X)=>{var Z=$!=null&&typeof $==="object";if(Z){var Y=q?v1??=new WeakMap:c1??=new WeakMap,z=Y.get($);if(z)return z}X=$!=null?T1(A1($)):{};let J=q||!$||!$.__esModule?A0(X,"default",{value:$,enumerable:!0}):X;for(let Q of b1($))if(!C1.call(J,Q))A0(J,Q,{get:u1.bind($,Q),enumerable:!0});if(Z)Y.set($,J);return J};var w=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);var a=g1(import.meta.url);var q$=w((t1)=>{class l$ extends Error{constructor($,q,X){super(X);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=q,this.exitCode=$,this.nestedError=void 0}}class b0 extends l${constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}t1.CommanderError=l$;t1.InvalidArgumentError=b0});var w$=w((s1)=>{var{InvalidArgumentError:n1}=q$();class C0{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,X)=>{if(!this.argChoices.includes(q))throw new n1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(q,X);return q},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function d1($){let q=$.name()+($.variadic===!0?"...":"");return $.required?"<"+q+">":"["+q+"]"}s1.Argument=C0;s1.humanReadableArgName=d1});var p$=w((o1)=>{var{humanReadableArgName:a1}=w$();class u0{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((Z)=>!Z._hidden),X=$._getHelpCommand();if(X&&!X._hidden)q.push(X);if(this.sortSubcommands)q.sort((Z,Y)=>{return Z.name().localeCompare(Y.name())});return q}compareOptions($,q){let X=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return X($).localeCompare(X(q))}visibleOptions($){let q=$.options.filter((Z)=>!Z.hidden),X=$._getHelpOption();if(X&&!X.hidden){let Z=X.short&&$._findOption(X.short),Y=X.long&&$._findOption(X.long);if(!Z&&!Y)q.push(X);else if(X.long&&!Y)q.push($.createOption(X.long,X.description));else if(X.short&&!Z)q.push($.createOption(X.short,X.description))}if(this.sortOptions)q.sort(this.compareOptions);return q}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let q=[];for(let X=$.parent;X;X=X.parent){let Z=X.options.filter((Y)=>!Y.hidden);q.push(...Z)}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((X)=>a1(X)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(q?" "+q:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,q){return q.visibleCommands($).reduce((X,Z)=>{return Math.max(X,this.displayWidth(q.styleSubcommandTerm(q.subcommandTerm(Z))))},0)}longestOptionTermLength($,q){return q.visibleOptions($).reduce((X,Z)=>{return Math.max(X,this.displayWidth(q.styleOptionTerm(q.optionTerm(Z))))},0)}longestGlobalOptionTermLength($,q){return q.visibleGlobalOptions($).reduce((X,Z)=>{return Math.max(X,this.displayWidth(q.styleOptionTerm(q.optionTerm(Z))))},0)}longestArgumentTermLength($,q){return q.visibleArguments($).reduce((X,Z)=>{return Math.max(X,this.displayWidth(q.styleArgumentTerm(q.argumentTerm(Z))))},0)}commandUsage($){let q=$._name;if($._aliases[0])q=q+"|"+$._aliases[0];let X="";for(let Z=$.parent;Z;Z=Z.parent)X=Z.name()+" "+X;return X+q+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((X)=>JSON.stringify(X)).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 X=`(${q.join(", ")})`;if($.description)return`${$.description} ${X}`;return X}return $.description}argumentDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((X)=>JSON.stringify(X)).join(", ")}`);if($.defaultValue!==void 0)q.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(q.length>0){let X=`(${q.join(", ")})`;if($.description)return`${$.description} ${X}`;return X}return $.description}formatItemList($,q,X){if(q.length===0)return[];return[X.styleTitle($),...q,""]}groupItems($,q,X){let Z=new Map;return $.forEach((Y)=>{let z=X(Y);if(!Z.has(z))Z.set(z,[])}),q.forEach((Y)=>{let z=X(Y);if(!Z.has(z))Z.set(z,[]);Z.get(z).push(Y)}),Z}formatHelp($,q){let X=q.padWidth($,q),Z=q.helpWidth??80;function Y(G,V){return q.formatItem(G,X,V,q)}let z=[`${q.styleTitle("Usage:")} ${q.styleUsage(q.commandUsage($))}`,""],J=q.commandDescription($);if(J.length>0)z=z.concat([q.boxWrap(q.styleCommandDescription(J),Z),""]);let Q=q.visibleArguments($).map((G)=>{return Y(q.styleArgumentTerm(q.argumentTerm(G)),q.styleArgumentDescription(q.argumentDescription(G)))});if(z=z.concat(this.formatItemList("Arguments:",Q,q)),this.groupItems($.options,q.visibleOptions($),(G)=>G.helpGroupHeading??"Options:").forEach((G,V)=>{let j=G.map((L)=>{return Y(q.styleOptionTerm(q.optionTerm(L)),q.styleOptionDescription(q.optionDescription(L)))});z=z.concat(this.formatItemList(V,j,q))}),q.showGlobalOptions){let G=q.visibleGlobalOptions($).map((V)=>{return Y(q.styleOptionTerm(q.optionTerm(V)),q.styleOptionDescription(q.optionDescription(V)))});z=z.concat(this.formatItemList("Global Options:",G,q))}return this.groupItems($.commands,q.visibleCommands($),(G)=>G.helpGroup()||"Commands:").forEach((G,V)=>{let j=G.map((L)=>{return Y(q.styleSubcommandTerm(q.subcommandTerm(L)),q.styleSubcommandDescription(q.subcommandDescription(L)))});z=z.concat(this.formatItemList(V,j,q))}),z.join(`
3
- `)}displayWidth($){return v0($).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,X,Z){let z=" ".repeat(2);if(!X)return z+$;let J=$.padEnd(q+$.length-Z.displayWidth($)),Q=2,f=(this.helpWidth??80)-q-Q-2,G;if(f<this.minWidthToWrap||Z.preformatted(X))G=X;else G=Z.boxWrap(X,f).replace(/\n/g,`
4
- `+" ".repeat(q+Q));return z+J+" ".repeat(Q)+G.replace(/\n/g,`
5
- ${z}`)}boxWrap($,q){if(q<this.minWidthToWrap)return $;let X=$.split(/\r\n|\n/),Z=/[\s]*[^\s]+/g,Y=[];return X.forEach((z)=>{let J=z.match(Z);if(J===null){Y.push("");return}let Q=[J.shift()],W=this.displayWidth(Q[0]);J.forEach((f)=>{let G=this.displayWidth(f);if(W+G<=q){Q.push(f),W+=G;return}Y.push(Q.join(""));let V=f.trimStart();Q=[V],W=this.displayWidth(V)}),Y.push(Q.join(""))}),Y.join(`
6
- `)}}function v0($){let q=/\x1b\[\d*(;\d*)*m/g;return $.replace(q,"")}o1.Help=u0;o1.stripColor=v0});var a$=w((X2)=>{var{InvalidArgumentError:$2}=q$();class g0{constructor($,q){this.flags=$,this.description=q||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let X=q2($);if(this.short=X.shortFlag,this.long=X.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,X)=>{if(!this.argChoices.includes(q))throw new $2(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(q,X);return q},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return c0(this.name().replace(/^no-/,""));return c0(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class t0{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,X)=>{if(this.positiveOptions.has(X))this.dualOptions.add(X)})}valueFromOption($,q){let X=q.attributeName();if(!this.dualOptions.has(X))return!0;let Z=this.negativeOptions.get(X).presetArg,Y=Z!==void 0?Z:!1;return q.negate===(Y===$)}}function c0($){return $.split("-").reduce((q,X)=>{return q+X[0].toUpperCase()+X.slice(1)})}function q2($){let q,X,Z=/^-[^-]$/,Y=/^--[^-]/,z=$.split(/[ |,]+/).concat("guard");if(Z.test(z[0]))q=z.shift();if(Y.test(z[0]))X=z.shift();if(!q&&Z.test(z[0]))q=z.shift();if(!q&&Y.test(z[0]))q=X,X=z.shift();if(z[0].startsWith("-")){let J=z[0],Q=`option creation failed due to '${J}' in option flags '${$}'`;if(/^-[^-][^-]/.test(J))throw Error(`${Q}
2
+ import{createRequire as _3}from"node:module";var D3=Object.create;var{getPrototypeOf:w3,defineProperty:uq,getOwnPropertyNames:x3}=Object;var H3=Object.prototype.hasOwnProperty;function j3($){return this[$]}var O3,T3,h0=($,q,J)=>{var X=$!=null&&typeof $==="object";if(X){var Z=q?O3??=new WeakMap:T3??=new WeakMap,z=Z.get($);if(z)return z}J=$!=null?D3(w3($)):{};let Q=q||!$||!$.__esModule?uq(J,"default",{value:$,enumerable:!0}):J;for(let Y of x3($))if(!H3.call(Q,Y))uq(Q,Y,{get:j3.bind($,Y),enumerable:!0});if(X)Z.set($,Q);return Q};var I=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);var V$=_3(import.meta.url);var x$=I((f3)=>{class C0 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 gq extends C0{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}f3.CommanderError=C0;f3.InvalidArgumentError=gq});var s$=I((E3)=>{var{InvalidArgumentError:k3}=x$();class cq{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 k3(`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 A3($){let q=$.name()+($.variadic===!0?"...":"");return $.required?"<"+q+">":"["+q+"]"}E3.Argument=cq;E3.humanReadableArgName=A3});var v0=I((v3)=>{var{humanReadableArgName:C3}=s$();class mq{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)=>C3(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(G,V){return q.formatItem(G,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 Y=q.visibleArguments($).map((G)=>{return Z(q.styleArgumentTerm(q.argumentTerm(G)),q.styleArgumentDescription(q.argumentDescription(G)))});if(z=z.concat(this.formatItemList("Arguments:",Y,q)),this.groupItems($.options,q.visibleOptions($),(G)=>G.helpGroupHeading??"Options:").forEach((G,V)=>{let K=G.map((L)=>{return Z(q.styleOptionTerm(q.optionTerm(L)),q.styleOptionDescription(q.optionDescription(L)))});z=z.concat(this.formatItemList(V,K,q))}),q.showGlobalOptions){let G=q.visibleGlobalOptions($).map((V)=>{return Z(q.styleOptionTerm(q.optionTerm(V)),q.styleOptionDescription(q.optionDescription(V)))});z=z.concat(this.formatItemList("Global Options:",G,q))}return this.groupItems($.commands,q.visibleCommands($),(G)=>G.helpGroup()||"Commands:").forEach((G,V)=>{let K=G.map((L)=>{return Z(q.styleSubcommandTerm(q.subcommandTerm(L)),q.styleSubcommandDescription(q.subcommandDescription(L)))});z=z.concat(this.formatItemList(V,K,q))}),z.join(`
3
+ `)}displayWidth($){return dq($).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($)),Y=2,W=(this.helpWidth??80)-q-Y-2,G;if(W<this.minWidthToWrap||X.preformatted(J))G=J;else G=X.boxWrap(J,W).replace(/\n/g,`
4
+ `+" ".repeat(q+Y));return z+Q+" ".repeat(Y)+G.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 Y=[Q.shift()],B=this.displayWidth(Y[0]);Q.forEach((W)=>{let G=this.displayWidth(W);if(B+G<=q){Y.push(W),B+=G;return}Z.push(Y.join(""));let V=W.trimStart();Y=[V],B=this.displayWidth(V)}),Z.push(Y.join(""))}),Z.join(`
6
+ `)}}function dq($){let q=/\x1b\[\d*(;\d*)*m/g;return $.replace(q,"")}v3.Help=mq;v3.stripColor=dq});var u0=I((d3)=>{var{InvalidArgumentError:c3}=x$();class pq{constructor($,q){this.flags=$,this.description=q||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let J=m3($);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 c3(`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 lq(this.name().replace(/^no-/,""));return lq(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class nq{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 lq($){return $.split("-").reduce((q,J)=>{return q+J[0].toUpperCase()+J.slice(1)})}function m3($){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],Y=`option creation failed due to '${Q}' in option flags '${$}'`;if(/^-[^-][^-]/.test(Q))throw Error(`${Y}
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(Z.test(J))throw Error(`${Q}
10
- - too many short flags`);if(Y.test(J))throw Error(`${Q}
11
- - too many long flags`);throw Error(`${Q}
12
- - unrecognised flag format`)}if(q===void 0&&X===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:q,longFlag:X}}X2.Option=g0;X2.DualOptions=t0});var m0=w((Q2)=>{function z2($,q){if(Math.abs($.length-q.length)>3)return Math.max($.length,q.length);let X=[];for(let Z=0;Z<=$.length;Z++)X[Z]=[Z];for(let Z=0;Z<=q.length;Z++)X[0][Z]=Z;for(let Z=1;Z<=q.length;Z++)for(let Y=1;Y<=$.length;Y++){let z=1;if($[Y-1]===q[Z-1])z=0;else z=1;if(X[Y][Z]=Math.min(X[Y-1][Z]+1,X[Y][Z-1]+1,X[Y-1][Z-1]+z),Y>1&&Z>1&&$[Y-1]===q[Z-2]&&$[Y-2]===q[Z-1])X[Y][Z]=Math.min(X[Y][Z],X[Y-2][Z-2]+1)}return X[$.length][q.length]}function J2($,q){if(!q||q.length===0)return"";q=Array.from(new Set(q));let X=$.startsWith("--");if(X)$=$.slice(2),q=q.map((J)=>J.slice(2));let Z=[],Y=3,z=0.4;if(q.forEach((J)=>{if(J.length<=1)return;let Q=z2($,J),W=Math.max($.length,J.length);if((W-Q)/W>z){if(Q<Y)Y=Q,Z=[J];else if(Q===Y)Z.push(J)}}),Z.sort((J,Q)=>J.localeCompare(Q)),X)Z=Z.map((J)=>`--${J}`);if(Z.length>1)return`
13
- (Did you mean one of ${Z.join(", ")}?)`;if(Z.length===1)return`
14
- (Did you mean ${Z[0]}?)`;return""}Q2.suggestSimilar=J2});var s0=w((w2)=>{var G2=a("node:events").EventEmitter,o$=a("node:child_process"),_=a("node:path"),S$=a("node:fs"),M=a("node:process"),{Argument:U2,humanReadableArgName:W2}=w$(),{CommanderError:r$}=q$(),{Help:B2,stripColor:V2}=p$(),{Option:i0,DualOptions:M2}=a$(),{suggestSimilar:n0}=m0();class $0 extends G2{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)=>M.stdout.write(q),writeErr:(q)=>M.stderr.write(q),outputError:(q,X)=>X(q),getOutHelpWidth:()=>M.stdout.isTTY?M.stdout.columns:void 0,getErrHelpWidth:()=>M.stderr.isTTY?M.stderr.columns:void 0,getOutHasColors:()=>e$()??(M.stdout.isTTY&&M.stdout.hasColors?.()),getErrHasColors:()=>e$()??(M.stderr.isTTY&&M.stderr.hasColors?.()),stripColor:(q)=>V2(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,X){let Z=q,Y=X;if(typeof Z==="object"&&Z!==null)Y=Z,Z=null;Y=Y||{};let[,z,J]=$.match(/([^ ]+) *(.*)/),Q=this.createCommand(z);if(Z)Q.description(Z),Q._executableHandler=!0;if(Y.isDefault)this._defaultCommandName=Q._name;if(Q._hidden=!!(Y.noHelp||Y.hidden),Q._executableFile=Y.executableFile||null,J)Q.arguments(J);if(this._registerCommand(Q),Q.parent=this,Q.copyInheritedSettings(this),Z)return this;return Q}createCommand($){return new $0($)}createHelp(){return Object.assign(new B2,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 U2($,q)}argument($,q,X,Z){let Y=this.createArgument($,q);if(typeof X==="function")Y.default(Z).argParser(X);else Y.default(X);return this.addArgument(Y),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 X=$??"help [command]",[,Z,Y]=X.match(/([^ ]+) *(.*)/),z=q??"display help for command",J=this.createCommand(Z);if(J.helpOption(!1),Y)J.arguments(Y);if(z)J.description(z);if(this._addImplicitHelpCommand=!0,this._helpCommand=J,$||q)this._initCommandGroup(J);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 X=["preSubcommand","preAction","postAction"];if(!X.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
16
- Expecting one of '${X.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,X){if(this._exitCallback)this._exitCallback(new r$($,q,X));M.exit($)}action($){let q=(X)=>{let Z=this.registeredArguments.length,Y=X.slice(0,Z);if(this._storeOptionsAsProperties)Y[Z]=this;else Y[Z]=this.opts();return Y.push(this),$.apply(this,Y)};return this._actionHandler=q,this}createOption($,q){return new i0($,q)}_callParseArg($,q,X,Z){try{return $.parseArg(q,X)}catch(Y){if(Y.code==="commander.invalidArgument"){let z=`${Z} ${Y.message}`;this.error(z,{exitCode:Y.exitCode,code:Y.code})}throw Y}}_registerOption($){let q=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(q){let X=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${X}'
17
- - already used by option '${q.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let q=(Z)=>{return[Z.name()].concat(Z.aliases())},X=q($).find((Z)=>this._findCommand(Z));if(X){let Z=q(this._findCommand(X)).join("|"),Y=q($).join("|");throw Error(`cannot add command '${Y}' as already have command '${Z}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let q=$.name(),X=$.attributeName();if($.negate){let Y=$.long.replace(/^--no-/,"--");if(!this._findOption(Y))this.setOptionValueWithSource(X,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(X,$.defaultValue,"default");let Z=(Y,z,J)=>{if(Y==null&&$.presetArg!==void 0)Y=$.presetArg;let Q=this.getOptionValue(X);if(Y!==null&&$.parseArg)Y=this._callParseArg($,Y,Q,z);else if(Y!==null&&$.variadic)Y=$._collectValue(Y,Q);if(Y==null)if($.negate)Y=!1;else if($.isBoolean()||$.optional)Y=!0;else Y="";this.setOptionValueWithSource(X,Y,J)};if(this.on("option:"+q,(Y)=>{let z=`error: option '${$.flags}' argument '${Y}' is invalid.`;Z(Y,z,"cli")}),$.envVar)this.on("optionEnv:"+q,(Y)=>{let z=`error: option '${$.flags}' value '${Y}' from env '${$.envVar}' is invalid.`;Z(Y,z,"env")});return this}_optionEx($,q,X,Z,Y){if(typeof q==="object"&&q instanceof i0)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let z=this.createOption(q,X);if(z.makeOptionMandatory(!!$.mandatory),typeof Z==="function")z.default(Y).argParser(Z);else if(Z instanceof RegExp){let J=Z;Z=(Q,W)=>{let f=J.exec(Q);return f?f[0]:W},z.default(Y).argParser(Z)}else z.default(Z);return this.addOption(z)}option($,q,X,Z){return this._optionEx({},$,q,X,Z)}requiredOption($,q,X,Z){return this._optionEx({mandatory:!0},$,q,X,Z)}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,X){if(this._storeOptionsAsProperties)this[$]=q;else this._optionValues[$]=q;return this._optionValueSources[$]=X,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let q;return this._getCommandAndAncestors().forEach((X)=>{if(X.getOptionValueSource($)!==void 0)q=X.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(M.versions?.electron)q.from="electron";let Z=M.execArgv??[];if(Z.includes("-e")||Z.includes("--eval")||Z.includes("-p")||Z.includes("--print"))q.from="eval"}if($===void 0)$=M.argv;this.rawArgs=$.slice();let X;switch(q.from){case void 0:case"node":this._scriptPath=$[1],X=$.slice(2);break;case"electron":if(M.defaultApp)this._scriptPath=$[1],X=$.slice(2);else X=$.slice(1);break;case"user":X=$.slice(0);break;case"eval":X=$.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",X}parse($,q){this._prepareForParse();let X=this._prepareUserArgs($,q);return this._parseCommand([],X),this}async parseAsync($,q){this._prepareForParse();let X=this._prepareUserArgs($,q);return await this._parseCommand([],X),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,X){if(S$.existsSync($))return;let Z=q?`searched for local subcommand relative to directory '${q}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Y=`'${$}' does not exist
19
- - if '${X}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(X.test(Q))throw Error(`${Y}
10
+ - too many short flags`);if(Z.test(Q))throw Error(`${Y}
11
+ - too many long flags`);throw Error(`${Y}
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}}d3.Option=pq;d3.DualOptions=nq});var sq=I((i3)=>{function n3($,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 s3($,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 Y=n3($,Q),B=Math.max($.length,Q.length);if((B-Y)/B>z){if(Y<Z)Z=Y,X=[Q];else if(Y===Z)X.push(Q)}}),X.sort((Q,Y)=>Q.localeCompare(Y)),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""}i3.suggestSimilar=s3});var aq=I((J6)=>{var o3=V$("node:events").EventEmitter,g0=V$("node:child_process"),p=V$("node:path"),i$=V$("node:fs"),F=V$("node:process"),{Argument:a3,humanReadableArgName:r3}=s$(),{CommanderError:c0}=x$(),{Help:e3,stripColor:$6}=v0(),{Option:iq,DualOptions:q6}=u0(),{suggestSimilar:tq}=sq();class d0 extends o3{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)=>F.stdout.write(q),writeErr:(q)=>F.stderr.write(q),outputError:(q,J)=>J(q),getOutHelpWidth:()=>F.stdout.isTTY?F.stdout.columns:void 0,getErrHelpWidth:()=>F.stderr.isTTY?F.stderr.columns:void 0,getOutHasColors:()=>m0()??(F.stdout.isTTY&&F.stdout.hasColors?.()),getErrHasColors:()=>m0()??(F.stderr.isTTY&&F.stderr.hasColors?.()),stripColor:(q)=>$6(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(/([^ ]+) *(.*)/),Y=this.createCommand(z);if(X)Y.description(X),Y._executableHandler=!0;if(Z.isDefault)this._defaultCommandName=Y._name;if(Y._hidden=!!(Z.noHelp||Z.hidden),Y._executableFile=Z.executableFile||null,Q)Y.arguments(Q);if(this._registerCommand(Y),Y.parent=this,Y.copyInheritedSettings(this),X)return this;return Y}createCommand($){return new d0($)}createHelp(){return Object.assign(new e3,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 a3($,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 c0($,q,J));F.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 iq($,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 Y=this.getOptionValue(J);if(Z!==null&&$.parseArg)Z=this._callParseArg($,Z,Y,z);else if(Z!==null&&$.variadic)Z=$._collectValue(Z,Y);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 iq)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=(Y,B)=>{let W=Q.exec(Y);return W?W[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(F.versions?.electron)q.from="electron";let X=F.execArgv??[];if(X.includes("-e")||X.includes("--eval")||X.includes("-p")||X.includes("--print"))q.from="eval"}if($===void 0)$=F.argv;this.rawArgs=$.slice();let J;switch(q.from){case void 0:case"node":this._scriptPath=$[1],J=$.slice(2);break;case"electron":if(F.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(i$.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
- - ${Z}`;throw Error(Y)}_executeSubCommand($,q){q=q.slice();let X=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function Y(f,G){let V=_.resolve(f,G);if(S$.existsSync(V))return V;if(Z.includes(_.extname(G)))return;let j=Z.find((L)=>S$.existsSync(`${V}${L}`));if(j)return`${V}${j}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=$._executableFile||`${this._name}-${$._name}`,J=this._executableDir||"";if(this._scriptPath){let f;try{f=S$.realpathSync(this._scriptPath)}catch{f=this._scriptPath}J=_.resolve(_.dirname(f),J)}if(J){let f=Y(J,z);if(!f&&!$._executableFile&&this._scriptPath){let G=_.basename(this._scriptPath,_.extname(this._scriptPath));if(G!==this._name)f=Y(J,`${G}-${$._name}`)}z=f||z}X=Z.includes(_.extname(z));let Q;if(M.platform!=="win32")if(X)q.unshift(z),q=d0(M.execArgv).concat(q),Q=o$.spawn(M.argv[0],q,{stdio:"inherit"});else Q=o$.spawn(z,q,{stdio:"inherit"});else this._checkForMissingExecutable(z,J,$._name),q.unshift(z),q=d0(M.execArgv).concat(q),Q=o$.spawn(M.execPath,q,{stdio:"inherit"});if(!Q.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((G)=>{M.on(G,()=>{if(Q.killed===!1&&Q.exitCode===null)Q.kill(G)})});let W=this._exitCallback;Q.on("close",(f)=>{if(f=f??1,!W)M.exit(f);else W(new r$(f,"commander.executeSubCommandAsync","(close)"))}),Q.on("error",(f)=>{if(f.code==="ENOENT")this._checkForMissingExecutable(z,J,$._name);else if(f.code==="EACCES")throw Error(`'${z}' not executable`);if(!W)M.exit(1);else{let G=new r$(1,"commander.executeSubCommandAsync","(error)");G.nestedError=f,W(G)}}),this.runningCommand=Q}_dispatchSubcommand($,q,X){let Z=this._findCommand($);if(!Z)this.help({error:!0});Z._prepareForParse();let Y;return Y=this._chainOrCallSubCommandHook(Y,Z,"preSubcommand"),Y=this._chainOrCall(Y,()=>{if(Z._executableHandler)this._executeSubCommand(Z,q.concat(X));else return Z._parseCommand(q,X)}),Y}_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 $=(X,Z,Y)=>{let z=Z;if(Z!==null&&X.parseArg){let J=`error: command-argument value '${Z}' is invalid for argument '${X.name()}'.`;z=this._callParseArg(X,Z,Y,J)}return z};this._checkNumberOfArguments();let q=[];this.registeredArguments.forEach((X,Z)=>{let Y=X.defaultValue;if(X.variadic){if(Z<this.args.length){if(Y=this.args.slice(Z),X.parseArg)Y=Y.reduce((z,J)=>{return $(X,J,z)},X.defaultValue)}else if(Y===void 0)Y=[]}else if(Z<this.args.length){if(Y=this.args[Z],X.parseArg)Y=$(X,Y,X.defaultValue)}q[Z]=Y}),this.processedArgs=q}_chainOrCall($,q){if($?.then&&typeof $.then==="function")return $.then(()=>q());return q()}_chainOrCallHooks($,q){let X=$,Z=[];if(this._getCommandAndAncestors().reverse().filter((Y)=>Y._lifeCycleHooks[q]!==void 0).forEach((Y)=>{Y._lifeCycleHooks[q].forEach((z)=>{Z.push({hookedCommand:Y,callback:z})})}),q==="postAction")Z.reverse();return Z.forEach((Y)=>{X=this._chainOrCall(X,()=>{return Y.callback(Y.hookedCommand,this)})}),X}_chainOrCallSubCommandHook($,q,X){let Z=$;if(this._lifeCycleHooks[X]!==void 0)this._lifeCycleHooks[X].forEach((Y)=>{Z=this._chainOrCall(Z,()=>{return Y(this,q)})});return Z}_parseCommand($,q){let X=this.parseOptions(q);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(X.operands),q=X.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(X.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Z=()=>{if(X.unknown.length>0)this.unknownOption(X.unknown[0])},Y=`command:${this.name()}`;if(this._actionHandler){Z(),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(Y,$,q)});return z=this._chainOrCallHooks(z,"postAction"),z}if(this.parent?.listenerCount(Y))Z(),this._processArguments(),this.parent.emit(Y,$,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 Z(),this._processArguments()}else if(this.commands.length)Z(),this.help({error:!0});else Z(),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((X)=>{let Z=X.attributeName();if(this.getOptionValue(Z)===void 0)return!1;return this.getOptionValueSource(Z)!=="default"});$.filter((X)=>X.conflictsWith.length>0).forEach((X)=>{let Z=$.find((Y)=>X.conflictsWith.includes(Y.attributeName()));if(Z)this._conflictingOption(X,Z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let q=[],X=[],Z=q;function Y(f){return f.length>1&&f[0]==="-"}let z=(f)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(f))return!1;return!this._getCommandAndAncestors().some((G)=>G.options.map((V)=>V.short).some((V)=>/^-\d$/.test(V)))},J=null,Q=null,W=0;while(W<$.length||Q){let f=Q??$[W++];if(Q=null,f==="--"){if(Z===X)Z.push(f);Z.push(...$.slice(W));break}if(J&&(!Y(f)||z(f))){this.emit(`option:${J.name()}`,f);continue}if(J=null,Y(f)){let G=this._findOption(f);if(G){if(G.required){let V=$[W++];if(V===void 0)this.optionMissingArgument(G);this.emit(`option:${G.name()}`,V)}else if(G.optional){let V=null;if(W<$.length&&(!Y($[W])||z($[W])))V=$[W++];this.emit(`option:${G.name()}`,V)}else this.emit(`option:${G.name()}`);J=G.variadic?G:null;continue}}if(f.length>2&&f[0]==="-"&&f[1]!=="-"){let G=this._findOption(`-${f[1]}`);if(G){if(G.required||G.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${G.name()}`,f.slice(2));else this.emit(`option:${G.name()}`),Q=`-${f.slice(2)}`;continue}}if(/^--[^=]+=/.test(f)){let G=f.indexOf("="),V=this._findOption(f.slice(0,G));if(V&&(V.required||V.optional)){this.emit(`option:${V.name()}`,f.slice(G+1));continue}}if(Z===q&&Y(f)&&!(this.commands.length===0&&z(f)))Z=X;if((this._enablePositionalOptions||this._passThroughOptions)&&q.length===0&&X.length===0){if(this._findCommand(f)){q.push(f),X.push(...$.slice(W));break}else if(this._getHelpCommand()&&f===this._getHelpCommand().name()){q.push(f,...$.slice(W));break}else if(this._defaultCommandName){X.push(f,...$.slice(W));break}}if(this._passThroughOptions){Z.push(f,...$.slice(W));break}Z.push(f)}return{operands:q,unknown:X}}opts(){if(this._storeOptionsAsProperties){let $={},q=this.options.length;for(let X=0;X<q;X++){let Z=this.options[X].attributeName();$[Z]=Z===this._versionOptionName?this._version:this[Z]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,q)=>Object.assign($,q.opts()),{})}error($,q){if(this._outputConfiguration.outputError(`${$}
21
+ - ${X}`;throw Error(Z)}_executeSubCommand($,q){q=q.slice();let J=!1,X=[".js",".ts",".tsx",".mjs",".cjs"];function Z(W,G){let V=p.resolve(W,G);if(i$.existsSync(V))return V;if(X.includes(p.extname(G)))return;let K=X.find((L)=>i$.existsSync(`${V}${L}`));if(K)return`${V}${K}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=$._executableFile||`${this._name}-${$._name}`,Q=this._executableDir||"";if(this._scriptPath){let W;try{W=i$.realpathSync(this._scriptPath)}catch{W=this._scriptPath}Q=p.resolve(p.dirname(W),Q)}if(Q){let W=Z(Q,z);if(!W&&!$._executableFile&&this._scriptPath){let G=p.basename(this._scriptPath,p.extname(this._scriptPath));if(G!==this._name)W=Z(Q,`${G}-${$._name}`)}z=W||z}J=X.includes(p.extname(z));let Y;if(F.platform!=="win32")if(J)q.unshift(z),q=oq(F.execArgv).concat(q),Y=g0.spawn(F.argv[0],q,{stdio:"inherit"});else Y=g0.spawn(z,q,{stdio:"inherit"});else this._checkForMissingExecutable(z,Q,$._name),q.unshift(z),q=oq(F.execArgv).concat(q),Y=g0.spawn(F.execPath,q,{stdio:"inherit"});if(!Y.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((G)=>{F.on(G,()=>{if(Y.killed===!1&&Y.exitCode===null)Y.kill(G)})});let B=this._exitCallback;Y.on("close",(W)=>{if(W=W??1,!B)F.exit(W);else B(new c0(W,"commander.executeSubCommandAsync","(close)"))}),Y.on("error",(W)=>{if(W.code==="ENOENT")this._checkForMissingExecutable(z,Q,$._name);else if(W.code==="EACCES")throw Error(`'${z}' not executable`);if(!B)F.exit(1);else{let G=new c0(1,"commander.executeSubCommandAsync","(error)");G.nestedError=W,B(G)}}),this.runningCommand=Y}_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(W){return W.length>1&&W[0]==="-"}let z=(W)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(W))return!1;return!this._getCommandAndAncestors().some((G)=>G.options.map((V)=>V.short).some((V)=>/^-\d$/.test(V)))},Q=null,Y=null,B=0;while(B<$.length||Y){let W=Y??$[B++];if(Y=null,W==="--"){if(X===J)X.push(W);X.push(...$.slice(B));break}if(Q&&(!Z(W)||z(W))){this.emit(`option:${Q.name()}`,W);continue}if(Q=null,Z(W)){let G=this._findOption(W);if(G){if(G.required){let V=$[B++];if(V===void 0)this.optionMissingArgument(G);this.emit(`option:${G.name()}`,V)}else if(G.optional){let V=null;if(B<$.length&&(!Z($[B])||z($[B])))V=$[B++];this.emit(`option:${G.name()}`,V)}else this.emit(`option:${G.name()}`);Q=G.variadic?G:null;continue}}if(W.length>2&&W[0]==="-"&&W[1]!=="-"){let G=this._findOption(`-${W[1]}`);if(G){if(G.required||G.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${G.name()}`,W.slice(2));else this.emit(`option:${G.name()}`),Y=`-${W.slice(2)}`;continue}}if(/^--[^=]+=/.test(W)){let G=W.indexOf("="),V=this._findOption(W.slice(0,G));if(V&&(V.required||V.optional)){this.emit(`option:${V.name()}`,W.slice(G+1));continue}}if(X===q&&Z(W)&&!(this.commands.length===0&&z(W)))X=J;if((this._enablePositionalOptions||this._passThroughOptions)&&q.length===0&&J.length===0){if(this._findCommand(W)){q.push(W),J.push(...$.slice(B));break}else if(this._getHelpCommand()&&W===this._getHelpCommand().name()){q.push(W,...$.slice(B));break}else if(this._defaultCommandName){J.push(W,...$.slice(B));break}}if(this._passThroughOptions){X.push(W,...$.slice(B));break}X.push(W)}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 X=q||{},Z=X.exitCode||1,Y=X.code||"commander.error";this._exit(Z,Y,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in M.env){let q=$.attributeName();if(this.getOptionValue(q)===void 0||["default","config","env"].includes(this.getOptionValueSource(q)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,M.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new M2(this.options),q=(X)=>{return this.getOptionValue(X)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(X))};this.options.filter((X)=>X.implied!==void 0&&q(X.attributeName())&&$.valueFromOption(this.getOptionValue(X.attributeName()),X)).forEach((X)=>{Object.keys(X.implied).filter((Z)=>!q(Z)).forEach((Z)=>{this.setOptionValueWithSource(Z,X.implied[Z],"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 X=(z)=>{let J=z.attributeName(),Q=this.getOptionValue(J),W=this.options.find((G)=>G.negate&&J===G.attributeName()),f=this.options.find((G)=>!G.negate&&J===G.attributeName());if(W&&(W.presetArg===void 0&&Q===!1||W.presetArg!==void 0&&Q===W.presetArg))return W;return f||z},Z=(z)=>{let J=X(z),Q=J.attributeName();if(this.getOptionValueSource(Q)==="env")return`environment variable '${J.envVar}'`;return`option '${J.flags}'`},Y=`error: ${Z($)} cannot be used with ${Z(q)}`;this.error(Y,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let q="";if($.startsWith("--")&&this._showSuggestionAfterError){let Z=[],Y=this;do{let z=Y.createHelp().visibleOptions(Y).filter((J)=>J.long).map((J)=>J.long);Z=Z.concat(z),Y=Y.parent}while(Y&&!Y._enablePositionalOptions);q=n0($,Z)}let X=`error: unknown option '${$}'${q}`;this.error(X,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let q=this.registeredArguments.length,X=q===1?"":"s",Y=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${q} argument${X} but got ${$.length}.`;this.error(Y,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],q="";if(this._showSuggestionAfterError){let Z=[];this.createHelp().visibleCommands(this).forEach((Y)=>{if(Z.push(Y.name()),Y.alias())Z.push(Y.alias())}),q=n0($,Z)}let X=`error: unknown command '${$}'${q}`;this.error(X,{code:"commander.unknownCommand"})}version($,q,X){if($===void 0)return this._version;this._version=$,q=q||"-V, --version",X=X||"output the version number";let Z=this.createOption(q,X);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.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 X=this.parent?._findCommand($);if(X){let Z=[X.name()].concat(X.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${Z}'`)}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((X)=>{return W2(X)});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=_.basename($,_.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let q=this.createHelp(),X=this._getOutputContext($);q.prepareContext({error:X.error,helpWidth:X.helpWidth,outputHasColors:X.hasColors});let Z=q.formatHelp(this,q);if(X.hasColors)return Z;return this._outputConfiguration.stripColor(Z)}_getOutputContext($){$=$||{};let q=!!$.error,X,Z,Y;if(q)X=(J)=>this._outputConfiguration.writeErr(J),Z=this._outputConfiguration.getErrHasColors(),Y=this._outputConfiguration.getErrHelpWidth();else X=(J)=>this._outputConfiguration.writeOut(J),Z=this._outputConfiguration.getOutHasColors(),Y=this._outputConfiguration.getOutHelpWidth();return{error:q,write:(J)=>{if(!Z)J=this._outputConfiguration.stripColor(J);return X(J)},hasColors:Z,helpWidth:Y}}outputHelp($){let q;if(typeof $==="function")q=$,$=void 0;let X=this._getOutputContext($),Z={error:X.error,write:X.write,command:this};this._getCommandAndAncestors().reverse().forEach((z)=>z.emit("beforeAllHelp",Z)),this.emit("beforeHelp",Z);let Y=this.helpInformation({error:X.error});if(q){if(Y=q(Y),typeof Y!=="string"&&!Buffer.isBuffer(Y))throw Error("outputHelp callback must return a string or a Buffer")}if(X.write(Y),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Z),this._getCommandAndAncestors().forEach((z)=>z.emit("afterAllHelp",Z))}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(M.exitCode??0);if(q===0&&$&&typeof $!=="function"&&$.error)q=1;this._exit(q,"commander.help","(outputHelp)")}addHelpText($,q){let X=["beforeAll","before","after","afterAll"];if(!X.includes($))throw Error(`Unexpected value for position to addHelpText.
26
- Expecting one of '${X.join("', '")}'`);let Z=`${$}Help`;return this.on(Z,(Y)=>{let z;if(typeof q==="function")z=q({error:Y.error,command:Y.command});else z=q;if(z)Y.write(`${z}
27
- `)}),this}_outputHelpIfRequested($){let q=this._getHelpOption();if(q&&$.find((Z)=>q.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function d0($){return $.map((q)=>{if(!q.startsWith("--inspect"))return q;let X,Z="127.0.0.1",Y="9229",z;if((z=q.match(/^(--inspect(-brk)?)$/))!==null)X=z[1];else if((z=q.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(X=z[1],/^\d+$/.test(z[3]))Y=z[3];else Z=z[3];else if((z=q.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)X=z[1],Z=z[3],Y=z[4];if(X&&Y!=="0")return`${X}=${Z}:${parseInt(Y)+1}`;return q})}function e$(){if(M.env.NO_COLOR||M.env.FORCE_COLOR==="0"||M.env.FORCE_COLOR==="false")return!1;if(M.env.FORCE_COLOR||M.env.CLICOLOR_FORCE!==void 0)return!0;return}w2.Command=$0;w2.useColor=e$});var o0=w((P2)=>{var{Argument:l0}=w$(),{Command:q0}=s0(),{CommanderError:F2,InvalidArgumentError:p0}=q$(),{Help:N2}=p$(),{Option:a0}=a$();P2.program=new q0;P2.createCommand=($)=>new q0($);P2.createOption=($,q)=>new a0($,q);P2.createArgument=($,q)=>new l0($,q);P2.Command=q0;P2.Option=a0;P2.Argument=l0;P2.Help=N2;P2.CommanderError=F2;P2.InvalidArgumentError=p0;P2.InvalidOptionArgumentError=p0});var Zq=w((Q3,Xq)=>{class g extends Error{constructor($,q,X){super("[ParserError] "+$,q,X);if(this.name="ParserError",this.code="ParserError",Error.captureStackTrace)Error.captureStackTrace(this,g)}}class J0{constructor($){this.parser=$,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}}class N${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 J0(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 g("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 J0($)}callNow($,q){return this.call($,q),this.runOne()}return($){if(this.stack.length===0)throw this.error(new g("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 g("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 g("Must declare a parseStart method")}}N$.END=1114112;N$.Error=g;Xq.exports=N$});var zq=w((f3,Yq)=>{Yq.exports=($)=>{let q=new Date($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var P$=w((G3,Jq)=>{Jq.exports=($,q)=>{q=String(q);while(q.length<$)q="0"+q;return q}});var Gq=w((U3,fq)=>{var r=P$();class Qq extends Date{constructor($){super($+"Z");this.isFloating=!0}toISOString(){let $=`${this.getUTCFullYear()}-${r(2,this.getUTCMonth()+1)}-${r(2,this.getUTCDate())}`,q=`${r(2,this.getUTCHours())}:${r(2,this.getUTCMinutes())}:${r(2,this.getUTCSeconds())}.${r(3,this.getUTCMilliseconds())}`;return`${$}T${q}`}}fq.exports=($)=>{let q=new Qq($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var Vq=w((W3,Bq)=>{var Uq=P$(),T2=global.Date;class Wq extends T2{constructor($){super($);this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${Uq(2,this.getUTCMonth()+1)}-${Uq(2,this.getUTCDate())}`}}Bq.exports=($)=>{let q=new Wq($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var Sq=w((B3,wq)=>{var D$=P$();class Mq extends Date{constructor($){super(`0000-01-01T${$}Z`);this.isTime=!0}toISOString(){return`${D$(2,this.getUTCHours())}:${D$(2,this.getUTCMinutes())}:${D$(2,this.getUTCSeconds())}.${D$(3,this.getUTCMilliseconds())}`}}wq.exports=($)=>{let q=new Mq($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var O$=w((Cq,U$)=>{U$.exports=bq(Zq());U$.exports.makeParserClass=bq;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};U$.exports.TomlError=U;var Q0=zq(),Kq=Gq(),Fq=Vq(),Nq=Sq(),S=9,N=10,D=13,I$=31,F=32,E=34,t=35,R=39,L$=43,Pq=44,T=45,H=46,v=48,A2=49,b2=55,k$=57,m=58,C2=61,w0=65,Z$=69,u2=70,v2=84,c2=85,j$=90,O=95,G$=97,hq=98,i=101,f$=102,Dq=105,g2=108,J$=110,t2=111,_q=114,m2=115,V0=116,Iq=117,i2=120,yq=122,n2=123,Lq=125,f0=91,M0=92,Y$=93,x$=127,d2=55296,s2=57343,xq={[hq]:"\b",[V0]:"\t",[J$]:`
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 Z=q.split(/\n/),Y=String(Math.min(Z.length,$.line+3)).length,z=" ";while(z.length<Y)z+=" ";for(let J=Math.max(0,$.line-1);J<Math.min(Z.length,$.line+2);++J){let Q=String(J+1);if(Q.length<Y)Q=" "+Q;if($.line===J){X+=Q+"> "+Z[J]+`
30
- `,X+=z+" ";for(let W=0;W<$.col;++W)X+=" ";X+=`^
31
- `}else X+=Q+": "+Z[J]+`
32
- `}}return $.message=X+`
33
- `,$}});var cq=w((M3,vq)=>{vq.exports=J8;var Y8=O$(),z8=E$();function J8($){if(global.Buffer&&global.Buffer.isBuffer($))$=$.toString("utf8");let q=new Y8;try{return q.parse($),q.finish()}catch(X){throw z8(X,$)}}});var mq=w((w3,tq)=>{tq.exports=f8;var Q8=O$(),gq=E$();function f8($,q){if(!q)q={};let X=0,Z=q.blocksize||40960,Y=new Q8;return new Promise((J,Q)=>{setImmediate(z,X,Z,J,Q)});function z(J,Q,W,f){if(J>=$.length)try{return W(Y.finish())}catch(G){return f(gq(G,$))}try{Y.parse($.slice(J,J+Q)),setImmediate(z,J+Q,Q,W,f)}catch(G){f(gq(G,$))}}}});var dq=w((S3,nq)=>{nq.exports=U8;var G8=a("stream"),iq=O$();function U8($){if($)return W8($);else return B8($)}function W8($){let q=new iq;return $.setEncoding("utf8"),new Promise((X,Z)=>{let Y,z=!1,J=!1;function Q(){if(z=!0,Y)return;try{X(q.finish())}catch(G){Z(G)}}function W(G){J=!0,Z(G)}$.once("end",Q),$.once("error",W),f();function f(){Y=!0;let G;while((G=$.read())!==null)try{q.parse(G)}catch(V){return W(V)}if(Y=!1,z)return Q();if(J)return;$.once("readable",f)}})}function B8(){let $=new iq;return new G8.Transform({objectMode:!0,transform(q,X,Z){try{$.parse(q.toString(X))}catch(Y){this.emit("error",Y)}Z()},flush(q){try{this.push($.finish())}catch(X){this.emit("error",X)}q()}})}});var sq=w((K3,W$)=>{W$.exports=cq();W$.exports.async=mq();W$.exports.stream=dq();W$.exports.prettyError=E$()});var q1=w((F3,x0)=>{x0.exports=V8;x0.exports.value=L0;function V8($){if($===null)throw s("null");if($===void 0)throw s("undefined");if(typeof $!=="object")throw s(typeof $);if(typeof $.toJSON==="function")$=$.toJSON();if($==null)return null;let q=I($);if(q!=="table")throw s(q);return I0("","",$)}function s($){return Error("Can only stringify objects, not "+$)}function M8(){return Error("Array values can't have mixed types")}function lq($){return Object.keys($).filter((q)=>pq($[q]))}function w8($){return Object.keys($).filter((q)=>!pq($[q]))}function h$($){let q=Array.isArray($)?[]:Object.prototype.hasOwnProperty.call($,"__proto__")?{["__proto__"]:void 0}:{};for(let X of Object.keys($))if($[X]&&typeof $[X].toJSON==="function"&&!("toISOString"in $[X]))q[X]=$[X].toJSON();else q[X]=$[X];return q}function I0($,q,X){X=h$(X);var Z,Y;Z=lq(X),Y=w8(X);var z=[],J=q||"";if(Z.forEach((W)=>{var f=I(X[W]);if(f!=="undefined"&&f!=="null")z.push(J+_$(W)+" = "+rq(X[W],!0))}),z.length>0)z.push("");var Q=$&&Z.length>0?q+" ":"";return Y.forEach((W)=>{z.push(k8($,Q,W,X[W]))}),z.join(`
34
- `)}function pq($){switch(I($)){case"undefined":case"null":case"integer":case"nan":case"float":case"boolean":case"string":case"datetime":return!0;case"array":return $.length===0||I($[0])!=="table";case"table":return Object.keys($).length===0;default:return!1}}function I($){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 _$($){var q=String($);if(/^[-A-Za-z0-9_]+$/.test(q))return q;else return aq(q)}function aq($){return'"'+oq($).replace(/"/g,"\\\"")+'"'}function S8($){return"'"+$+"'"}function K8($,q){while(q.length<$)q="0"+q;return q}function oq($){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"+K8(4,q.codePointAt(0).toString(16)))}function F8($){let q=$.split(/\n/).map((X)=>{return oq(X).replace(/"(?="")/g,"\\\"")}).join(`
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 F.env){let q=$.attributeName();if(this.getOptionValue(q)===void 0||["default","config","env"].includes(this.getOptionValueSource(q)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,F.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new q6(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(),Y=this.getOptionValue(Q),B=this.options.find((G)=>G.negate&&Q===G.attributeName()),W=this.options.find((G)=>!G.negate&&Q===G.attributeName());if(B&&(B.presetArg===void 0&&Y===!1||B.presetArg!==void 0&&Y===B.presetArg))return B;return W||z},X=(z)=>{let Q=J(z),Y=Q.attributeName();if(this.getOptionValueSource(Y)==="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=tq($,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=tq($,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 r3(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=p.basename($,p.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(F.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 oq($){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 m0(){if(F.env.NO_COLOR||F.env.FORCE_COLOR==="0"||F.env.FORCE_COLOR==="false")return!1;if(F.env.FORCE_COLOR||F.env.CLICOLOR_FORCE!==void 0)return!0;return}J6.Command=d0;J6.useColor=m0});var q2=I((Y6)=>{var{Argument:rq}=s$(),{Command:l0}=aq(),{CommanderError:z6,InvalidArgumentError:eq}=x$(),{Help:Q6}=v0(),{Option:$2}=u0();Y6.program=new l0;Y6.createCommand=($)=>new l0($);Y6.createOption=($,q)=>new $2($,q);Y6.createArgument=($,q)=>new rq($,q);Y6.Command=l0;Y6.Option=$2;Y6.Argument=rq;Y6.Help=Q6;Y6.CommanderError=z6;Y6.InvalidArgumentError=eq;Y6.InvalidOptionArgumentError=eq});var K2=I((CJ,U2)=>{class J$ extends Error{constructor($,q,J){super("[ParserError] "+$,q,J);if(this.name="ParserError",this.code="ParserError",Error.captureStackTrace)Error.captureStackTrace(this,J$)}}class o0{constructor($){this.parser=$,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}}class e${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 o0(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 J$("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 o0($)}callNow($,q){return this.call($,q),this.runOne()}return($){if(this.stack.length===0)throw this.error(new J$("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 J$("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 J$("Must declare a parseStart method")}}e$.END=1114112;e$.Error=J$;U2.exports=e$});var N2=I((vJ,F2)=>{F2.exports=($)=>{let q=new Date($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var $0=I((uJ,I2)=>{I2.exports=($,q)=>{q=String(q);while(q.length<$)q="0"+q;return q}});var L2=I((gJ,S2)=>{var I$=$0();class P2 extends Date{constructor($){super($+"Z");this.isFloating=!0}toISOString(){let $=`${this.getUTCFullYear()}-${I$(2,this.getUTCMonth()+1)}-${I$(2,this.getUTCDate())}`,q=`${I$(2,this.getUTCHours())}:${I$(2,this.getUTCMinutes())}:${I$(2,this.getUTCSeconds())}.${I$(3,this.getUTCMilliseconds())}`;return`${$}T${q}`}}S2.exports=($)=>{let q=new P2($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var H2=I((cJ,x2)=>{var D2=$0(),v6=global.Date;class w2 extends v6{constructor($){super($);this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${D2(2,this.getUTCMonth()+1)}-${D2(2,this.getUTCDate())}`}}x2.exports=($)=>{let q=new w2($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var T2=I((mJ,O2)=>{var q0=$0();class j2 extends Date{constructor($){super(`0000-01-01T${$}Z`);this.isTime=!0}toISOString(){return`${q0(2,this.getUTCHours())}:${q0(2,this.getUTCMinutes())}:${q0(2,this.getUTCSeconds())}.${q0(3,this.getUTCMilliseconds())}`}}O2.exports=($)=>{let q=new j2($);if(isNaN(q))throw TypeError("Invalid Datetime");else return q}});var G0=I((i2,h$)=>{h$.exports=s2(K2());h$.exports.makeParserClass=s2;class M extends Error{constructor($){super($);if(this.name="TomlError",Error.captureStackTrace)Error.captureStackTrace(this,M);this.fromTOML=!0,this.wrapped=null}}M.wrap=($)=>{let q=new M($.message);return q.code=$.code,q.wrapped=$,q};h$.exports.TomlError=M;var a0=N2(),_2=L2(),f2=H2(),R2=T2(),P=9,f=10,k=13,J0=31,x=32,m=34,X$=35,n=39,X0=43,y2=44,s=45,g=46,r=48,u6=49,g6=55,Q0=57,Z$=58,c6=61,zq=65,f$=69,m6=70,d6=84,l6=85,z0=90,c=95,b$=97,c2=98,z$=101,E$=102,k2=105,p6=108,k$=110,n6=111,m2=114,s6=115,Xq=116,A2=117,i6=120,d2=122,t6=123,E2=125,r0=91,Zq=92,R$=93,Z0=127,o6=55296,a6=57343,b2={[c2]:"\b",[Xq]:"\t",[k$]:`
28
+ `,[E$]:"\f",[m2]:"\r",[m]:'"',[Zq]:"\\"};function D($){return $>=r&&$<=Q0}function e0($){return $>=zq&&$<=m6||$>=b$&&$<=E$||$>=r&&$<=Q0}function r6($){return $===u6||$===r}function e6($){return $>=r&&$<=g6}function $8($){return $>=zq&&$<=z0||$>=b$&&$<=d2||$>=r&&$<=Q0||$===n||$===m||$===c||$===s}function q8($){return $>=zq&&$<=z0||$>=b$&&$<=d2||$>=r&&$<=Q0||$===c||$===s}var R=Symbol("type"),A$=Symbol("declared"),J8=Object.prototype.hasOwnProperty,X8=Object.defineProperty,Z8={configurable:!0,enumerable:!0,writable:!0,value:void 0};function a($,q){if(J8.call($,q))return!0;if(q==="__proto__")X8($,"__proto__",Z8);return!1}var Qq=Symbol("inline-table");function h2(){return Object.defineProperties({},{[R]:{value:Qq}})}function z8($){if($===null||typeof $!=="object")return!1;return $[R]===Qq}var Yq=Symbol("table");function Q$(){return Object.defineProperties({},{[R]:{value:Yq},[A$]:{value:!1,writable:!0}})}function y$($){if($===null||typeof $!=="object")return!1;return $[R]===Yq}var l2=Symbol("content-type"),Gq=Symbol("inline-list");function C2($){return Object.defineProperties([],{[R]:{value:Gq},[l2]:{value:$}})}function v2($){if($===null||typeof $!=="object")return!1;return $[R]===Gq}var Wq=Symbol("list");function Q8(){return Object.defineProperties([],{[R]:{value:Wq}})}function $q($){if($===null||typeof $!=="object")return!1;return $[R]===Wq}var p2;try{let utilInspect=eval("require('util').inspect");p2=utilInspect.custom}catch($){}var Bq=p2||"inspect";class n2{constructor($){try{this.value=global.BigInt.asIntN(64,$)}catch(q){this.value=null}Object.defineProperty(this,R,{value:Y0})}isNaN(){return this.value===null}toString(){return String(this.value)}[Bq](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}}var Y0=Symbol("integer");function Y$($){let q=Number($);if(Object.is(q,-0))q=0;if(global.BigInt&&!Number.isSafeInteger(q))return new n2($);else return Object.defineProperties(new Number(q),{isNaN:{value:function(){return isNaN(this)}},[R]:{value:Y0},[Bq]:{value:()=>`[Integer: ${$}]`}})}function qq($){if($===null||typeof $!=="object")return!1;return $[R]===Y0}var Vq=Symbol("float");function u2($){return Object.defineProperties(new Number($),{[R]:{value:Vq},[Bq]:{value:()=>`[Float: ${$}]`}})}function Jq($){if($===null||typeof $!=="object")return!1;return $[R]===Vq}function g2($){let q=typeof $;if(q==="object"){if($===null)return"null";if($ instanceof Date)return"datetime";if(R in $)switch($[R]){case Qq:return"inline-table";case Gq:return"inline-list";case Yq:return"table";case Wq:return"list";case Vq:return"float";case Y0:return"integer"}}return q}function s2($){class q extends ${constructor(){super();this.ctx=this.obj=Q$()}atEndOfWord(){return this.char===X$||this.char===P||this.char===x||this.atEndOfLine()}atEndOfLine(){return this.char===$.END||this.char===f||this.char===k}parseStart(){if(this.char===$.END)return null;else if(this.char===r0)return this.call(this.parseTableOrList);else if(this.char===X$)return this.call(this.parseComment);else if(this.char===f||this.char===x||this.char===P||this.char===k)return null;else if($8(this.char))return this.callNow(this.parseAssignStatement);else throw this.error(new M(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===x||this.char===P||this.char===k)return null;else if(this.char===X$)return this.goto(this.parseComment);else if(this.char===$.END||this.char===f)return this.return();else throw this.error(new M("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(a(X,z)&&(!y$(X[z])||X[z][A$]))throw this.error(new M("Can't redefine existing key"));X=X[z]=X[z]||Q$()}if(a(X,Z))throw this.error(new M("Can't redefine existing key"));if(qq(J.value)||Jq(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===g)return this.next(this.parseAssignKeywordPostDot);else if(this.char!==x&&this.char!==P)return this.goto(this.parseAssignEqual)}parseAssignKeywordPostDot(){if(this.char!==x&&this.char!==P)return this.callNow(this.parseKeyword,this.recordAssignKeyword)}parseAssignEqual(){if(this.char===c6)return this.next(this.parseAssignPreValue);else throw this.error(new M('Invalid character, expected "="'))}parseAssignPreValue(){if(this.char===x||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===f)return this.return();while(this.nextChar())}parseTableOrList(){if(this.char===r0)this.next(this.parseList);else return this.goto(this.parseTable)}parseTable(){return this.ctx=this.obj,this.goto(this.parseTableNext)}parseTableNext(){if(this.char===x||this.char===P)return null;else return this.callNow(this.parseKeyword,this.parseTableMore)}parseTableMore(J){if(this.char===x||this.char===P)return null;else if(this.char===R$){if(a(this.ctx,J)&&(!y$(this.ctx[J])||this.ctx[J][A$]))throw this.error(new M("Can't redefine existing key"));else this.ctx=this.ctx[J]=this.ctx[J]||Q$(),this.ctx[A$]=!0;return this.next(this.parseWhitespaceToEOL)}else if(this.char===g){if(!a(this.ctx,J))this.ctx=this.ctx[J]=Q$();else if(y$(this.ctx[J]))this.ctx=this.ctx[J];else if($q(this.ctx[J]))this.ctx=this.ctx[J][this.ctx[J].length-1];else throw this.error(new M("Can't redefine existing key"));return this.next(this.parseTableNext)}else throw this.error(new M("Unexpected character, expected whitespace, . or ]"))}parseList(){return this.ctx=this.obj,this.goto(this.parseListNext)}parseListNext(){if(this.char===x||this.char===P)return null;else return this.callNow(this.parseKeyword,this.parseListMore)}parseListMore(J){if(this.char===x||this.char===P)return null;else if(this.char===R$){if(!a(this.ctx,J))this.ctx[J]=Q8();if(v2(this.ctx[J]))throw this.error(new M("Can't extend an inline array"));else if($q(this.ctx[J])){let X=Q$();this.ctx[J].push(X),this.ctx=X}else throw this.error(new M("Can't redefine an existing key"));return this.next(this.parseListEnd)}else if(this.char===g){if(!a(this.ctx,J))this.ctx=this.ctx[J]=Q$();else if(v2(this.ctx[J]))throw this.error(new M("Can't extend an inline array"));else if(z8(this.ctx[J]))throw this.error(new M("Can't extend an inline table"));else if($q(this.ctx[J]))this.ctx=this.ctx[J][this.ctx[J].length-1];else if(y$(this.ctx[J]))this.ctx=this.ctx[J];else throw this.error(new M("Can't redefine an existing key"));return this.next(this.parseListNext)}else throw this.error(new M("Unexpected character, expected whitespace, . or ]"))}parseListEnd(J){if(this.char===R$)return this.next(this.parseWhitespaceToEOL);else throw this.error(new M("Unexpected character, expected whitespace, . or ]"))}parseValue(){if(this.char===$.END)throw this.error(new M("Key without value"));else if(this.char===m)return this.next(this.parseDoubleString);if(this.char===n)return this.next(this.parseSingleString);else if(this.char===s||this.char===X0)return this.goto(this.parseNumberSign);else if(this.char===k2)return this.next(this.parseInf);else if(this.char===k$)return this.next(this.parseNan);else if(D(this.char))return this.goto(this.parseNumberOrDateTime);else if(this.char===Xq||this.char===E$)return this.goto(this.parseBoolean);else if(this.char===r0)return this.call(this.parseInlineList,this.recordValue);else if(this.char===t6)return this.call(this.parseInlineTable,this.recordValue);else throw this.error(new M("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"))}recordValue(J){return this.returnNow(J)}parseInf(){if(this.char===k$)return this.next(this.parseInf2);else throw this.error(new M('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseInf2(){if(this.char===E$)if(this.state.buf==="-")return this.return(-1/0);else return this.return(1/0);else throw this.error(new M('Unexpected character, expected "inf", "+inf" or "-inf"'))}parseNan(){if(this.char===b$)return this.next(this.parseNan2);else throw this.error(new M('Unexpected character, expected "nan"'))}parseNan2(){if(this.char===k$)return this.return(NaN);else throw this.error(new M('Unexpected character, expected "nan"'))}parseKeyword(){if(this.char===m)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 M("Key ended without value"));else if(q8(this.char))this.consume();else if(this.state.buf.length===0)throw this.error(new M("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 M("Unterminated string"));else if(this.char===Z0||this.char<=J0&&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===k)return null;else if(this.char===f)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 M("Unterminated multi-line string"));else if(this.char===Z0||this.char<=J0&&this.char!==P&&this.char!==f&&this.char!==k)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===m)return this.next(this.parseMultiStringMaybe);else return this.goto(this.parseBasicString)}parseBasicString(){do if(this.char===Zq)return this.call(this.parseEscape,this.recordEscapeReplacement);else if(this.char===m)return this.return();else if(this.atEndOfLine())throw this.error(new M("Unterminated string"));else if(this.char===Z0||this.char<=J0&&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===m)return this.next(this.parseMultiString);else return this.returnNow()}parseMultiString(){if(this.char===k)return null;else if(this.char===f)return this.next(this.parseMultiStringContent);else return this.goto(this.parseMultiStringContent)}parseMultiStringContent(){do if(this.char===Zq)return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement);else if(this.char===m)return this.next(this.parseMultiEnd);else if(this.char===$.END)throw this.error(new M("Unterminated multi-line string"));else if(this.char===Z0||this.char<=J0&&this.char!==P&&this.char!==f&&this.char!==k)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 M(`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===m)return this.next(this.parseMultiEnd2);else return this.state.buf+='"',this.goto(this.parseMultiStringContent)}parseMultiEnd2(){if(this.char===m)return this.return();else return this.state.buf+='""',this.goto(this.parseMultiStringContent)}parseMultiEscape(){if(this.char===k||this.char===f)return this.next(this.parseMultiTrim);else if(this.char===x||this.char===P)return this.next(this.parsePreMultiTrim);else return this.goto(this.parseEscape)}parsePreMultiTrim(){if(this.char===x||this.char===P)return null;else if(this.char===k||this.char===f)return this.next(this.parseMultiTrim);else throw this.error(new M("Can't escape whitespace"))}parseMultiTrim(){if(this.char===f||this.char===x||this.char===P||this.char===k)return null;else return this.returnNow()}parseEscape(){if(this.char in b2)return this.return(b2[this.char]);else if(this.char===A2)return this.call(this.parseSmallUnicode,this.parseUnicodeReturn);else if(this.char===l6)return this.call(this.parseLargeUnicode,this.parseUnicodeReturn);else throw this.error(new M("Unknown escape character: "+this.char))}parseUnicodeReturn(J){try{let X=parseInt(J,16);if(X>=o6&&X<=a6)throw this.error(new M("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));return this.returnNow(String.fromCodePoint(X))}catch(X){throw this.error(M.wrap(X))}}parseSmallUnicode(){if(!e0(this.char))throw this.error(new M("Invalid character in unicode sequence, expected hex"));else if(this.consume(),this.state.buf.length>=4)return this.return()}parseLargeUnicode(){if(!e0(this.char))throw this.error(new M("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===k2)return this.next(this.parseInf);else if(this.char===k$)return this.next(this.parseNan);else return this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}parseNumberIntegerStart(){if(this.char===r)return this.consume(),this.next(this.parseNumberIntegerExponentOrDecimal);else return this.goto(this.parseNumberInteger)}parseNumberIntegerExponentOrDecimal(){if(this.char===g)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===f$||this.char===z$)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(Y$(this.state.buf))}parseNumberInteger(){if(D(this.char))this.consume();else if(this.char===c)return this.call(this.parseNoUnder);else if(this.char===f$||this.char===z$)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===g)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else{let J=Y$(this.state.buf);if(J.isNaN())throw this.error(new M("Invalid number"));else return this.returnNow(J)}}parseNoUnder(){if(this.char===c||this.char===g||this.char===f$||this.char===z$)throw this.error(new M("Unexpected character, expected digit"));else if(this.atEndOfWord())throw this.error(new M("Incomplete number"));return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===c||this.char===g)throw this.error(new M("Unexpected character, expected digit"));else if(this.atEndOfWord())throw this.error(new M("Incomplete number"));return this.returnNow()}parseNumberFloat(){if(this.char===c)return this.call(this.parseNoUnder,this.parseNumberFloat);else if(D(this.char))this.consume();else if(this.char===f$||this.char===z$)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(u2(this.state.buf))}parseNumberExponentSign(){if(D(this.char))return this.goto(this.parseNumberExponent);else if(this.char===s||this.char===X0)this.consume(),this.call(this.parseNoUnder,this.parseNumberExponent);else throw this.error(new M("Unexpected character, expected -, + or digit"))}parseNumberExponent(){if(D(this.char))this.consume();else if(this.char===c)return this.call(this.parseNoUnder);else return this.returnNow(u2(this.state.buf))}parseNumberOrDateTime(){if(this.char===r)return this.consume(),this.next(this.parseNumberBaseOrDateTime);else return this.goto(this.parseNumberOrDateTimeOnly)}parseNumberOrDateTimeOnly(){if(this.char===c)return this.call(this.parseNoUnder,this.parseNumberInteger);else if(D(this.char)){if(this.consume(),this.state.buf.length>4)this.next(this.parseNumberInteger)}else if(this.char===f$||this.char===z$)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===g)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===s)return this.goto(this.parseDateTime);else if(this.char===Z$)return this.goto(this.parseOnlyTimeHour);else return this.returnNow(Y$(this.state.buf))}parseDateTimeOnly(){if(this.state.buf.length<4)if(D(this.char))return this.consume();else if(this.char===Z$)return this.goto(this.parseOnlyTimeHour);else throw this.error(new M("Expected digit while parsing year part of a date"));else if(this.char===s)return this.goto(this.parseDateTime);else throw this.error(new M("Expected hyphen (-) while parsing year part of date"))}parseNumberBaseOrDateTime(){if(this.char===c2)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin);else if(this.char===n6)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct);else if(this.char===i6)return this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex);else if(this.char===g)return this.goto(this.parseNumberInteger);else if(D(this.char))return this.goto(this.parseDateTimeOnly);else return this.returnNow(Y$(this.state.buf))}parseIntegerHex(){if(e0(this.char))this.consume();else if(this.char===c)return this.call(this.parseNoUnderHexOctBinLiteral);else{let J=Y$(this.state.buf);if(J.isNaN())throw this.error(new M("Invalid number"));else return this.returnNow(J)}}parseIntegerOct(){if(e6(this.char))this.consume();else if(this.char===c)return this.call(this.parseNoUnderHexOctBinLiteral);else{let J=Y$(this.state.buf);if(J.isNaN())throw this.error(new M("Invalid number"));else return this.returnNow(J)}}parseIntegerBin(){if(r6(this.char))this.consume();else if(this.char===c)return this.call(this.parseNoUnderHexOctBinLiteral);else{let J=Y$(this.state.buf);if(J.isNaN())throw this.error(new M("Invalid number"));else return this.returnNow(J)}}parseDateTime(){if(this.state.buf.length<4)throw this.error(new M("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===s){if(this.state.buf.length<2)throw this.error(new M("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(D(this.char))this.consume();else throw this.error(new M("Incomplete datetime"))}parseDateDay(){if(this.char===d6||this.char===x){if(this.state.buf.length<2)throw this.error(new M("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(f2(this.state.result+"-"+this.state.buf));else if(D(this.char))this.consume();else throw this.error(new M("Incomplete datetime"))}parseStartTimeHour(){if(this.atEndOfWord())return this.returnNow(f2(this.state.result));else return this.goto(this.parseTimeHour)}parseTimeHour(){if(this.char===Z$){if(this.state.buf.length<2)throw this.error(new M("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(D(this.char))this.consume();else throw this.error(new M("Incomplete datetime"))}parseTimeMin(){if(this.state.buf.length<2&&D(this.char))this.consume();else if(this.state.buf.length===2&&this.char===Z$)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseTimeSec);else throw this.error(new M("Incomplete datetime"))}parseTimeSec(){if(D(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 M("Incomplete datetime"))}parseOnlyTimeHour(){if(this.char===Z$){if(this.state.buf.length<2)throw this.error(new M("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 M("Incomplete time"))}parseOnlyTimeMin(){if(this.state.buf.length<2&&D(this.char))this.consume();else if(this.state.buf.length===2&&this.char===Z$)return this.state.result+=":"+this.state.buf,this.state.buf="",this.next(this.parseOnlyTimeSec);else throw this.error(new M("Incomplete time"))}parseOnlyTimeSec(){if(D(this.char)){if(this.consume(),this.state.buf.length===2)return this.next(this.parseOnlyTimeFractionMaybe)}else throw this.error(new M("Incomplete time"))}parseOnlyTimeFractionMaybe(){if(this.state.result+=":"+this.state.buf,this.char===g)this.state.buf="",this.next(this.parseOnlyTimeFraction);else return this.return(R2(this.state.result))}parseOnlyTimeFraction(){if(D(this.char))this.consume();else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new M("Expected digit in milliseconds"));return this.returnNow(R2(this.state.result+"."+this.state.buf))}else throw this.error(new M("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneOrFraction(){if(this.char===g)this.consume(),this.next(this.parseDateTimeFraction);else if(this.char===s||this.char===X0)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===z0)return this.consume(),this.return(a0(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(_2(this.state.result+this.state.buf));else throw this.error(new M("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseDateTimeFraction(){if(D(this.char))this.consume();else if(this.state.buf.length===1)throw this.error(new M("Expected digit in milliseconds"));else if(this.char===s||this.char===X0)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===z0)return this.consume(),this.return(a0(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(_2(this.state.result+this.state.buf));else throw this.error(new M("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"))}parseTimeZoneHour(){if(D(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else throw this.error(new M("Unexpected character in datetime, expected digit"))}parseTimeZoneSep(){if(this.char===Z$)this.consume(),this.next(this.parseTimeZoneMin);else throw this.error(new M("Unexpected character in datetime, expected colon"))}parseTimeZoneMin(){if(D(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.return(a0(this.state.result+this.state.buf))}else throw this.error(new M("Unexpected character in datetime, expected digit"))}parseBoolean(){if(this.char===Xq)return this.consume(),this.next(this.parseTrue_r);else if(this.char===E$)return this.consume(),this.next(this.parseFalse_a)}parseTrue_r(){if(this.char===m2)return this.consume(),this.next(this.parseTrue_u);else throw this.error(new M("Invalid boolean, expected true or false"))}parseTrue_u(){if(this.char===A2)return this.consume(),this.next(this.parseTrue_e);else throw this.error(new M("Invalid boolean, expected true or false"))}parseTrue_e(){if(this.char===z$)return this.return(!0);else throw this.error(new M("Invalid boolean, expected true or false"))}parseFalse_a(){if(this.char===b$)return this.consume(),this.next(this.parseFalse_l);else throw this.error(new M("Invalid boolean, expected true or false"))}parseFalse_l(){if(this.char===p6)return this.consume(),this.next(this.parseFalse_s);else throw this.error(new M("Invalid boolean, expected true or false"))}parseFalse_s(){if(this.char===s6)return this.consume(),this.next(this.parseFalse_e);else throw this.error(new M("Invalid boolean, expected true or false"))}parseFalse_e(){if(this.char===z$)return this.return(!1);else throw this.error(new M("Invalid boolean, expected true or false"))}parseInlineList(){if(this.char===x||this.char===P||this.char===k||this.char===f)return null;else if(this.char===$.END)throw this.error(new M("Unterminated inline array"));else if(this.char===X$)return this.call(this.parseComment);else if(this.char===R$)return this.return(this.state.resultArr||C2());else return this.callNow(this.parseValue,this.recordInlineListValue)}recordInlineListValue(J){if(this.state.resultArr){let X=this.state.resultArr[l2],Z=g2(J);if(X!==Z)throw this.error(new M(`Inline lists must be a single type, not a mix of ${X} and ${Z}`))}else this.state.resultArr=C2(g2(J));if(Jq(J)||qq(J))this.state.resultArr.push(J.valueOf());else this.state.resultArr.push(J);return this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===x||this.char===P||this.char===k||this.char===f)return null;else if(this.char===X$)return this.call(this.parseComment);else if(this.char===y2)return this.next(this.parseInlineList);else if(this.char===R$)return this.goto(this.parseInlineList);else throw this.error(new M("Invalid character, expected whitespace, comma (,) or close bracket (])"))}parseInlineTable(){if(this.char===x||this.char===P)return null;else if(this.char===$.END||this.char===X$||this.char===f||this.char===k)throw this.error(new M("Unterminated inline array"));else if(this.char===E2)return this.return(this.state.resultTable||h2());else{if(!this.state.resultTable)this.state.resultTable=h2();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(a(X,z)&&(!y$(X[z])||X[z][A$]))throw this.error(new M("Can't redefine existing key"));X=X[z]=X[z]||Q$()}if(a(X,Z))throw this.error(new M("Can't redefine existing key"));if(qq(J.value)||Jq(J.value))X[Z]=J.value.valueOf();else X[Z]=J.value;return this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===x||this.char===P)return null;else if(this.char===$.END||this.char===X$||this.char===f||this.char===k)throw this.error(new M("Unterminated inline array"));else if(this.char===y2)return this.next(this.parseInlineTable);else if(this.char===E2)return this.goto(this.parseInlineTable);else throw this.error(new M("Invalid character, expected whitespace, comma (,) or close bracket (])"))}}return q}});var W0=I((dJ,t2)=>{t2.exports=Y8;function Y8($,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 Y=String(Q+1);if(Y.length<Z)Y=" "+Y;if($.line===Q){J+=Y+"> "+X[Q]+`
30
+ `,J+=z+" ";for(let B=0;B<$.col;++B)J+=" ";J+=`^
31
+ `}else J+=Y+": "+X[Q]+`
32
+ `}}return $.message=J+`
33
+ `,$}});var a2=I((lJ,o2)=>{o2.exports=B8;var G8=G0(),W8=W0();function B8($){if(global.Buffer&&global.Buffer.isBuffer($))$=$.toString("utf8");let q=new G8;try{return q.parse($),q.finish()}catch(J){throw W8(J,$)}}});var $1=I((pJ,e2)=>{e2.exports=M8;var V8=G0(),r2=W0();function M8($,q){if(!q)q={};let J=0,X=q.blocksize||40960,Z=new V8;return new Promise((Q,Y)=>{setImmediate(z,J,X,Q,Y)});function z(Q,Y,B,W){if(Q>=$.length)try{return B(Z.finish())}catch(G){return W(r2(G,$))}try{Z.parse($.slice(Q,Q+Y)),setImmediate(z,Q+Y,Y,B,W)}catch(G){W(r2(G,$))}}}});var X1=I((nJ,J1)=>{J1.exports=K8;var U8=V$("stream"),q1=G0();function K8($){if($)return F8($);else return N8($)}function F8($){let q=new q1;return $.setEncoding("utf8"),new Promise((J,X)=>{let Z,z=!1,Q=!1;function Y(){if(z=!0,Z)return;try{J(q.finish())}catch(G){X(G)}}function B(G){Q=!0,X(G)}$.once("end",Y),$.once("error",B),W();function W(){Z=!0;let G;while((G=$.read())!==null)try{q.parse(G)}catch(V){return B(V)}if(Z=!1,z)return Y();if(Q)return;$.once("readable",W)}})}function N8(){let $=new q1;return new U8.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 Z1=I((sJ,C$)=>{C$.exports=a2();C$.exports.async=$1();C$.exports.stream=X1();C$.exports.prettyError=W0()});var M1=I((iJ,Kq)=>{Kq.exports=I8;Kq.exports.value=Uq;function I8($){if($===null)throw G$("null");if($===void 0)throw G$("undefined");if(typeof $!=="object")throw G$(typeof $);if(typeof $.toJSON==="function")$=$.toJSON();if($==null)return null;let q=A($);if(q!=="table")throw G$(q);return Mq("","",$)}function G$($){return Error("Can only stringify objects, not "+$)}function P8(){return Error("Array values can't have mixed types")}function z1($){return Object.keys($).filter((q)=>Q1($[q]))}function S8($){return Object.keys($).filter((q)=>!Q1($[q]))}function B0($){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 Mq($,q,J){J=B0(J);var X,Z;X=z1(J),Z=S8(J);var z=[],Q=q||"";if(X.forEach((B)=>{var W=A(J[B]);if(W!=="undefined"&&W!=="null")z.push(Q+V0(B)+" = "+W1(J[B],!0))}),z.length>0)z.push("");var Y=$&&X.length>0?q+" ":"";return Z.forEach((B)=>{z.push(R8($,Y,B,J[B]))}),z.join(`
34
+ `)}function Q1($){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 V0($){var q=String($);if(/^[-A-Za-z0-9_]+$/.test(q))return q;else return Y1(q)}function Y1($){return'"'+G1($).replace(/"/g,"\\\"")+'"'}function L8($){return"'"+$+"'"}function D8($,q){while(q.length<$)q="0"+q;return q}function G1($){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"+D8(4,q.codePointAt(0).toString(16)))}function w8($){let q=$.split(/\n/).map((J)=>{return G1(J).replace(/"(?="")/g,"\\\"")}).join(`
35
35
  `);if(q.slice(-1)==='"')q+="\\\n";return`"""
36
- `+q+'"""'}function rq($,q){let X=I($);if(X==="string"){if(q&&/\n/.test($))X="string-multiline";else if(!/[\b\t\n\f\r']/.test($)&&/"/.test($))X="string-literal"}return L0($,X)}function L0($,q){if(!q)q=I($);switch(q){case"string-multiline":return F8($);case"string":return aq($);case"string-literal":return S8($);case"integer":return eq($);case"float":return N8($);case"boolean":return P8($);case"datetime":return D8($);case"array":return x8($.filter((X)=>I(X)!=="null"&&I(X)!=="undefined"&&I(X)!=="nan"));case"table":return j8($);default:throw s(q)}}function eq($){return String($).replace(/\B(?=(\d{3})+(?!\d))/g,"_")}function N8($){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("."),X=q[0],Z=q[1]||0;return eq(X)+"."+Z}function P8($){return String($)}function D8($){return $.toISOString()}function I8($){return $==="float"||$==="integer"}function L8($){var q=I($[0]);if($.every((X)=>I(X)===q))return q;if($.every((X)=>I8(I(X))))return"float";return"mixed"}function $1($){let q=L8($);if(q==="mixed")throw M8();return q}function x8($){$=h$($);let q=$1($);var X="[",Z=$.map((Y)=>L0(Y,q));if(Z.join(", ").length>60||/\n/.test(Z))X+=`
37
- `+Z.join(`,
36
+ `+q+'"""'}function W1($,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 Uq($,J)}function Uq($,q){if(!q)q=A($);switch(q){case"string-multiline":return w8($);case"string":return Y1($);case"string-literal":return L8($);case"integer":return B1($);case"float":return x8($);case"boolean":return H8($);case"datetime":return j8($);case"array":return _8($.filter((J)=>A(J)!=="null"&&A(J)!=="undefined"&&A(J)!=="nan"));case"table":return f8($);default:throw G$(q)}}function B1($){return String($).replace(/\B(?=(\d{3})+(?!\d))/g,"_")}function x8($){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 B1(J)+"."+X}function H8($){return String($)}function j8($){return $.toISOString()}function O8($){return $==="float"||$==="integer"}function T8($){var q=A($[0]);if($.every((J)=>A(J)===q))return q;if($.every((J)=>O8(A(J))))return"float";return"mixed"}function V1($){let q=T8($);if(q==="mixed")throw P8();return q}function _8($){$=B0($);let q=V1($);var J="[",X=$.map((Z)=>Uq(Z,q));if(X.join(", ").length>60||/\n/.test(X))J+=`
37
+ `+X.join(`,
38
38
  `)+`
39
- `;else X+=" "+Z.join(", ")+(Z.length>0?" ":"");return X+"]"}function j8($){$=h$($);var q=[];return Object.keys($).forEach((X)=>{q.push(_$(X)+" = "+rq($[X],!1))}),"{ "+q.join(", ")+(q.length>0?" ":"")+"}"}function k8($,q,X,Z){var Y=I(Z);if(Y==="array")return H8($,q,X,Z);else if(Y==="table")return O8($,q,X,Z);else throw s(Y)}function H8($,q,X,Z){Z=h$(Z),$1(Z);var Y=I(Z[0]);if(Y!=="table")throw s(Y);var z=$+_$(X),J="";return Z.forEach((Q)=>{if(J.length>0)J+=`
40
- `;J+=q+"[["+z+`]]
41
- `,J+=I0(z+".",q,Q)}),J}function O8($,q,X,Z){var Y=$+_$(X),z="";if(lq(Z).length>0)z+=q+"["+Y+`]
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 f8($){$=B0($);var q=[];return Object.keys($).forEach((J)=>{q.push(V0(J)+" = "+W1($[J],!1))}),"{ "+q.join(", ")+(q.length>0?" ":"")+"}"}function R8($,q,J,X){var Z=A(X);if(Z==="array")return y8($,q,J,X);else if(Z==="table")return k8($,q,J,X);else throw G$(Z)}function y8($,q,J,X){X=B0(X),V1(X);var Z=A(X[0]);if(Z!=="table")throw G$(Z);var z=$+V0(J),Q="";return X.forEach((Y)=>{if(Q.length>0)Q+=`
40
+ `;Q+=q+"[["+z+`]]
41
+ `,Q+=Mq(z+".",q,Y)}),Q}function k8($,q,J,X){var Z=$+V0(J),z="";if(z1(X).length>0)z+=q+"["+Z+`]
42
+ `;return z+Mq(Z+".",q,X)}});var Fq=I((A8)=>{A8.parse=Z1();A8.stringify=M1()});var J2=h0(q2(),1),{program:$J,createCommand:qJ,createArgument:JJ,createOption:XJ,CommanderError:X2,InvalidArgumentError:ZJ,InvalidOptionArgumentError:zJ,Command:w,Argument:QJ,Option:YJ,Help:GJ}=J2.default;var p0=/^[a-z][a-z0-9-]{0,62}$/;var b={Success:0,AgentError:1,UserError:2,HookBlocked:3,BackendUnavailable:4,Interrupted:130};class H$ extends Error{code;constructor($,q,J){super(q,J);this.name="KmanError",this.code=$}}class U extends H${constructor($,q){super(b.UserError,$,q);this.name="UserError"}}class $$ extends H${constructor($,q){super(b.BackendUnavailable,$,q);this.name="BackendUnavailableError"}}var M$={name:"@unliftedq/kman",version:"0.0.4",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 S0,readFile as K4,readdir as F4,rename as N4,rm as L0,stat as I4,writeFile as D0}from"node:fs/promises";import{join as u$}from"node:path";import{homedir as L6}from"node:os";import{join as q$}from"node:path";function t(){let $=process.env.KMAN_HOME;return $&&$.length>0?$:q$(L6(),".kman")}function j$(){return q$(t(),"agents")}function v(){return q$(t(),"config.json")}function N($){return q$(j$(),$)}function t$($){return q$(N($),"agent.toml")}function o($,q="soul.md"){return q$(N($),q)}function u($){return q$(N($),"skills")}import{join as n0}from"node:path";var o$="kman";function D6(){return n0(t(),"runtime")}function O$($){return n0(D6(),$)}function Z2($,q){return n0(O$($),q==="claude"?".claude":".copilot")}import{randomUUID as W2}from"node:crypto";import{cp as H6,mkdir as _$,readFile as j6,rename as G2,rm as i0,stat as O6,symlink as T6,writeFile as a$}from"node:fs/promises";import{isAbsolute as _6,dirname as f6,join as _}from"node:path";class T$ extends Error{constructor($){super($);this.name="PromptArgumentError"}}var s0=[{name:"list-agents",description:"List the available kman-managed agents in a readable summary.",arguments:[],buildText:()=>"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."},{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}],buildText:($)=>`Task: ${$.task}
43
+
44
+ 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.`},{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}],buildText:($)=>`Run this task with the kman-managed agent "${$.agent}":
45
+
46
+ ${$.task}
47
+
48
+ Call kman_run_agent with agent="${$.agent}". Summarize the result in your own words and flag anything the agent could not complete.`},{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}],buildText:($)=>`Get a second opinion from the kman-managed agent "${$.agent}" on:
49
+
50
+ ${$.topic}
51
+
52
+ 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.`}];function z2(){return s0.map(({name:$,description:q,arguments:J})=>({name:$,description:q,arguments:J}))}function Q2($,q){let J=s0.find((X)=>X.name===$);if(!J)throw new T$(`Unknown prompt: ${$}`);for(let X of J.arguments){let Z=q[X.name];if(X.required&&(typeof Z!=="string"||Z.length===0))throw new T$(`Missing required argument: "${X.name}".`)}return{description:J.description,messages:[{role:"user",content:{type:"text",text:J.buildText(q)}}]}}function Y2(){return s0.map(($)=>{let q=w6($.arguments),J=x6($),X=$.buildText(q),Z=`---
53
+ description: ${$.description}
54
+ ---
55
+
56
+ `+(J?`${J}
57
+
58
+ `:"")+`${X}
59
+ `;return{name:$.name,content:Z}})}function w6($){let q={};if($.length===1)q[$[0].name]="$ARGUMENTS";else $.forEach((J,X)=>{q[J.name]=`$${X+1}`});return q}function x6($){if($.arguments.length===0)return"";if($.arguments.length===1)return`Usage: /${$.name} <${$.arguments[0].name}>`;let q=$.arguments.map((J)=>`<${J.name}>`).join(" ");return`Usage: /${$.name} ${q}`}var R6=["skills","hooks","scripts","bin","commands"],y6=[{from:"mcp.json",legacyFrom:".mcp.json",to:".mcp.json"}],B2="kman-commands";async function K$($,q){let J=N($.name),X=Z2($.name,q),Z=`${X}.staging-${process.pid}-${W2()}`;try{await k6(Z,J,$,q),await h6(Z,X)}catch(z){throw await i0(Z,{recursive:!0,force:!0}).catch(()=>{}),z}return{pluginDir:X,pluginAgent:`${o$}:${$.name}`}}async function k6($,q,J,X){await _$($,{recursive:!0}),await C6($,q,J,X);let Z=J.soul.prompt_file,z=_6(Z)?Z:o(J.name,Z);if(await _$(_($,"agents"),{recursive:!0}),await U$(z))await E6(z,$,J,X);for(let Q of R6){let Y=_(q,Q);if(await U$(Y))await t0(Y,_($,Q),"dir")}for(let Q of y6){let Y=_(q,Q.from);if(!await U$(Y)&&Q.legacyFrom){let B=_(q,Q.legacyFrom);if(await U$(B))Y=B}if(await U$(Y))await t0(Y,_($,Q.to),"file")}if(X==="copilot")await A6($)}async function A6($){let q=_($,B2);await _$(q,{recursive:!0});for(let J of Y2())await a$(_(q,`${J.name}.md`),J.content,"utf8")}async function E6($,q,J,X){let Z=_(q,"agents");if(X==="claude"){await t0($,_(Z,`${J.name}.md`),"file");return}let z=await j6($,"utf8"),Q=b6(z,J);await a$(_(Z,`${J.name}.agent.md`),Q,"utf8")}function b6($,q){let J=q.description??`${q.name} agent`;if(!$.startsWith(`---
60
+ `))return`---
61
+ name: ${q.name}
62
+ description: ${J}
63
+ ---
64
+
65
+ ${$}`;let X=$.indexOf(`
66
+ ---`,4);if(X<0)return $;let Z=$.slice(0,X);if(/^description:/m.test(Z))return $;return $.replace(/^---\n/,`---
67
+ description: ${J}
68
+ `)}async function h6($,q){await _$(f6(q),{recursive:!0});for(let J=0;J<100;J++){let X=`${q}.trash-${process.pid}-${W2()}`,Z=!1;try{await G2(q,X),Z=!0}catch(z){if(z.code!=="ENOENT")throw z}try{await G2($,q)}catch(z){if(Z)await i0(X,{recursive:!0,force:!0}).catch(()=>{});let Q=z.code;if(Q==="ENOTEMPTY"||Q==="EEXIST")continue;throw z}if(Z)await i0(X,{recursive:!0,force:!0}).catch(()=>{});return}throw Error(`materializeRuntimePlugin: could not swap ${$} into ${q}`)}async function C6($,q,J,X){if(X==="claude"){let Q={name:o$,agents:[`./agents/${J.name}.md`]};if(J.description)Q.description=J.description;await _$(_($,".claude-plugin"),{recursive:!0}),await a$(_($,".claude-plugin","plugin.json"),JSON.stringify(Q,null,2)+`
69
+ `,"utf8");return}let Z=[`${B2}/`];if(await U$(_(q,"commands")))Z.unshift("commands/");let z={name:o$,agents:"agents/",commands:Z};if(J.description)z.description=J.description;await a$(_($,"plugin.json"),JSON.stringify(z,null,2)+`
70
+ `,"utf8")}async function t0($,q,J){let X=J==="dir"?process.platform==="win32"?"junction":"dir":"file";try{await T6($,q,X)}catch(Z){if(Z.code==="EEXIST")return;await H6($,q,{recursive:J==="dir"})}}async function U$($){try{return await O6($),!0}catch(q){if(q.code==="ENOENT")return!1;throw q}}var M2=["claude-code","copilot-cli"],F$=["ask","auto","yolo"],N$=["text","json","stream-json"],V2={permission_mode:"ask",output_format:"text"};function r$($,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??V2.permission_mode,output_format:q.defaults?.output_format??V2.output_format},runtimeOverrides:q.runtimeOverrides??{}}}var U1=h0(Fq(),1);import{readFile as h8}from"node:fs/promises";function P$($){if(!p0.test($))throw new U(`Invalid agent name "${$}". Must match ${p0.source} (lowercase kebab-case, 1–63 chars).`)}function M0($){if(P$($.name),!$.runtime||typeof $.runtime.default!=="string")throw new U(`Profile "${$.name}" is missing runtime.default.`);let q=$.defaults.permission_mode;if(q!==void 0&&!F$.includes(q))throw new U(`Profile "${$.name}" has invalid permission_mode "${q}". Expected one of: ${F$.join(", ")}.`);let J=$.defaults.output_format;if(J!==void 0&&!N$.includes(J))throw new U(`Profile "${$.name}" has invalid output_format "${J}". Expected one of: ${N$.join(", ")}.`);if($.defaults.max_turns!==void 0&&(!Number.isInteger($.defaults.max_turns)||$.defaults.max_turns<=0))throw new U(`Profile "${$.name}" has invalid max_turns ${$.defaults.max_turns}. Expected positive integer.`)}function C8($,q){if(typeof q!=="object"||q===null)throw new U(`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,Y={};for(let[L,O]of Object.entries(Z)){if(L==="default"||L==="model")continue;if(typeof O==="object"&&O!==null&&!Array.isArray(O)){let l=O,B$={};if(typeof l.permission_mode_raw==="string")B$.permission_mode_raw=l.permission_mode_raw;if(Array.isArray(l.extra_args))B$.extra_args=l.extra_args.filter((n$)=>typeof n$==="string");if(typeof l.model==="string")B$.model=l.model;Y[L]=B$}}let B=J.soul??{},W=typeof B.prompt_file==="string"?B.prompt_file:"soul.md",G=J.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},K=r$($,{description:X,runtime:{default:z,...Q!==void 0?{model:Q}:{}},soul:{prompt_file:W},defaults:V,runtimeOverrides:Y});return M0(K),K}async function h($){let q=t$($),J;try{J=await h8(q,"utf8")}catch(Z){if(Z.code==="ENOENT")throw new U(`Agent "${$}" not found at ${q}.`);throw new U(`Failed to read profile for "${$}": ${Z.message}`,{cause:Z})}let X;try{X=U1.default.parse(J)}catch(Z){throw new U(`Failed to parse ${q}: ${Z.message}`,{cause:Z})}return C8($,{...X,name:$})}var K1=h0(Fq(),1);import{writeFile as v8,mkdir as u8}from"node:fs/promises";import{dirname as g8}from"node:path";function c8($){M0($);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,K1.default.stringify(q)}async function Nq($){let q=t$($.name);await u8(g8(q),{recursive:!0});let J=c8($);return await v8(q,J,"utf8"),q}var m8={defaults:{runtime:"claude-code"}};function Iq($){let q={runtime:$?.defaults?.runtime??m8.defaults.runtime};if($?.defaults?.model!==void 0)q.model=$.defaults.model;if($?.defaults?.permission_mode!==void 0)q.permission_mode=$.defaults.permission_mode;if($?.defaults?.output_format!==void 0)q.output_format=$.defaults.output_format;if($?.defaults?.max_turns!==void 0)q.max_turns=$.defaults.max_turns;return{defaults:q}}function S$($){let q=$.defaults;if(typeof q.runtime!=="string"||q.runtime.length===0)throw new U("config.json: defaults.runtime must be a non-empty string.");if(q.permission_mode!==void 0&&!F$.includes(q.permission_mode))throw new U(`config.json: invalid defaults.permission_mode "${q.permission_mode}". Expected one of: ${F$.join(", ")}.`);if(q.output_format!==void 0&&!N$.includes(q.output_format))throw new U(`config.json: invalid defaults.output_format "${q.output_format}". Expected one of: ${N$.join(", ")}.`);if(q.max_turns!==void 0&&(!Number.isInteger(q.max_turns)||q.max_turns<=0))throw new U(`config.json: invalid defaults.max_turns ${q.max_turns}. Expected a positive integer.`)}function U0($){return M2.includes($)}import{readFile as d8}from"node:fs/promises";function l8($){if(typeof $!=="object"||$===null||Array.isArray($))throw new U("config.json must contain a JSON object.");let J=$.defaults??{};if(typeof J!=="object"||J===null||Array.isArray(J))throw new U('config.json: "defaults" must be an object.');let X={};if(v$(J,"runtime","string"))X.runtime=J.runtime;if(v$(J,"model","string"))X.model=J.model;if(v$(J,"permission_mode","string"))X.permission_mode=J.permission_mode;if(v$(J,"output_format","string"))X.output_format=J.output_format;if(v$(J,"max_turns","number"))X.max_turns=J.max_turns;let Z=Iq({defaults:X});return S$(Z),Z}function v$($,q,J){let X=$[q];if(X===void 0||X===null)return!1;if(typeof X!==J)throw new U(`config.json: defaults.${q} must be a ${J}, got ${typeof X}.`);return!0}async function i(){let $=v(),q;try{q=await d8($,"utf8")}catch(X){if(X.code==="ENOENT")return Iq(void 0);throw new U(`Failed to read ${$}: ${X.message}`,{cause:X})}let J;try{J=JSON.parse(q)}catch(X){throw new U(`Failed to parse ${$}: ${X.message}`,{cause:X})}return l8(J)}import{mkdir as p8,writeFile as n8}from"node:fs/promises";import{dirname as s8}from"node:path";function i8($){S$($);let q={runtime:$.defaults.runtime};if($.defaults.model!==void 0)q.model=$.defaults.model;if($.defaults.permission_mode!==void 0)q.permission_mode=$.defaults.permission_mode;if($.defaults.output_format!==void 0)q.output_format=$.defaults.output_format;if($.defaults.max_turns!==void 0)q.max_turns=$.defaults.max_turns;return JSON.stringify({defaults:q},null,2)+`
71
+ `}async function Pq($){let q=v();return await p8(s8(q),{recursive:!0}),await n8(q,i8($),"utf8"),q}import{readFile as t8}from"node:fs/promises";import{isAbsolute as o8,join as a8}from"node:path";async function K0($,q={}){let J=N($.name),X=o8($.soul.prompt_file)?$.soul.prompt_file:a8(J,$.soul.prompt_file),Z="";try{Z=await t8(X,"utf8")}catch(O){if(O.code==="ENOENT")Z="";else throw new U(`Failed to read soul prompt at ${X}: ${O.message}`,{cause:O})}let z=q.backend??$.runtime.default,Q=$.runtimeOverrides[z]??{},Y=q.model??Q.model??$.runtime.model,B=q.permission??$.defaults.permission_mode??"ask",W=q.outputFormat??(q.stream?"stream-json":$.defaults.output_format??"text"),G=q.stream===!0||W==="stream-json",V=[...Q.extra_args??[],...q.runtimeFlags??[]],K={...q.env};return{profile:$,agentDir:J,soulPrompt:Z,backend:z,...Y!==void 0?{model:Y}:{},permission:B,outputFormat:W,...$.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:K,...q.task!==void 0?{task:q.task}:{},stream:G}}async function F1($,q){return I1($,q,"run")}async function N1($,q){return I1($,q,"chat")}async function I1($,q,J){if(q.soulPrompt.trim().length>0&&!$.capabilities.supportsAppendSystemPrompt)throw new $$(`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 $$(`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",(Y)=>{if(Y.code==="ENOENT")Q(new $$(`Backend "${$.name}" binary not found on PATH. Install it before running.`,{cause:Y}));else Q(Y)}),X.on("exit",(Y,B)=>{if(B==="SIGINT"||B==="SIGTERM")z({exitCode:b.Interrupted});else z({exitCode:Y??0})})})}finally{process.off("SIGINT",Z),process.off("SIGTERM",Z)}}var P1={ok:0,info:1,warn:2,error:3};function Sq($){let q="ok";for(let J of $.sections)for(let X of J.checks)if(P1[X.severity]>P1[q])q=X.severity;return q}import{spawn as r8}from"node:child_process";var F0=[{name:"claude-code",defaultBin:"claude",envOverride:"KMAN_CLAUDE_BIN"},{name:"copilot-cli",defaultBin:"copilot",envOverride:"KMAN_COPILOT_BIN"}];function e8($){if($.envOverride){let q=process.env[$.envOverride];if(q&&q.length>0)return q}return $.defaultBin}async function $4($,q=15000){return new Promise((J)=>{let X="",Z="",z=!1,Q=(W)=>{if(z)return;z=!0,J(W)},Y;try{Y=r8($,["--version"],{stdio:["ignore","pipe","pipe"],shell:!1})}catch(W){let G=W;Q({ok:!1,errorCode:G.code,errorMessage:G.message});return}let B=setTimeout(()=>{if(Y.exitCode===null&&Y.signalCode===null)Y.kill("SIGTERM");setTimeout(()=>{if(Y.exitCode===null&&Y.signalCode===null)Y.kill("SIGKILL")},250).unref(),Q({ok:!1,errorCode:"ETIMEDOUT",errorMessage:`${$} --version timed out`})},q).unref();Y.stdout?.on("data",(W)=>{X+=W.toString("utf8")}),Y.stderr?.on("data",(W)=>{Z+=W.toString("utf8")}),Y.on("error",(W)=>{clearTimeout(B);let G=W;Q({ok:!1,errorCode:G.code,errorMessage:G.message})}),Y.on("exit",(W)=>{clearTimeout(B);let V=(X||Z).trim().split(/\r?\n/).find((K)=>K.trim().length>0)??"";if(W===0&&V.length>0)Q({ok:!0,version:V});else if(W===0)Q({ok:!0,version:"(no output)"});else Q({ok:!1,errorCode:`EXIT_${W??"NULL"}`,errorMessage:V||`${$} --version exited ${W}`})})})}async function N0($){let q=e8($),J=await $4(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 S1,readFile as L1,stat as Lq}from"node:fs/promises";import{isAbsolute as q4,join as I0,resolve as J4}from"node:path";var X4=["git","node","npm","npx","bun","sh","bash","zsh","env","rm","mv","cp","ls","cat","echo","kman","claude","copilot","python","python3","pip","pip3"],Z4=process.platform==="win32";async function P0($){try{return await Lq($),!0}catch(q){if(q.code==="ENOENT")return!1;throw q}}async function z4($){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 Q4($){let q=$.soul.prompt_file,J=q4(q)?q:o($.name,q);try{let X=await Lq(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 Y4($){let q=I0(N($),"mcp.json"),J;try{J=await P0(q)}catch(G){return[{id:"mcp.present",label:"mcp.json",severity:"error",message:G.message}]}let X=q;if(!J){let G=I0(N($),".mcp.json");try{if(await P0(G))J=!0,X=G}catch(V){return[{id:"mcp.present",label:"mcp.json",severity:"error",message:V.message}]}}if(!J)return[{id:"mcp.present",label:"mcp.json",severity:"info",message:"not present; MCP servers disabled for this agent."}];let Z;try{Z=await L1(X,"utf8")}catch(G){return[{id:"mcp.readable",label:"mcp.json",severity:"error",message:G.message}]}let z;try{z=JSON.parse(Z)}catch(G){return[{id:"mcp.json",label:"mcp.json",severity:"error",message:`invalid JSON: ${G.message}`,detail:`Edit ${X} 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 Q=z.mcpServers,Y=[];if(typeof Q!=="object"||Q===null||Array.isArray(Q))return Y.push({id:"mcp.shape",label:"mcp.json",severity:"error",message:'missing "mcpServers" object.'}),Y;let B=Object.entries(Q);if(B.length===0)return Y.push({id:"mcp.servers",label:"mcp.json",severity:"info",message:"no MCP servers configured."}),Y;let W=0;for(let[G,V]of B){if(typeof V!=="object"||V===null){Y.push({id:`mcp.server.${G}.shape`,label:`mcpServers.${G}`,severity:"error",message:"entry must be an object."}),W++;continue}let K=V.command;if(typeof K!=="string"||K.length===0)Y.push({id:`mcp.server.${G}.command`,label:`mcpServers.${G}`,severity:"error",message:'"command" must be a non-empty string.'}),W++}return Y.unshift({id:"mcp.servers",label:"mcp.json",severity:W>0?"error":"ok",message:`${B.length} server(s) declared${W>0?`, ${W} invalid`:""}.`}),Y}function*G4($){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 Y=Q.command;if(typeof Y==="string"&&Y.length>0)yield Z===void 0?{command:Y}:{matcher:Z,command:Y}}}}}function W4($){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 B4($){let q=I0(N($),"hooks","hooks.json"),J;try{J=await P0(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 L1(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=N($),Y=Array.from(G4(Z));if(Y.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:`${Y.length} command hook(s) declared.`});for(let[B,W]of Y.entries()){let G=W4(W.command),V=`hook[${B}]${W.matcher?` matcher=${W.matcher}`:""}`;if(!G){z.push({id:`hooks.${B}.script`,label:V,severity:"info",message:"inline command (no ${CLAUDE_PLUGIN_ROOT} reference); skipped."});continue}let K=J4(Q,G);try{let L=await Lq(K);if(!L.isFile()){z.push({id:`hooks.${B}.script`,label:V,severity:"error",message:`${K} exists but is not a file.`});continue}if(Z4){z.push({id:`hooks.${B}.script`,label:V,severity:"ok",message:`${G} present (executable bit not checked on Windows).`});continue}if((L.mode&73)===0)z.push({id:`hooks.${B}.script`,label:V,severity:"error",message:`${G} is not executable.`,detail:`Run: chmod +x ${K}`});else z.push({id:`hooks.${B}.script`,label:V,severity:"ok",message:`${G} executable.`})}catch(L){let O=L;z.push({id:`hooks.${B}.script`,label:V,severity:"error",message:O.code==="ENOENT"?`${G} missing.`:O.message})}}return z}async function V4($){let q=I0(N($),"bin"),J;try{J=await S1(q,{withFileTypes:!0})}catch(Y){let B=Y;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((Y)=>Y.isFile()||Y.isSymbolicLink()).map((Y)=>Y.name);if(X.length===0)return[{id:"bin.entries",label:"bin/",severity:"info",message:"empty."}];let Z=(Y)=>Y.replace(/\.(sh|bat|cmd|exe|ps1)$/i,""),z=X.filter((Y)=>X4.includes(Z(Y))),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 M4($){let q=u($),J;try{J=await S1(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 D1($){let q=N($),J;try{J=await P0(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 z4($);if(X.push(...Z),z)X.push(await Q4(z));if(X.push(...await Y4($)),X.push(...await B4($)),X.push(...await V4($)),X.push(...await M4($)),z){let Q=F0.find((Y)=>Y.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 Y=await N0(Q);for(let B of Y)X.push({...B,id:`agent.${B.id}`})}}return X}async function w1($={}){let q=[];q.push({title:"Environment",checks:[{id:"env.kman_home",label:"KMAN_HOME",severity:"ok",message:t()},{id:"env.platform",label:"platform",severity:"ok",message:`${process.platform} ${process.arch} (node ${process.version})`},await U4()]});let J=$.backends??F0,X=await Promise.all(J.map((Z)=>N0(Z)));if(q.push({title:"Backends",checks:X.flat()}),$.agent){let Z=await D1($.agent);q.push({title:`Agent: ${$.agent}`,checks:Z})}return{sections:q,generatedAt:new Date().toISOString()}}async function U4(){try{let q=(await i()).defaults.runtime;if(!U0(q))return{id:"env.config",label:"config.json",severity:"warn",message:`defaults.runtime="${q}" has no built-in adapter`,detail:v()};return{id:"env.config",label:"config.json",severity:"ok",message:`defaults.runtime=${q}`,detail:v()}}catch($){return{id:"env.config",label:"config.json",severity:"warn",message:$.message,detail:v()}}}function x1(){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 H1(){let $=new w("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)=>{P$(q);let X=N(q);if(await g$(X))throw new U(`Agent "${q}" already exists at ${X}.`);let Z=await i();await S0(X,{recursive:!0}),await S0(u$(X,"skills"),{recursive:!0}),await S0(u$(X,"hooks"),{recursive:!0}),await S0(u$(X,"scripts"),{recursive:!0});let z=J.runtime??Z.defaults.runtime,Q=J.model??Z.defaults.model,Y={runtime:{default:z,...Q!==void 0?{model:Q}:{}}};if(J.description)Y.description=J.description;let B={...Z.defaults.permission_mode!==void 0?{permission_mode:Z.defaults.permission_mode}:{},...Z.defaults.output_format!==void 0?{output_format:Z.defaults.output_format}:{},...Z.defaults.max_turns!==void 0?{max_turns:Z.defaults.max_turns}:{}};if(Object.keys(B).length>0)Y.defaults=B;let W=r$(q,Y);await Nq(W);let G=J.soul??`# ${q}
43
72
 
44
73
  You are ${q}. Replace this file with your agent's system prompt.
45
- `;await Q1($q(q,z.soul.prompt_file),J,"utf8"),await Q1(b$(Z,".mcp.json"),JSON.stringify({mcpServers:{}},null,2)+`
46
- `,"utf8"),process.stdout.write(`Created agent "${q}" at ${Z}
47
- `)}),$.command("list").description("List all agents.").action(async()=>{let q=Z0(),X;try{X=await g8(q,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT"){process.stdout.write(`(no agents)
48
- `);return}throw Y}let Z=X.filter((Y)=>Y.isDirectory()).map((Y)=>Y.name).sort();if(Z.length===0){process.stdout.write(`(no agents)
49
- `);return}for(let Y of Z)process.stdout.write(`${Y}
50
- `)}),$.command("show <name>").description("Show profile + paths for an agent.").action(async(q)=>{let X=await l(q);if(process.stdout.write(`name: ${X.name}
51
- `),X.description)process.stdout.write(`description: ${X.description}
52
- `);if(process.stdout.write(`directory: ${k(X.name)}
53
- `),process.stdout.write(`runtime: ${X.runtime.default}`),X.runtime.model)process.stdout.write(` (model=${X.runtime.model})`);if(process.stdout.write(`
54
- `),process.stdout.write(`soul: ${X.soul.prompt_file}
55
- `),process.stdout.write(`defaults: permission=${X.defaults.permission_mode??"ask"} `),process.stdout.write(`output=${X.defaults.output_format??"text"}`),X.defaults.max_turns!==void 0)process.stdout.write(` max_turns=${X.defaults.max_turns}`);process.stdout.write(`
56
- `);let Z=Object.keys(X.runtimeOverrides);if(Z.length>0)process.stdout.write(`overrides: ${Z.join(", ")}
57
- `)}),$.command("delete <name>").description("Delete an agent directory.").option("--yes","Skip confirmation prompt.").action(async(q,X)=>{e(q);let Z=k(q);if(!await C$(Z))throw new B(`Agent "${q}" not found.`);if(!X.yes){if(!process.stdin.isTTY)throw new B(`Pass --yes to delete "${q}" non-interactively.`);process.stdout.write(`Delete agent "${q}" at ${Z}? [y/N] `);let Y=await T$();if(!/^y(es)?$/i.test(Y.trim())){process.stdout.write(`Aborted.
58
- `);return}}await m8(Z,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${Z}
59
- `)}),$.command("rename <from> <to>").description("Rename an agent.").action(async(q,X)=>{e(q),e(X);let Z=k(q),Y=k(X);if(!await C$(Z))throw new B(`Agent "${q}" not found.`);if(await C$(Y))throw new B(`Agent "${X}" already exists.`);await t8(Z,Y);let z=await l(X);await k0({...z,name:X}),process.stdout.write(`Renamed ${q} → ${X}
60
- `)}),$}async function C$($){try{return await i8($),!0}catch{return!1}}import{isAbsolute as n8,resolve as d8}from"node:path";var s8=/^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)(?:\/([^@\s]+))?(?:@(.+))?$/,l8=new Set(["anthropic-skills"]);function u$($,q){let X=$.trim();if(X.length===0)throw new B("Source cannot be empty.");if(X.startsWith(".")||X.startsWith("/")||X.startsWith("~")||X.startsWith("file://")||/^[A-Za-z]:[\\/]/.test(X)||n8(X)){let J=X.startsWith("file://")?X.slice(7):X;if(J.startsWith("~"))J=J.replace(/^~/,process.env.HOME??process.env.USERPROFILE??"~");return{kind:"local",path:d8(J),...q?{ref:q}:{}}}let Z=X.match(/^https?:\/\/github\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?(?:\/tree\/([^/]+))?(?:\/(.+))?$/);if(Z){let[,J="",Q="",W,f]=Z,G={kind:"github",owner:J,repo:Q};if(f)G.subpath=H0(f);let V=q??W;if(V)G.ref=V;return G}let Y=X.match(/^https?:\/\/gitlab\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?(?:\/-\/tree\/([^/]+))?(?:\/(.+))?$/);if(Y){let[,J="",Q="",W,f]=Y,G={kind:"gitlab",owner:J,repo:Q};if(f)G.subpath=H0(f);let V=q??W;if(V)G.ref=V;return G}if(X.startsWith("git+")||X.startsWith("ssh://")||/^git@[^:]+:/.test(X)||X.endsWith(".git")){let J={kind:"git",url:X.startsWith("git+")?X.slice(4):X};if(q)J.ref=q;return J}let z=X.match(s8);if(z){let[,J="",Q="",W,f]=z,G={kind:"github",owner:J,repo:Q};if(W)G.subpath=H0(W);let V=q??f;if(V)G.ref=V;return G}if(!X.includes("/")&&l8.has(X)){let J={kind:"well-known",name:X};if(q)J.ref=q;return J}throw new B(`Unrecognized source "${$}". Use a local path, GitHub/GitLab URL, owner/repo[/path][@ref], git URL, or well-known name.`)}function H0($){let q=$.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");if(q.length===0)throw new B("Empty source subpath after sanitization.");let X=q.split("/");for(let Z of X)if(Z===".."||Z==="."||Z.length===0)throw new B(`Invalid source subpath segment "${Z}" in "${$}".`);return X.join("/")}import{readdir as U1,stat as p8}from"node:fs/promises";import{basename as O0,join as B$,relative as E0}from"node:path";var a8=["","skills",".claude/skills"],o8=4,W1=new Set(["node_modules",".git",".turbo","dist","build",".cache"]);async function v$($,q){let X=q?B$($,q):$;if(!(await h0(X))?.isDirectory())throw new B(`Source path does not exist or is not a directory: ${X}`);let Y=[];if(await _0(X))return Y.push({name:O0(X),dir:X,relPath:E0($,X)||"."}),Y;for(let z of a8){let J=z?B$(X,z):X;if(!(await h0(J))?.isDirectory())continue;let W=await r8(J);for(let f of W)Y.push({name:O0(f),dir:f,relPath:E0($,f)});if(Y.length>0)return G1(Y)}if(await B1(X,0,$,Y),Y.length===0)throw new B(`No SKILL.md found anywhere under ${X}.`);return G1(Y)}async function r8($){let q;try{q=await U1($,{withFileTypes:!0})}catch{return[]}let X=[];for(let Z of q){if(!Z.isDirectory()||W1.has(Z.name))continue;let Y=B$($,Z.name);if(await _0(Y))X.push(Y)}return X}async function B1($,q,X,Z){if(q>o8)return;let Y;try{Y=await U1($,{withFileTypes:!0})}catch{return}if(await _0($)){Z.push({name:O0($),dir:$,relPath:E0(X,$)||"."});return}for(let z of Y){if(!z.isDirectory()||W1.has(z.name))continue;await B1(B$($,z.name),q+1,X,Z)}}async function _0($){return!!(await h0(B$($,"SKILL.md")))?.isFile()}async function h0($){try{return await p8($)}catch{return null}}function G1($){let q=new Set,X=[];for(let Z of $){if(q.has(Z.dir))continue;q.add(Z.dir),X.push(Z)}return X}import{cp as K1,mkdir as Y6,stat as z6}from"node:fs/promises";import{join as J6}from"node:path";import{readFile as e8,writeFile as $6,stat as q6}from"node:fs/promises";import{join as X6}from"node:path";var Z6=".kman-skill.json";function y0($){return X6($,Z6)}async function c$($){try{let q=await e8(y0($),"utf8");return JSON.parse(q)}catch(q){if(q.code==="ENOENT")return null;throw q}}async function V1($,q){await $6(y0($),JSON.stringify(q,null,2)+`
61
- `,"utf8")}async function M1($){try{return(await q6(y0($))).mtime}catch{return null}}function w1($){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 S1($){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 g$($){let q=$.installName??$.skill.name,X=J6(y($.agent),q),Z=await Q6(X);if(Z&&!$.force)throw new B(`Skill "${q}" already exists at ${X}. Use --force to overwrite.`);if(await Y6(y($.agent),{recursive:!0}),Z)await K1($.skill.dir,X,{recursive:!0,force:!0});else await K1($.skill.dir,X,{recursive:!0});let Y={source:w1($.source),installed_at:new Date().toISOString()},z=S1($.source);if(z)Y.source_url=z;if("ref"in $.source&&$.source.ref)Y.ref=$.source.ref;return await V1(X,Y),{installedPath:X,manifest:Y}}async function Q6($){try{return await z6($),!0}catch{return!1}}import{readdir as V6,stat as M6}from"node:fs/promises";import{join as F1}from"node:path";import{spawn as f6}from"node:child_process";import{mkdtemp as G6,rm as U6}from"node:fs/promises";import{tmpdir as W6}from"node:os";import{join as B6}from"node:path";async function m$($){switch($.kind){case"local":return{rootDir:$.path,subpath:$.subpath,cleanup:async()=>{}};case"github":return t$(`https://github.com/${$.owner}/${$.repo}.git`,$.ref,$.subpath);case"gitlab":return t$(`https://gitlab.com/${$.owner}/${$.repo}.git`,$.ref,$.subpath);case"git":return t$($.url,$.ref,$.subpath);case"well-known":{let X={"anthropic-skills":"https://github.com/anthropics/skills.git"}[$.name];if(!X)throw new B(`Unknown well-known skill source "${$.name}".`);return t$(X,$.ref,void 0)}default:{let q=$;throw new B("Unsupported source kind.")}}}async function t$($,q,X){let Z=await G6(B6(W6(),"kman-skill-"));if(await V$(["clone","--depth","1",$,Z]),q)try{await V$(["fetch","--depth","1","origin",q],Z),await V$(["checkout","FETCH_HEAD"],Z)}catch{await V$(["fetch","--unshallow"],Z).catch(()=>{}),await V$(["checkout",q],Z)}return{rootDir:Z,subpath:X,cleanup:()=>U6(Z,{recursive:!0,force:!0})}}function V$($,q){return new Promise((X,Z)=>{let Y=f6("git",$,{cwd:q,stdio:["ignore","pipe","pipe"]}),z="";Y.stderr?.on("data",(J)=>{z+=J.toString()}),Y.on("error",(J)=>{if(J.code==="ENOENT")Z(new c("git not found on PATH; cannot fetch skill sources."));else Z(J)}),Y.on("exit",(J)=>{if(J===0)X();else Z(new B(`git ${$.join(" ")} failed: ${z.trim()}`))})})}async function N1($){let q=F1(y($.agent),$.skill),X=await c$(q);if(!X)throw new B(`Skill "${$.skill}" has no .kman-skill.json manifest; cannot update. Use "skills remove" then "skills add".`);if(!$.force){let z=await M1(q);if(z){let J=await w6(q);if(J&&J.getTime()>z.getTime()+1000)throw new B(`Skill "${$.skill}" has local modifications newer than the manifest. Re-running update would overwrite them. Pass --force or "skills remove" first.`)}}let Z=u$(X.source,X.ref),Y=await m$(Z);try{let z=await v$(Y.rootDir,Y.subpath),J=z.find((W)=>W.name===$.skill)??z[0];if(!J)throw new B(`No skill named "${$.skill}" in source ${X.source}.`);let{installedPath:Q}=await g$({agent:$.agent,source:Z,skill:J,installName:$.skill,force:!0});return{installedPath:Q}}finally{await Y.cleanup()}}async function w6($){let q=null,X=[$];while(X.length>0){let Z=X.pop(),Y;try{Y=await V6(Z,{withFileTypes:!0})}catch{continue}for(let z of Y){let J=F1(Z,z.name);if(z.isDirectory()){X.push(J);continue}if(z.name===".kman-skill.json")continue;try{let Q=await M6(J);if(!q||Q.mtime>q)q=Q.mtime}catch{}}}return q}import{rm as S6,stat as K6}from"node:fs/promises";import{join as F6}from"node:path";async function P1($,q){let X=F6(y($),q);try{if(!(await K6(X)).isDirectory())throw new B(`Skill path is not a directory: ${X}`)}catch(Z){if(Z.code==="ENOENT")throw new B(`Skill "${q}" not found for agent "${$}".`);throw Z}return await S6(X,{recursive:!0,force:!0}),X}import{readdir as N6}from"node:fs/promises";import{join as P6}from"node:path";async function i$($){let q=y($),X;try{X=await N6(q,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT")return[];throw Y}let Z=[];for(let Y of X){if(!Y.isDirectory())continue;let z=P6(q,Y.name),J=await c$(z);Z.push({name:Y.name,dir:z,manifest:J})}return Z.sort((Y,z)=>Y.name.localeCompare(z.name))}function D1($){let q=[],X;for(let Z=0;Z<$.length;Z++){let Y=$[Z];if(Y==="-a"||Y==="--agent"){let z=$[Z+1];if(z===void 0||z.startsWith("-"))throw new B(`Missing value for ${Y}.`);R0(X),X=z,Z++;continue}if(Y.startsWith("--agent=")){R0(X),X=Y.slice(8);continue}if(Y.startsWith("-a=")){R0(X),X=Y.slice(3);continue}q.push(Y)}return{rest:q,agent:X}}function R0($){if($!==void 0)throw new B("--agent specified more than once.")}function h(){let $=process.env.KMAN_SELECTED_AGENT;if(!$)throw new B("Missing required --agent <name>. Agent-scoped commands need a target agent.");return $}function I1(){let $=new x("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).",D6,[]).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 X=h(),Z=u$(q.source,q.ref),Y=await m$(Z);try{let z=await v$(Y.rootDir,Y.subpath),J=await I6(z,q.skill.length>0?q.skill:void 0,q.all===!0);for(let Q of J){let W=await g$({agent:X,source:Z,skill:Q,force:q.force===!0});process.stdout.write(`Installed ${Q.name} → ${W.installedPath}
62
- `)}}finally{await Y.cleanup()}}),$.command("list").description("List installed skills for an agent.").action(async()=>{let q=h(),X=await i$(q);if(X.length===0){process.stdout.write(`(no skills installed for ${q})
63
- `);return}for(let Z of X){let Y=Z.manifest?.source??"local",z=Z.manifest?.ref?`@${Z.manifest.ref}`:"";process.stdout.write(`${Z.name} ${Y}${z}
64
- `)}}),$.command("show").description("Show details for an installed skill.").requiredOption("--skill <name>","Skill name.").action(async(q)=>{let X=h(),Y=(await i$(X)).find((z)=>z.name===q.skill);if(!Y)throw new B(`Skill "${q.skill}" not installed for agent "${X}".`);if(process.stdout.write(`name: ${Y.name}
65
- `),process.stdout.write(`directory: ${Y.dir}
66
- `),Y.manifest){if(process.stdout.write(`source: ${Y.manifest.source}
67
- `),Y.manifest.source_url)process.stdout.write(`source_url: ${Y.manifest.source_url}
68
- `);if(Y.manifest.ref)process.stdout.write(`ref: ${Y.manifest.ref}
69
- `);process.stdout.write(`installed_at: ${Y.manifest.installed_at}
74
+ `,V=J.description?`description: ${J.description}
75
+ `:"",K=`---
76
+ name: ${q}
77
+ ${V}---
78
+
79
+ ${G}`;await D0(o(q,W.soul.prompt_file),K,"utf8"),await D0(u$(X,"mcp.json"),JSON.stringify({mcpServers:{}},null,2)+`
80
+ `,"utf8"),process.stdout.write(`Created agent "${q}" at ${X}
81
+ `)}),$.command("list").description("List all agents.").action(async()=>{let q=j$(),J;try{J=await F4(q,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT"){process.stdout.write(`(no agents)
82
+ `);return}throw Z}let X=J.filter((Z)=>Z.isDirectory()).map((Z)=>Z.name).sort();if(X.length===0){process.stdout.write(`(no agents)
83
+ `);return}for(let Z of X)process.stdout.write(`${Z}
84
+ `)}),$.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}
85
+ `),J.description)process.stdout.write(`description: ${J.description}
86
+ `);if(process.stdout.write(`directory: ${N(J.name)}
87
+ `),process.stdout.write(`runtime: ${J.runtime.default}`),J.runtime.model)process.stdout.write(` (model=${J.runtime.model})`);if(process.stdout.write(`
88
+ `),process.stdout.write(`soul: ${J.soul.prompt_file}
89
+ `),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(`
90
+ `);let X=Object.keys(J.runtimeOverrides);if(X.length>0)process.stdout.write(`overrides: ${X.join(", ")}
91
+ `)}),$.command("delete <name>").description("Delete an agent's directory and all its contents.").option("--yes","Skip the confirmation prompt.").action(async(q,J)=>{P$(q);let X=N(q);if(!await g$(X))throw new U(`Agent "${q}" not found.`);if(!J.yes){if(!process.stdin.isTTY)throw new U(`Pass --yes to delete "${q}" non-interactively.`);process.stdout.write(`Delete agent "${q}" at ${X}? [y/N] `);let Z=await x1();if(!/^y(es)?$/i.test(Z.trim())){process.stdout.write(`Aborted.
92
+ `);return}}await L0(X,{recursive:!0,force:!0}),await L0(O$(q),{recursive:!0,force:!0}),process.stdout.write(`Deleted ${X}
93
+ `)}),$.command("rename <from> <to>").description("Rename an agent.").action(async(q,J)=>{P$(q),P$(J);let X=N(q),Z=N(J);if(!await g$(X))throw new U(`Agent "${q}" not found.`);if(await g$(Z))throw new U(`Agent "${J}" already exists.`);await N4(X,Z);let z=await h(J);await Nq({...z,name:J}),await P4(u$(Z,z.soul.prompt_file),J),await L0(O$(q),{recursive:!0,force:!0}),await L0(O$(J),{recursive:!0,force:!0}),process.stdout.write(`Renamed ${q} → ${J}
94
+ `)}),$}async function g$($){try{return await I4($),!0}catch{return!1}}async function P4($,q){if(!await g$($))return;let J=await K4($,"utf8");if(!J.startsWith("---")){let B=`---
95
+ name: ${q}
96
+ ---
97
+
98
+ `;await D0($,B+J,"utf8");return}let X=J.indexOf(`
99
+ ---`,3);if(X<0)return;let Z=J.slice(0,X),z=J.slice(X),Q=Z.replace(/^name:.*$/m,`name: ${q}`),Y=/^name:/m.test(Q)?Q:Q.replace(/^---\n/,`---
100
+ name: ${q}
101
+ `);await D0($,Y+z,"utf8")}import{isAbsolute as S4,resolve as L4}from"node:path";var D4=/^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)(?:\/([^@\s]+))?(?:@(.+))?$/,w4=new Set(["anthropic-skills"]);function w0($,q){let J=$.trim();if(J.length===0)throw new U("Source cannot be empty.");if(J.startsWith(".")||J.startsWith("/")||J.startsWith("~")||J.startsWith("file://")||/^[A-Za-z]:[\\/]/.test(J)||S4(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:L4(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="",Y="",B,W]=X,G={kind:"github",owner:Q,repo:Y};if(W)G.subpath=Dq(W);let V=q??B;if(V)G.ref=V;return G}let Z=J.match(/^https?:\/\/gitlab\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?(?:\/-\/tree\/([^/]+))?(?:\/(.+))?$/);if(Z){let[,Q="",Y="",B,W]=Z,G={kind:"gitlab",owner:Q,repo:Y};if(W)G.subpath=Dq(W);let V=q??B;if(V)G.ref=V;return G}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(D4);if(z){let[,Q="",Y="",B,W]=z,G={kind:"github",owner:Q,repo:Y};if(B)G.subpath=Dq(B);let V=q??W;if(V)G.ref=V;return G}if(!J.includes("/")&&w4.has(J)){let Q={kind:"well-known",name:J};if(q)Q.ref=q;return Q}throw new U(`Unrecognized source "${$}". Use a local path, GitHub/GitLab URL, owner/repo[/path][@ref], git URL, or well-known name.`)}function Dq($){let q=$.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");if(q.length===0)throw new U("Empty source subpath after sanitization.");let J=q.split("/");for(let X of J)if(X===".."||X==="."||X.length===0)throw new U(`Invalid source subpath segment "${X}" in "${$}".`);return J.join("/")}import{readdir as O1,stat as x4}from"node:fs/promises";import{basename as wq,join as c$,relative as xq}from"node:path";var H4=["","skills",".claude/skills"],j4=4,T1=new Set(["node_modules",".git",".turbo","dist","build",".cache"]);async function x0($,q){let J=q?c$($,q):$;if(!(await Hq(J))?.isDirectory())throw new U(`Source path does not exist or is not a directory: ${J}`);let Z=[];if(await jq(J))return Z.push({name:wq(J),dir:J,relPath:xq($,J)||"."}),Z;for(let z of H4){let Q=z?c$(J,z):J;if(!(await Hq(Q))?.isDirectory())continue;let B=await O4(Q);for(let W of B)Z.push({name:wq(W),dir:W,relPath:xq($,W)});if(Z.length>0)return j1(Z)}if(await _1(J,0,$,Z),Z.length===0)throw new U(`No SKILL.md found anywhere under ${J}.`);return j1(Z)}async function O4($){let q;try{q=await O1($,{withFileTypes:!0})}catch{return[]}let J=[];for(let X of q){if(!X.isDirectory()||T1.has(X.name))continue;let Z=c$($,X.name);if(await jq(Z))J.push(Z)}return J}async function _1($,q,J,X){if(q>j4)return;let Z;try{Z=await O1($,{withFileTypes:!0})}catch{return}if(await jq($)){X.push({name:wq($),dir:$,relPath:xq(J,$)||"."});return}for(let z of Z){if(!z.isDirectory()||T1.has(z.name))continue;await _1(c$($,z.name),q+1,J,X)}}async function jq($){return!!(await Hq(c$($,"SKILL.md")))?.isFile()}async function Hq($){try{return await x4($)}catch{return null}}function j1($){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 A1,mkdir as k4,stat as A4}from"node:fs/promises";import{join as E4}from"node:path";import{readFile as T4,writeFile as _4,stat as f4}from"node:fs/promises";import{join as R4}from"node:path";var y4=".kman-skill.json";function Oq($){return R4($,y4)}async function H0($){try{let q=await T4(Oq($),"utf8");return JSON.parse(q)}catch(q){if(q.code==="ENOENT")return null;throw q}}async function f1($,q){await _4(Oq($),JSON.stringify(q,null,2)+`
102
+ `,"utf8")}async function R1($){try{return(await f4(Oq($))).mtime}catch{return null}}function y1($){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 k1($){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 j0($){let q=$.installName??$.skill.name,J=E4(u($.agent),q),X=await b4(J);if(X&&!$.force)throw new U(`Skill "${q}" already exists at ${J}. Use --force to overwrite.`);if(await k4(u($.agent),{recursive:!0}),X)await A1($.skill.dir,J,{recursive:!0,force:!0});else await A1($.skill.dir,J,{recursive:!0});let Z={source:y1($.source),installed_at:new Date().toISOString()},z=k1($.source);if(z)Z.source_url=z;if("ref"in $.source&&$.source.ref)Z.ref=$.source.ref;return await f1(J,Z),{installedPath:J,manifest:Z}}async function b4($){try{return await A4($),!0}catch{return!1}}import{readdir as c4,stat as m4}from"node:fs/promises";import{join as E1}from"node:path";import{spawn as h4}from"node:child_process";import{mkdtemp as C4,rm as v4}from"node:fs/promises";import{tmpdir as u4}from"node:os";import{join as g4}from"node:path";async function T0($){switch($.kind){case"local":return{rootDir:$.path,subpath:$.subpath,cleanup:async()=>{}};case"github":return O0(`https://github.com/${$.owner}/${$.repo}.git`,$.ref,$.subpath);case"gitlab":return O0(`https://gitlab.com/${$.owner}/${$.repo}.git`,$.ref,$.subpath);case"git":return O0($.url,$.ref,$.subpath);case"well-known":{let J={"anthropic-skills":"https://github.com/anthropics/skills.git"}[$.name];if(!J)throw new U(`Unknown well-known skill source "${$.name}".`);return O0(J,$.ref,void 0)}default:{let q=$;throw new U("Unsupported source kind.")}}}async function O0($,q,J){let X=await C4(g4(u4(),"kman-skill-"));if(await m$(["clone","--depth","1",$,X]),q)try{await m$(["fetch","--depth","1","origin",q],X),await m$(["checkout","FETCH_HEAD"],X)}catch{await m$(["fetch","--unshallow"],X).catch(()=>{}),await m$(["checkout",q],X)}return{rootDir:X,subpath:J,cleanup:()=>v4(X,{recursive:!0,force:!0})}}function m$($,q){return new Promise((J,X)=>{let Z=h4("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 $$("git not found on PATH; cannot fetch skill sources."));else X(Q)}),Z.on("exit",(Q)=>{if(Q===0)J();else X(new U(`git ${$.join(" ")} failed: ${z.trim()}`))})})}async function b1($){let q=E1(u($.agent),$.skill),J=await H0(q);if(!J)throw new U(`Skill "${$.skill}" has no .kman-skill.json manifest; cannot update. Use "skills remove" then "skills add".`);if(!$.force){let z=await R1(q);if(z){let Q=await d4(q);if(Q&&Q.getTime()>z.getTime()+1000)throw new U(`Skill "${$.skill}" has local modifications newer than the manifest. Re-running update would overwrite them. Pass --force or "skills remove" first.`)}}let X=w0(J.source,J.ref),Z=await T0(X);try{let z=await x0(Z.rootDir,Z.subpath),Q=z.find((B)=>B.name===$.skill)??z[0];if(!Q)throw new U(`No skill named "${$.skill}" in source ${J.source}.`);let{installedPath:Y}=await j0({agent:$.agent,source:X,skill:Q,installName:$.skill,force:!0});return{installedPath:Y}}finally{await Z.cleanup()}}async function d4($){let q=null,J=[$];while(J.length>0){let X=J.pop(),Z;try{Z=await c4(X,{withFileTypes:!0})}catch{continue}for(let z of Z){let Q=E1(X,z.name);if(z.isDirectory()){J.push(Q);continue}if(z.name===".kman-skill.json")continue;try{let Y=await m4(Q);if(!q||Y.mtime>q)q=Y.mtime}catch{}}}return q}import{rm as l4,stat as p4}from"node:fs/promises";import{join as n4}from"node:path";async function h1($,q){let J=n4(u($),q);try{if(!(await p4(J)).isDirectory())throw new U(`Skill path is not a directory: ${J}`)}catch(X){if(X.code==="ENOENT")throw new U(`Skill "${q}" not found for agent "${$}".`);throw X}return await l4(J,{recursive:!0,force:!0}),J}import{readdir as s4}from"node:fs/promises";import{join as i4}from"node:path";async function _0($){let q=u($),J;try{J=await s4(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=i4(q,Z.name),Q=await H0(z);X.push({name:Z.name,dir:z,manifest:Q})}return X.sort((Z,z)=>Z.name.localeCompare(z.name))}function C1($){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 U(`Missing value for ${Z}.`);Tq(J),J=z,X++;continue}if(Z.startsWith("--agent=")){Tq(J),J=Z.slice(8);continue}if(Z.startsWith("-a=")){Tq(J),J=Z.slice(3);continue}q.push(Z)}return{rest:q,agent:J}}function Tq($){if($!==void 0)throw new U("--agent specified more than once.")}function d(){let $=process.env.KMAN_SELECTED_AGENT;if(!$)throw new U("Missing required --agent <name>. Agent-scoped commands need a target agent.");return $}function v1(){return process.env.KMAN_SELECTED_AGENT||void 0}function L$($){if(process.env.KMAN_SELECTED_AGENT)throw new U(`Subcommand "${$}" does not accept --agent.`)}import{emitKeypressEvents as t4}from"node:readline";function o4($){let q=$.selected.length;if(q===0)return;$.cursor=($.cursor-1+q)%q}function a4($){let q=$.selected.length;if(q===0)return;$.cursor=($.cursor+1)%q}function r4($){if($.selected.length===0)return;$.selected[$.cursor]=!$.selected[$.cursor]}function e4($){let q=$.selected.length>0&&$.selected.every(Boolean);$.selected.fill(!q)}var y="\x1B[",S={hideCursor:`${y}?25l`,showCursor:`${y}?25h`,clearDown:`${y}J`,moveToCol1:`${y}1G`,up:($)=>$>0?`${y}${$}A`:"",dim:($)=>`${y}2m${$}${y}22m`,bold:($)=>`${y}1m${$}${y}22m`,cyan:($)=>`${y}36m${$}${y}39m`,green:($)=>`${y}32m${$}${y}39m`,red:($)=>`${y}31m${$}${y}39m`};function $9($,q,J,X){let Z=[];Z.push(`${S.bold("?")} ${$} ${S.dim("(↑/↓ navigate · space toggle · a select all · enter confirm · esc cancel)")}`);for(let[z,Q]of q.entries()){let Y=z===J.cursor,B=J.selected[z],W=Y?S.cyan("❯"):" ",G=B?S.green("●"):S.dim("○"),V=Y?S.cyan(Q.label):Q.label,K=Q.hint?` ${S.dim(Q.hint)}`:"";Z.push(`${W} ${G} ${V}${K}`)}if(X)Z.push(S.red(X));return{text:Z.join(`
103
+ `)+`
104
+ `,lineCount:Z.length}}async function u1($){let{items:q,message:J}=$;if(q.length===0)return[];let X=$.requireOne!==!1,Z=new Set($.initialSelected??[]),z={cursor:0,selected:q.map((K)=>Z.has(K.value))},Q=process.stdout,Y=process.stdin,B=Y.isRaw===!0,W=0,G="";function V(){if(W>0)Q.write(S.moveToCol1),Q.write(S.up(W)),Q.write(S.clearDown);let K=$9(J,q,z,G);Q.write(K.text),W=K.lineCount}return new Promise((K,L)=>{function O(){Y.off("keypress",vq);try{if(!B&&Y.isTTY)Y.setRawMode(!1)}catch{}Y.pause(),Q.write(S.showCursor)}function l(){Q.write(S.moveToCol1),Q.write(S.up(W)),Q.write(S.clearDown)}function B$(){O(),l();let w$=q.filter((e,E)=>z.selected[E]);Q.write(`${S.bold("✓")} ${J} ${S.dim("—")} ${S.green(w$.map((e)=>e.label).join(", "))}
105
+ `),K(w$.map((e)=>e.value))}function n$(){O(),l(),Q.write(`${S.red("✗")} ${J} ${S.dim("(cancelled)")}
106
+ `),L(new U("Selection cancelled."))}function vq(w$,e){let E=e.name;if(e.ctrl&&E==="c")return n$();if(E==="escape"||E==="q")return n$();if(E==="up"||E==="k")return o4(z),G="",V();if(E==="down"||E==="j")return a4(z),G="",V();if(E==="space")return r4(z),G="",V();if(E==="a")return e4(z),G="",V();if(E==="return"){if(X&&z.selected.every((L3)=>!L3))return G="! Select at least one item, or press Esc to cancel.",V();return B$()}}try{if(t4(Y),Y.isTTY)Y.setRawMode(!0);Y.resume(),Q.write(S.hideCursor),Y.on("keypress",vq),V()}catch(w$){O(),L(w$)}})}function g1(){let $=new w("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).",q9,[]).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=d(),X=w0(q.source,q.ref),Z=await T0(X);try{let z=await x0(Z.rootDir,Z.subpath),Q=await J9(z,q.skill.length>0?q.skill:void 0,q.all===!0);for(let Y of Q){let B=await j0({agent:J,source:X,skill:Y,force:q.force===!0});process.stdout.write(`Installed ${Y.name} → ${B.installedPath}
107
+ `)}}finally{await Z.cleanup()}}),$.command("list").description("List installed skills for an agent.").action(async()=>{let q=d(),J=await _0(q);if(J.length===0){process.stdout.write(`(no skills installed for ${q})
108
+ `);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}
109
+ `)}}),$.command("show").description("Show details for an installed skill.").requiredOption("--skill <name>","Skill name.").action(async(q)=>{let J=d(),Z=(await _0(J)).find((z)=>z.name===q.skill);if(!Z)throw new U(`Skill "${q.skill}" not installed for agent "${J}".`);if(process.stdout.write(`name: ${Z.name}
110
+ `),process.stdout.write(`directory: ${Z.dir}
111
+ `),Z.manifest){if(process.stdout.write(`source: ${Z.manifest.source}
112
+ `),Z.manifest.source_url)process.stdout.write(`source_url: ${Z.manifest.source_url}
113
+ `);if(Z.manifest.ref)process.stdout.write(`ref: ${Z.manifest.ref}
114
+ `);process.stdout.write(`installed_at: ${Z.manifest.installed_at}
70
115
  `)}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 X=h();if(!q.skill&&!q.all)throw new B("Pass --skill <name> or --all.");let Z=q.all?(await i$(X)).filter((Y)=>!!Y.manifest).map((Y)=>Y.name):[q.skill];for(let Y of Z){let z=await N1({agent:X,skill:Y,force:q.force===!0});process.stdout.write(`Updated ${Y} → ${z.installedPath}
72
- `)}}),$.command("remove").description("Remove an installed skill.").requiredOption("--skill <name>","Skill name.").action(async(q)=>{let X=h(),Z=await P1(X,q.skill);process.stdout.write(`Removed ${Z}
73
- `)}),$}function D6($,q){return[...q,$]}async function I6($,q,X){if($.length===0)throw new B("No SKILL.md found in source.");if(q&&q.length>0){let Z=$.filter((Y)=>q.includes(Y.name));if(Z.length===0)throw new B(`Requested skills not found in source. Available: ${$.map((Y)=>Y.name).join(", ")}.`);return Z}if(X)return $;if($.length===1)return $;if(process.stdin.isTTY&&process.stdout.isTTY)return L6($);throw new B(`Source contains multiple skills. Pass --skill <name> (repeatable) or --all. Discovered: ${$.map((Z)=>Z.name).join(", ")}.`)}async function L6($){process.stdout.write(`Multiple skills discovered. Enter a comma-separated list of names to install (or "all"):
74
- `);for(let[Y,z]of $.entries())process.stdout.write(` ${Y+1}. ${z.name} (${z.relPath})
75
- `);process.stdout.write("> ");let q=(await T$()).trim();if(q.toLowerCase()==="all")return $;let X=q.split(",").map((Y)=>Y.trim()).filter(Boolean),Z=$.filter((Y)=>X.includes(Y.name));if(Z.length===0)throw new B(`No matching skills selected. Wanted: ${X.join(", ")}.`);return Z}import{spawn as x6}from"node:child_process";function $$($,q){let X={...process.env,...$.env},Z={cwd:$.cwd,env:X,stdio:"inherit",shell:!1,...q.options};return x6(q.command,q.args,Z)}var j6={ask:"default",auto:"acceptEdits",yolo:"bypassPermissions"};class L1{name="claude-code";capabilities={supportClaudeCodePlugin:!0,supportsAppendSystemPrompt:!0,supportsNativeResume:!0};binary;constructor($){this.binary=$??process.env.KMAN_CLAUDE_BIN??"claude"}mapPermission($){return j6[$]??"default"}async spawn($,q){let X=this.buildArgs($,!1);return $$($,{command:this.binary,args:X})}async chat($,q){let X=this.buildArgs($,!0);return $$($,{command:this.binary,args:X})}buildArgs($,q){let X=[];if(X.push("--plugin-dir",$.agentDir),$.soulPrompt.trim().length>0)X.push("--append-system-prompt",$.soulPrompt);if($.model)X.push("--model",$.model);let Z=$.permissionModeRaw??this.mapPermission($.permission);if(X.push("--permission-mode",Z),$.maxTurns!==void 0)X.push("--max-turns",String($.maxTurns));if(!q){if(X.push("--output-format",$.outputFormat),$.stream&&$.outputFormat==="stream-json")X.push("--include-partial-messages")}for(let Y of $.extraArgs)X.push(Y);if(!q&&$.task!==void 0)X.push("--print",$.task);return X}}function x1($){return new L1($)}var k6={ask:"ask",auto:"auto",yolo:"all"};class j1{name="copilot-cli";capabilities={supportClaudeCodePlugin:!1,supportsAppendSystemPrompt:!0,supportsNativeResume:!0};binary;constructor($){this.binary=$??process.env.KMAN_COPILOT_BIN??"copilot"}mapPermission($){return k6[$]??"ask"}async spawn($,q){let X=this.buildArgs($,!1);return $$($,{command:this.binary,args:X})}async chat($,q){let X=this.buildArgs($,!0);return $$($,{command:this.binary,args:X})}buildArgs($,q){let X=[];if($.soulPrompt.trim().length>0)X.push("--system-prompt",$.soulPrompt);if($.model)X.push("--model",$.model);let Z=$.permissionModeRaw??this.mapPermission($.permission);X.push("--approve-mode",Z);for(let Y of $.extraArgs)X.push(Y);if(!q&&$.task!==void 0)X.push("--prompt",$.task);return X}}function k1($){return new j1($)}var H1={"claude-code":x1,"copilot-cli":k1};function n$($){let q=H1[$];if(!q)throw new B(`Unknown backend "${$}". Built-in backends: ${Object.keys(H1).join(", ")}.`);return q()}function d$($){if($==="ask"||$==="auto"||$==="yolo")return $;throw new B(`Invalid --permission "${$}". Expected: ask | auto | yolo.`)}function O1($){if($==="text"||$==="json"||$==="stream-json")return $;throw new B(`Invalid --output "${$}". Expected: text | json | stream-json.`)}function E1(){return new x("run").description("One-shot run of an agent.").option("--task <text>","Task prompt passed to the backend.").option("--runtime <backend>","Override the agent's default backend.").option("--model <id>","Override model id.").option("--permission <level>","ask | auto | yolo").option("--runtime-flag <flag>","Raw backend-native flag (repeatable).",H6,[]).option("--output <format>","text | json | stream-json").option("--stream","Implies --output stream-json.").option("--cwd <path>","Working directory for the backend.").action(async($)=>{let q=h(),X=await l(q);if($.stream&&$.output&&$.output!=="stream-json")throw new B("--stream conflicts with --output of a different value.");let Z=await R$(X,{...$.runtime?{backend:$.runtime}:{},...$.model?{model:$.model}:{},...$.permission?{permission:d$($.permission)}:{},...$.output?{outputFormat:O1($.output)}:{},...$.stream!==void 0?{stream:$.stream===!0}:{},...$.cwd?{cwd:$.cwd}:{},...$.task!==void 0?{task:$.task}:{},runtimeFlags:O6($.runtimeFlag)}),Y=n$(Z.backend),{exitCode:z}=await Y1(Y,Z);process.exit(z)})}function H6($,q){return[...q,$]}function O6($){let q=[];for(let X of $)if(X.includes("=")&&!X.startsWith("--")){let Z=X.indexOf("="),Y=X.slice(0,Z),z=X.slice(Z+1);q.push(`--${Y}`,z)}else q.push(X);return q}function h1(){return new x("chat").description("Interactive REPL with an agent.").option("--runtime <backend>","Override the agent's default backend.").option("--model <id>","Override model id.").option("--permission <level>","ask | auto | yolo").option("--runtime-flag <flag>","Raw backend-native flag (repeatable).",E6,[]).option("--cwd <path>","Working directory for the backend.").action(async($)=>{let q=h(),X=await l(q),Z=await R$(X,{...$.runtime?{backend:$.runtime}:{},...$.model?{model:$.model}:{},...$.permission?{permission:d$($.permission)}:{},...$.cwd?{cwd:$.cwd}:{},runtimeFlags:h6($.runtimeFlag)}),Y=n$(Z.backend),{exitCode:z}=await z1(Y,Z);process.exit(z)})}function E6($,q){return[...q,$]}function h6($){let q=[];for(let X of $)if(X.includes("=")&&!X.startsWith("--")){let Z=X.indexOf("="),Y=X.slice(0,Z),z=X.slice(Z+1);q.push(`--${Y}`,z)}else q.push(X);return q}function _1(){return new x("version").description("Print kman CLI version.").action(()=>{process.stdout.write(`kman 0.0.2
76
- `)})}function y1($){if($ instanceof X$){if($.message)process.stderr.write(`kman: ${$.message}
77
- `);process.exit($.code)}if($ instanceof e0){let X=$.code==="commander.help"||$.code==="commander.helpDisplayed"?0:C.UserError;process.exit(X)}let q=$ instanceof Error?$.message:String($);if(process.stderr.write(`kman: unexpected error: ${q}
116
+ `)}),$.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=d();if(!q.skill&&!q.all)throw new U("Pass --skill <name> or --all.");let X=q.all?(await _0(J)).filter((Z)=>!!Z.manifest).map((Z)=>Z.name):[q.skill];for(let Z of X){let z=await b1({agent:J,skill:Z,force:q.force===!0});process.stdout.write(`Updated ${Z} → ${z.installedPath}
117
+ `)}}),$.command("remove").description("Remove an installed skill.").requiredOption("--skill <name>","Skill name.").action(async(q)=>{let J=d(),X=await h1(J,q.skill);process.stdout.write(`Removed ${X}
118
+ `)}),$}function q9($,q){return[...q,$]}async function J9($,q,J){if($.length===0)throw new U("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 U(`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 X9($);throw new U(`Source contains multiple skills. Pass --skill <name> (repeatable) or --all. Discovered: ${$.map((X)=>X.name).join(", ")}.`)}async function X9($){return u1({message:`Select skills to install (${$.length} discovered)`,items:$.map((q)=>({value:q,label:q.name,hint:q.relPath}))})}import{spawn as Z9}from"node:child_process";function D$($,q){let J={...process.env,...$.env},X={cwd:$.cwd,env:J,stdio:"inherit",shell:!1,...q.options};return Z9(q.command,q.args,X)}var z9={ask:"default",auto:"acceptEdits",yolo:"bypassPermissions"};class c1{name="claude-code";capabilities={supportClaudeCodePlugin:!0,supportsAppendSystemPrompt:!0,supportsNativeResume:!0};binary;constructor($){this.binary=$??process.env.KMAN_CLAUDE_BIN??"claude"}mapPermission($){return z9[$]??"default"}async spawn($,q){let{pluginDir:J,pluginAgent:X}=await K$($.profile,"claude"),Z=this.buildArgs($,J,X,!1);return D$($,{command:this.binary,args:Z})}async chat($,q){let{pluginDir:J,pluginAgent:X}=await K$($.profile,"claude"),Z=this.buildArgs($,J,X,!0);return D$($,{command:this.binary,args:Z})}buildArgs($,q,J,X){let Z=[];if(Z.push("--plugin-dir",q),Z.push("--agent",J),$.model)Z.push("--model",$.model);let z=$.permissionModeRaw??this.mapPermission($.permission);if(Z.push("--permission-mode",z),$.maxTurns!==void 0)Z.push("--max-turns",String($.maxTurns));if(!X){if(Z.push("--output-format",$.outputFormat),$.stream&&$.outputFormat==="stream-json")Z.push("--include-partial-messages")}for(let Q of $.extraArgs)Z.push(Q);if(!X&&$.task!==void 0)Z.push("--print",$.task);return Z}}function m1($){return new c1($)}var d1={ask:null,auto:"--allow-all-tools",yolo:"--yolo"};class l1{name="copilot-cli";capabilities={supportClaudeCodePlugin:!0,supportsAppendSystemPrompt:!0,supportsNativeResume:!0};binary;constructor($){this.binary=$??process.env.KMAN_COPILOT_BIN??"copilot"}mapPermission($){return d1[$]??"(default)"}async spawn($,q){let{pluginDir:J,pluginAgent:X}=await K$($.profile,"copilot"),Z=this.buildArgs($,J,X,!1);return D$($,{command:this.binary,args:Z})}async chat($,q){let{pluginDir:J,pluginAgent:X}=await K$($.profile,"copilot"),Z=this.buildArgs($,J,X,!0);return D$($,{command:this.binary,args:Z})}buildArgs($,q,J,X){let Z=[];if(Z.push("--plugin-dir",q),Z.push("--agent",J),$.permissionModeRaw===void 0){let z=d1[$.permission];if(z)Z.push(z)}if($.model)Z.push("--model",$.model);if(!X){if($.outputFormat==="stream-json")Z.push("--output-format","json","--stream","on");else if($.outputFormat==="json"||$.outputFormat==="text")Z.push("--output-format",$.outputFormat)}for(let z of $.extraArgs)Z.push(z);if(!X&&$.task!==void 0)Z.push("-p",$.task);return Z}}function p1($){return new l1($)}var n1={"claude-code":m1,"copilot-cli":p1};function f0($){let q=n1[$];if(!q)throw new U(`Unknown backend "${$}". Built-in backends: ${Object.keys(n1).join(", ")}.`);return q()}import{createInterface as U9}from"node:readline";var H={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603};class T extends Error{code;data;constructor($,q,J){super(q);if(this.code=$,J!==void 0)this.data=J}}import{readFile as Q9,readdir as Y9,stat as G9}from"node:fs/promises";async function R0($){let q=j$(),J;try{J=await Y9(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 y0($){let q=await h($),J="";try{J=await Q9(o(q.name,q.soul.prompt_file),"utf8")}catch(X){if(X.code!=="ENOENT")throw X}return{profile:q,soul:J,directory:N(q.name)}}async function _q($){try{return(await G9(N($))).isDirectory()}catch{return!1}}import{spawn as W9}from"node:child_process";async function s1($,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 Y=W9($.command,X,{stdio:["ignore","pipe","pipe"],env:Z,shell:!1}),B="",W="";Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(V)=>{B+=V}),Y.stderr?.on("data",(V)=>{W+=V});let G;if(J&&J>0)G=setTimeout(()=>{if(!Y.killed)Y.kill("SIGTERM")},J);Y.on("error",(V)=>{if(G)clearTimeout(G);Q(V)}),Y.on("exit",(V)=>{if(G)clearTimeout(G);z({exitCode:V??0,stdout:B,stderr:W})})})}var i1={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}},t1={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}},o1={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 a1(){return[i1,t1,o1]}async function r1($,q,J){switch($){case i1.name:return B9(J);case t1.name:return V9(q);case o1.name:return M9(q,J);default:throw new T(H.MethodNotFound,`Unknown tool: ${$}`)}}async function B9($){let q=await R0($.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 V9($){let q=fq($,"agent");if(!await _q(q))return W$(`Agent "${q}" not found at ~/.kman/agents/${q}/.`);let J=await y0(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 M9($,q){let J=fq($,"agent"),X=fq($,"task");if(q.selfAgent&&J===q.selfAgent)return W$(`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 W$(`Refusing to delegate to "${J}" — cycle detected (chain so far: ${z.join(" → ")}).`);if(z.length>=8)return W$(`Delegation depth limit reached (chain: ${z.join(" → ")}).`);if(!await _q(J))return W$(`Agent "${J}" not found at ~/.kman/agents/${J}/.`);let Q;try{Q=await s1(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 W$(`Failed to spawn kman subprocess: ${B.message}. Check that 'kman' is on PATH or set KMAN_BIN.`)}let Y=Q.stdout.trim();if(Q.exitCode===0)return{content:[{type:"text",text:Y.length>0?Y:"(agent produced no output)"}]};return W$(`Agent "${J}" exited with code ${Q.exitCode}.
119
+ `+(Q.stderr?`stderr:
120
+ ${Q.stderr.trim()}
121
+ `:"")+(Y?`stdout:
122
+ ${Y}`:""))}function fq($,q){let J=$[q];if(typeof J!=="string"||J.length===0)throw new T(H.InvalidParams,`Missing or non-string argument: "${q}".`);return J}function W$($){return{content:[{type:"text",text:$}],isError:!0}}var Rq={uri:"kman://agents",name:"Agent roster",description:"JSON list of every agent under ~/.kman/agents/.",mimeType:"application/json"},e1={uriTemplate:"kman://agents/{name}",name:"Agent profile",description:"Per-agent profile + soul prompt as a single JSON document.",mimeType:"application/json"};function $3(){return[Rq]}function q3(){return[e1]}async function J3($,q){if($===Rq.uri){let X=await R0(q.selfAgent);return{uri:$,mimeType:Rq.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 T(H.InvalidParams,`Resource ${$} is hidden: agent "${X}" hosts this MCP server.`);let Z=await y0(X);return{uri:$,mimeType:e1.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 T(H.InvalidParams,`Unknown resource URI: ${$}`)}function X3(){return z2()}function Z3($,q){try{return Q2($,q)}catch(J){if(J instanceof T$)throw new T(H.InvalidParams,J.message);throw J}}var K9="2024-11-05",F9="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 z3($={}){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=U9({input:q,crlfDelay:1/0}),z=(B)=>{J.write(JSON.stringify(B)+`
123
+ `)},Q=new Set;return{done:new Promise((B)=>{Z.on("line",(W)=>{let G=W.trim();if(!G)return;let V=N9(G,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 N9($,q,J){let X;try{X=JSON.parse($)}catch{J({jsonrpc:"2.0",id:null,error:{code:H.ParseError,message:"Invalid JSON."}});return}if(typeof X!=="object"||X===null){J({jsonrpc:"2.0",id:null,error:{code:H.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:H.InvalidRequest,message:"Not JSON-RPC 2.0."}});return}let Q="id"in Z;try{let Y=await I9(Z.method,Z.params,q);if(Q&&Y!==void 0)J({jsonrpc:"2.0",id:z,result:Y})}catch(Y){if(!Q)return;if(Y instanceof T)J({jsonrpc:"2.0",id:z,error:{code:Y.code,message:Y.message,...Y.data!==void 0?{data:Y.data}:{}}});else J({jsonrpc:"2.0",id:z,error:{code:H.InternalError,message:Y.message}})}}async function I9($,q,J){switch($){case"initialize":return{protocolVersion:K9,capabilities:{tools:{listChanged:!1},resources:{listChanged:!1,subscribe:!1},prompts:{listChanged:!1}},serverInfo:{name:"kman",version:P9()},instructions:F9};case"notifications/initialized":case"notifications/cancelled":case"notifications/roots/list_changed":return;case"ping":return{};case"tools/list":return{tools:a1()};case"tools/call":{let X=yq(q),Z=typeof X.name==="string"?X.name:"",z=X.arguments??{};if(!Z)throw new T(H.InvalidParams,'tools/call requires "name".');return r1(Z,z,J)}case"resources/list":return{resources:$3()};case"resources/templates/list":return{resourceTemplates:q3()};case"resources/read":{let X=yq(q),Z=typeof X.uri==="string"?X.uri:"";if(!Z)throw new T(H.InvalidParams,'resources/read requires "uri".');return{contents:[await J3(Z,{...J.selfAgent?{selfAgent:J.selfAgent}:{}})]}}case"prompts/list":return{prompts:X3()};case"prompts/get":{let X=yq(q),Z=typeof X.name==="string"?X.name:"",z=X.arguments??{};if(!Z)throw new T(H.InvalidParams,'prompts/get requires "name".');return Z3(Z,z)}default:throw new T(H.MethodNotFound,`Method not implemented: ${$}`)}}function yq($){if(typeof $!=="object"||$===null||Array.isArray($))throw new T(H.InvalidParams,"params must be an object.");return $}function P9(){return process.env.KMAN_VERSION??"0.0.0"}import{mkdir as S9,writeFile as L9,readFile as D9}from"node:fs/promises";import{dirname as w9}from"node:path";import{join as x9}from"node:path";function H9(){return x9(t(),"runtime","mcp-config.json")}async function Q3($){let q=H9();await S9(w9(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 j9(q,JSON.stringify(X,null,2)+`
124
+ `),q}async function j9($,q){try{if(await D9($,"utf8")===q)return}catch{}await L9($,q,"utf8")}import{mkdir as Y3,readFile as O9,writeFile as A0}from"node:fs/promises";import{homedir as T9,platform as _9}from"node:os";import{dirname as G3,join as k0,resolve as W3}from"node:path";var j="kman";function Aq($,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 B3($){let q;if($==="claude-code"||$==="claude")q=Eq("user");else if($==="copilot-cli"||$==="copilot")q=bq();else return!1;try{let X=(await l$(q)).mcpServers;if(typeof X!=="object"||X===null)return!1;return Object.prototype.hasOwnProperty.call(X,j)}catch{return!1}}function V3(){let $=new w("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 config 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=M$.version;let Z=d$();await z3({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=d$();if(q==="claude-code"||q==="claude")await f9(X,J.scope==="project"?"project":"user",J.force===!0);else if(q==="copilot-cli"||q==="copilot")await y9(X,J.force===!0);else throw new U(`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=d$(),J={mcpServers:{[j]:Aq(q)}};process.stdout.write(JSON.stringify(J,null,2)+`
125
+ `)}),$.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 R9(J.scope==="project"?"project":"user");else if(q==="copilot-cli"||q==="copilot")await k9();else throw new U(`Unknown runtime "${q}". Use claude-code or copilot-cli.`)}),$}function d$(){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:[W3(q)]}}async function f9($,q,J){let X=Eq(q),Z=await l$(X),z=Z.mcpServers??{};if(z[j]&&!J)throw new U(`Claude Code config already has an MCP server named "${j}". Re-run with --force to overwrite.`);z[j]=Aq($),Z.mcpServers=z,await Y3(G3(X),{recursive:!0}),await A0(X,JSON.stringify(Z,null,2)+`
126
+ `,"utf8"),process.stdout.write(`Registered "${j}" MCP server in ${X}
127
+ `)}async function R9($){let q=Eq($),J=await l$(q),X=J.mcpServers??{};if(!X[j]){process.stdout.write(`No "${j}" entry in ${q}.
128
+ `);return}delete X[j],J.mcpServers=X,await A0(q,JSON.stringify(J,null,2)+`
129
+ `,"utf8"),process.stdout.write(`Removed "${j}" from ${q}
130
+ `)}async function y9($,q){let J=bq(),X=await l$(J),Z=X.mcpServers??{};if(Z[j]&&!q)throw new U(`Copilot CLI config already has an MCP server named "${j}". Re-run with --force to overwrite.`);Z[j]=Aq($,{copilotType:!0}),X.mcpServers=Z,await Y3(G3(J),{recursive:!0}),await A0(J,JSON.stringify(X,null,2)+`
131
+ `,"utf8"),process.stdout.write(`Registered "${j}" MCP server in ${J}
132
+ `)}async function k9(){let $=bq(),q=await l$($),J=q.mcpServers??{};if(!J[j]){process.stdout.write(`No "${j}" entry in ${$}.
133
+ `);return}delete J[j],q.mcpServers=J,await A0($,JSON.stringify(q,null,2)+`
134
+ `,"utf8"),process.stdout.write(`Removed "${j}" from ${$}
135
+ `)}function kq(){return process.env.HOME??process.env.USERPROFILE??T9()}function Eq($){if($==="project")return W3(process.cwd(),".claude.json");return k0(kq(),".claude.json")}function bq(){if(_9()==="win32"){let $=process.env.APPDATA??k0(kq(),"AppData","Roaming");return k0($,"github-copilot","mcp_config.json")}return k0(kq(),".config","github-copilot","mcp_config.json")}async function l$($){try{let q=await O9($,"utf8");if(!q.trim())return{};let J=JSON.parse(q);if(typeof J!=="object"||J===null||Array.isArray(J))throw new U(`${$} is not a JSON object — refusing to edit.`);return J}catch(q){if(q.code==="ENOENT")return{};if(q instanceof U)throw q;if(q instanceof SyntaxError)throw new U(`${$} contains invalid JSON — refusing to edit: ${q.message}`);throw q}}async function E0($){if(process.env.KMAN_NO_MCP==="1")return $;let q=A9($.backend);if(!q)return $;let J=await B3($.backend),X={...$.env,KMAN_SELF_AGENT:$.profile.name,KMAN_RUN_CHAIN:E9(process.env.KMAN_RUN_CHAIN,$.profile.name),KMAN_SELECTED_AGENT:""};if(J)return{...$,env:X};let Z=d$(),z=await Q3({kmanCommand:Z.command,kmanBaseArgs:Z.baseArgs}),Q=q.pathPrefix?`${q.pathPrefix}${z}`:z;return{...$,extraArgs:[q.flag,Q,...$.extraArgs],env:X}}function A9($){switch($){case"claude-code":return{flag:"--mcp-config"};case"copilot-cli":return{flag:"--additional-mcp-config",pathPrefix:"@"};default:return}}function E9($,q){if(!$)return q;let J=$.split(",").filter(Boolean);if(J[J.length-1]===q)return $;return[...J,q].join(",")}function b0($){if($==="ask"||$==="auto"||$==="yolo")return $;throw new U(`Invalid --permission "${$}". Expected: ask | auto | yolo.`)}function M3($){if($==="text"||$==="json"||$==="stream-json")return $;throw new U(`Invalid --output "${$}". Expected: text | json | stream-json.`)}function U3(){return new w("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).",b9,[]).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=d(),J=await h(q);if($.stream&&$.output&&$.output!=="stream-json")throw new U("--stream conflicts with --output of a different value.");let X=await K0(J,{...$.runtime?{backend:$.runtime}:{},...$.model?{model:$.model}:{},...$.permission?{permission:b0($.permission)}:{},...$.output?{outputFormat:M3($.output)}:{},...$.stream!==void 0?{stream:$.stream===!0}:{},...$.cwd?{cwd:$.cwd}:{},...$.task!==void 0?{task:$.task}:{},runtimeFlags:h9($.runtimeFlag)}),Z=f0(X.backend),z=await E0(X),{exitCode:Q}=await F1(Z,z);process.exit(Q)})}function b9($,q){return[...q,$]}function h9($){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}var p$=["defaults.runtime","defaults.model","defaults.permission_mode","defaults.output_format","defaults.max_turns"];function K3(){let $=new w("config").description("View and edit global defaults in ~/.kman/config.json (e.g. the default runtime for new agents).");return $.command("show").description("Print the effective configuration (built-in defaults merged with config.json).").option("--json","Emit the configuration as JSON.").action(async(q)=>{L$("config show");let J=await i();if(q.json){process.stdout.write(JSON.stringify(J,null,2)+`
136
+ `);return}let X=J.defaults;if(process.stdout.write(`path: ${v()}
137
+ `),process.stdout.write(`defaults.runtime: ${X.runtime}`),!U0(X.runtime))process.stdout.write(" (no built-in adapter)");if(process.stdout.write(`
138
+ `),X.model!==void 0)process.stdout.write(`defaults.model: ${X.model}
139
+ `);if(X.permission_mode!==void 0)process.stdout.write(`defaults.permission_mode: ${X.permission_mode}
140
+ `);if(X.output_format!==void 0)process.stdout.write(`defaults.output_format: ${X.output_format}
141
+ `);if(X.max_turns!==void 0)process.stdout.write(`defaults.max_turns: ${X.max_turns}
142
+ `)}),$.command("path").description("Print the path to config.json.").action(()=>{L$("config path"),process.stdout.write(`${v()}
143
+ `)}),$.command("get <key>").description(`Print a single value. Keys: ${p$.join(", ")}.`).action(async(q)=>{L$("config get");let J=await i(),X=C9(J,hq(q));process.stdout.write(X===void 0?`(unset)
144
+ `:`${X}
145
+ `)}),$.command("set <key> <value>").description(`Set a value and write it to config.json. Keys: ${p$.join(", ")}.`).action(async(q,J)=>{L$("config set");let X=await i(),Z=v9(X,hq(q),J);S$(Z);let z=await Pq(Z);process.stdout.write(`Set ${q} = ${J} in ${z}
146
+ `)}),$.command("unset <key>").description(`Remove a value (reverts to the built-in default). Keys: ${p$.join(", ")}.`).action(async(q)=>{L$("config unset");let J=hq(q);if(J==="defaults.runtime")throw new U("defaults.runtime cannot be unset; set it to claude-code or copilot-cli instead.");let X=await i();delete X.defaults[F3(J)];let Z=await Pq(X);process.stdout.write(`Unset ${q} in ${Z}
147
+ `)}),$}function hq($){if(p$.includes($))return $;throw new U(`Unknown config key "${$}". Expected one of: ${p$.join(", ")}.`)}function F3($){return $.slice(9)}function C9($,q){return $.defaults[F3(q)]}function v9($,q,J){let X={...$.defaults};switch(q){case"defaults.runtime":X.runtime=J;break;case"defaults.model":X.model=J;break;case"defaults.permission_mode":X.permission_mode=J;break;case"defaults.output_format":X.output_format=J;break;case"defaults.max_turns":{let Z=Number(J);if(!Number.isInteger(Z))throw new U(`defaults.max_turns must be an integer, got "${J}".`);X.max_turns=Z;break}}return{defaults:X}}function N3(){return new w("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).",u9,[]).option("--cwd <path>","Working directory for the runtime process.").action(async($)=>{let q=d(),J=await h(q),X=await K0(J,{...$.runtime?{backend:$.runtime}:{},...$.model?{model:$.model}:{},...$.permission?{permission:b0($.permission)}:{},...$.cwd?{cwd:$.cwd}:{},runtimeFlags:g9($.runtimeFlag)}),Z=f0(X.backend),z=await E0(X),{exitCode:Q}=await N1(Z,z);process.exit(Q)})}function u9($,q){return[...q,$]}function g9($){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 I3(){return new w("version").description("Print kman CLI version.").action(()=>{process.stdout.write(`kman ${M$.version}
148
+ `)})}function P3(){return new w("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=v1(),J=await w1({...q?{agent:q}:{}});if($.json)process.stdout.write(JSON.stringify(J,null,2)+`
149
+ `);else process.stdout.write(d9(J,$.verbose===!0));if(Sq(J)==="error")process.exit(c9(J));process.exit(b.Success)})}function c9($){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 m9={ok:"✓",info:"·",warn:"!",error:"✗"};function d9($,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(` ${m9[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=Sq($),Z=l9($);return J.push(`overall: ${X} (${Z})`),J.map((z)=>z+`
150
+ `).join("")}function l9($){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 S3($){if($ instanceof H$){if($.message)process.stderr.write(`kman: ${$.message}
151
+ `);process.exit($.code)}if($ instanceof X2){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}
78
152
  `),process.env.KMAN_DEBUG&&$ instanceof Error&&$.stack)process.stderr.write($.stack+`
79
- `);process.exit(C.AgentError)}var A=new x;A.name("kman").description("Multi-agent orchestration engine (inspired by Kingsman).").version("0.0.2","-v, --version","Print kman CLI version.").helpOption("-h, --help","Show help.").showHelpAfterError().exitOverride();A.option("-a, --agent <name>","Target agent name (lowercase kebab-case). Required by agent-scoped subcommands.");A.addCommand(f1());A.addCommand(I1());A.addCommand(E1());A.addCommand(h1());A.addCommand(_1());var T0;try{let $=process.argv.slice(2),{rest:q,agent:X}=D1($);if(X!==void 0)process.env.KMAN_SELECTED_AGENT=X;T0=q}catch($){y1($)}if(T0.length===0)A.outputHelp(),process.exit(C.UserError);try{await A.parseAsync(T0,{from:"user"})}catch($){y1($)}
80
-
81
- //# debugId=8E30A6D5BFB497E864756E2164756E21
82
- //# sourceMappingURL=main.js.map
153
+ `);process.exit(b.AgentError)}var C=new w;C.name("kman").description("Multi-agent management tool.").version(M$.version,"-v, --version","Print kman CLI version.").helpOption("-h, --help","Show help.").showHelpAfterError().exitOverride();C.option("-a, --agent <name>","Target agent name (lowercase kebab-case). Required by agent-scoped subcommands.");C.addCommand(H1());C.addCommand(g1());C.addCommand(K3());C.addCommand(U3());C.addCommand(N3());C.addCommand(I3());C.addCommand(P3());C.addCommand(V3());var Cq;try{let $=process.argv.slice(2),{rest:q,agent:J}=C1($);if(J!==void 0)process.env.KMAN_SELECTED_AGENT=J;Cq=q}catch($){S3($)}if(Cq.length===0)C.outputHelp(),process.exit(b.UserError);try{await C.parseAsync(Cq,{from:"user"})}catch($){S3($)}