@unliftedq/kman 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +28 -0
- package/dist/main.js +82 -0
- package/dist/main.js.map +61 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Qiao Wang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# @unliftedq/kman
|
|
2
|
+
|
|
3
|
+
> Multi-agent orchestration engine — *inspired by [Kingsman](https://en.wikipedia.org/wiki/Kingsman:_The_Secret_Service)*.
|
|
4
|
+
|
|
5
|
+
`kman` is a backend-agnostic CLI that orchestrates existing agent CLIs (Claude Code, Copilot CLI, ...) through named agent profiles compatible with the Claude Code plugin spec.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
bun install -g @unliftedq/kman
|
|
11
|
+
# or
|
|
12
|
+
npm install -g @unliftedq/kman
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
kman --help
|
|
19
|
+
kman agent create coder --runtime claude-code
|
|
20
|
+
kman -a coder run --task "Refactor the auth module."
|
|
21
|
+
kman -a coder chat
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
See the monorepo at https://github.com/unliftedq/kman for the design document and source.
|
|
25
|
+
|
|
26
|
+
## License
|
|
27
|
+
|
|
28
|
+
MIT
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
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}
|
|
7
|
+
- a short flag is a single dash and a single character
|
|
8
|
+
- either use a single dash and a single character (for a short flag)
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);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
|
|
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(`${$}
|
|
22
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
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(`
|
|
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(`,
|
|
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}
|
|
43
|
+
|
|
44
|
+
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}
|
|
70
|
+
`)}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.1
|
|
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}
|
|
78
|
+
`),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.1","-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=DF6DC79E6914500364756E2164756E21
|
|
82
|
+
//# sourceMappingURL=main.js.map
|