@task-handoff/server 0.0.3-alpha.4 → 0.0.3-alpha.5

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/README.md CHANGED
@@ -1,3 +1,3 @@
1
1
  # @task-handoff/server
2
2
 
3
- Complete TaskHandoff server package. Installing it installs the control plane, node agent, and controlled instance runtimes at the same version. Run `task-handoff-install-server` as root to create and start the systemd services.
3
+ Complete TaskHandoff server package. Installing it installs the control plane, node agent, and controlled instance runtimes at the same version. Run `task-handoff install` as root to create and start the systemd services.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require("../dist/server-cli.js");
@@ -0,0 +1 @@
1
+ "use strict";var t=require("node:events"),e=require("node:child_process"),n=require("node:path"),i=require("node:fs"),o=require("node:process"),r=require("node:http");function s(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var a,h,l={},u={},c={};function p(){if(a)return c;a=1;class t extends Error{constructor(t,e,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}}return c.CommanderError=t,c.InvalidArgumentError=class extends t{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},c}function d(){if(h)return u;h=1;const{InvalidArgumentError:t}=p();return u.Argument=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,e){return e!==this.defaultValue&&Array.isArray(e)?(e.push(t),e):[t]}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},u.humanReadableArgName=function(t){const e=t.name()+(!0===t.variadic?"...":"");return t.required?"<"+e+">":"["+e+"]"},u}var m,g={},f={};function _(){if(m)return f;m=1;const{humanReadableArgName:t}=d();function e(t){return t.replace(/\x1b\[\d*(;\d*)*m/g,"")}return f.Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){const e=t.commands.filter(t=>!t._hidden),n=t._getHelpCommand();return n&&!n._hidden&&e.push(n),this.sortSubcommands&&e.sort((t,e)=>t.name().localeCompare(e.name())),e}compareOptions(t,e){const n=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");return n(t).localeCompare(n(e))}visibleOptions(t){const e=t.options.filter(t=>!t.hidden),n=t._getHelpOption();if(n&&!n.hidden){const i=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);i||o?n.long&&!o?e.push(t.createOption(n.long,n.description)):n.short&&!i&&e.push(t.createOption(n.short,n.description)):e.push(n)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];const e=[];for(let n=t.parent;n;n=n.parent){const t=n.options.filter(t=>!t.hidden);e.push(...t)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(t=>t.description)?t.registeredArguments:[]}subcommandTerm(e){const n=e.registeredArguments.map(e=>t(e)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((t,n)=>Math.max(t,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((t,n)=>Math.max(t,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((t,n)=>Math.max(t,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((t,n)=>Math.max(t,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let n="";for(let e=t.parent;e;e=e.parent)n=e.name()+" "+n;return n+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){const e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(t=>JSON.stringify(t)).join(", ")}`),void 0!==t.defaultValue&&(t.required||t.optional||t.isBoolean()&&"boolean"==typeof t.defaultValue)&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),void 0!==t.presetArg&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),void 0!==t.envVar&&e.push(`env: ${t.envVar}`),e.length>0){const n=`(${e.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}argumentDescription(t){const e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(t=>JSON.stringify(t)).join(", ")}`),void 0!==t.defaultValue&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){const n=`(${e.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatItemList(t,e,n){return 0===e.length?[]:[n.styleTitle(t),...e,""]}groupItems(t,e,n){const i=new Map;return t.forEach(t=>{const e=n(t);i.has(e)||i.set(e,[])}),e.forEach(t=>{const e=n(t);i.has(e)||i.set(e,[]),i.get(e).push(t)}),i}formatHelp(t,e){const n=e.padWidth(t,e),i=e.helpWidth??80;function o(t,i){return e.formatItem(t,n,i,e)}let r=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""];const s=e.commandDescription(t);s.length>0&&(r=r.concat([e.boxWrap(e.styleCommandDescription(s),i),""]));const a=e.visibleArguments(t).map(t=>o(e.styleArgumentTerm(e.argumentTerm(t)),e.styleArgumentDescription(e.argumentDescription(t))));r=r.concat(this.formatItemList("Arguments:",a,e));const h=this.groupItems(t.options,e.visibleOptions(t),t=>t.helpGroupHeading??"Options:");if(h.forEach((t,n)=>{const i=t.map(t=>o(e.styleOptionTerm(e.optionTerm(t)),e.styleOptionDescription(e.optionDescription(t))));r=r.concat(this.formatItemList(n,i,e))}),e.showGlobalOptions){const n=e.visibleGlobalOptions(t).map(t=>o(e.styleOptionTerm(e.optionTerm(t)),e.styleOptionDescription(e.optionDescription(t))));r=r.concat(this.formatItemList("Global Options:",n,e))}return this.groupItems(t.commands,e.visibleCommands(t),t=>t.helpGroup()||"Commands:").forEach((t,n)=>{const i=t.map(t=>o(e.styleSubcommandTerm(e.subcommandTerm(t)),e.styleSubcommandDescription(e.subcommandDescription(t))));r=r.concat(this.formatItemList(n,i,e))}),r.join("\n")}displayWidth(t){return e(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(t=>"[options]"===t?this.styleOptionText(t):"[command]"===t?this.styleSubcommandText(t):"["===t[0]||"<"===t[0]?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(t=>"[options]"===t?this.styleOptionText(t):"["===t[0]||"<"===t[0]?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,n,i){const o=" ".repeat(2);if(!n)return o+t;const r=t.padEnd(e+t.length-i.displayWidth(t)),s=(this.helpWidth??80)-e-2-2;let a;return a=s<this.minWidthToWrap||i.preformatted(n)?n:i.boxWrap(n,s).replace(/\n/g,"\n"+" ".repeat(e+2)),o+r+" ".repeat(2)+a.replace(/\n/g,`\n${o}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;const n=t.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,o=[];return n.forEach(t=>{const n=t.match(i);if(null===n)return void o.push("");let r=[n.shift()],s=this.displayWidth(r[0]);n.forEach(t=>{const n=this.displayWidth(t);if(s+n<=e)return r.push(t),void(s+=n);o.push(r.join(""));const i=t.trimStart();r=[i],s=this.displayWidth(i)}),o.push(r.join(""))}),o.join("\n")}},f.stripColor=e,f}var O,v={};function A(){if(O)return v;O=1;const{InvalidArgumentError:t}=p();function e(t){return t.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}return v.Option=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;const n=function(t){let e,n;const i=/^-[^-]$/,o=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");if(i.test(r[0])&&(e=r.shift()),o.test(r[0])&&(n=r.shift()),!e&&i.test(r[0])&&(e=r.shift()),!e&&o.test(r[0])&&(e=n,n=r.shift()),r[0].startsWith("-")){const e=r[0],n=`option creation failed due to '${e}' in option flags '${t}'`;if(/^-[^-][^-]/.test(e))throw new Error(`${n}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(i.test(e))throw new Error(`${n}\n- too many short flags`);if(o.test(e))throw new Error(`${n}\n- too many long flags`);throw new Error(`${n}\n- unrecognised flag format`)}if(void 0===e&&void 0===n)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:n}}(t);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return"string"==typeof t&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,e){return e!==this.defaultValue&&Array.isArray(e)?(e.push(t),e):[t]}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?e(this.name().replace(/^no-/,"")):e(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},v.DualOptions=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,e)=>{this.positiveOptions.has(e)&&this.dualOptions.add(e)})}valueFromOption(t,e){const n=e.attributeName();if(!this.dualOptions.has(n))return!0;const i=this.negativeOptions.get(n).presetArg,o=void 0!==i&&i;return e.negate===(o===t)}},v}var C,b,w,y={};function E(){return C||(C=1,y.suggestSimilar=function(t,e){if(!e||0===e.length)return"";e=Array.from(new Set(e));const n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(t=>t.slice(2)));let i=[],o=3;return e.forEach(e=>{if(e.length<=1)return;const n=function(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);const n=[];for(let e=0;e<=t.length;e++)n[e]=[e];for(let t=0;t<=e.length;t++)n[0][t]=t;for(let i=1;i<=e.length;i++)for(let o=1;o<=t.length;o++){let r=1;r=t[o-1]===e[i-1]?0:1,n[o][i]=Math.min(n[o-1][i]+1,n[o][i-1]+1,n[o-1][i-1]+r),o>1&&i>1&&t[o-1]===e[i-2]&&t[o-2]===e[i-1]&&(n[o][i]=Math.min(n[o][i],n[o-2][i-2]+1))}return n[t.length][e.length]}(t,e),r=Math.max(t.length,e.length);(r-n)/r>.4&&(n<o?(o=n,i=[e]):n===o&&i.push(e))}),i.sort((t,e)=>t.localeCompare(e)),n&&(i=i.map(t=>`--${t}`)),i.length>1?`\n(Did you mean one of ${i.join(", ")}?)`:1===i.length?`\n(Did you mean ${i[0]}?)`:""}),y}var $=function(){if(w)return l;w=1;const{Argument:r}=d(),{Command:s}=function(){if(b)return g;b=1;const r=t.EventEmitter,s=e,a=n,h=i,l=o,{Argument:u,humanReadableArgName:c}=d(),{CommanderError:m}=p(),{Help:f,stripColor:O}=_(),{Option:v,DualOptions:C}=A(),{suggestSimilar:w}=E();class y extends r{constructor(t){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=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>l.stdout.write(t),writeErr:t=>l.stderr.write(t),outputError:(t,e)=>e(t),getOutHelpWidth:()=>l.stdout.isTTY?l.stdout.columns:void 0,getErrHelpWidth:()=>l.stderr.isTTY?l.stderr.columns:void 0,getOutHasColors:()=>x()??(l.stdout.isTTY&&l.stdout.hasColors?.()),getErrHasColors:()=>x()??(l.stderr.isTTY&&l.stderr.hasColors?.()),stripColor:t=>O(t)},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(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){const t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,n){let i=e,o=n;"object"==typeof i&&null!==i&&(o=i,i=null),o=o||{};const[,r,s]=t.match(/([^ ]+) *(.*)/),a=this.createCommand(r);return i&&(a.description(i),a._executableHandler=!0),o.isDefault&&(this._defaultCommandName=a._name),a._hidden=!(!o.noHelp&&!o.hidden),a._executableFile=o.executableFile||null,s&&a.arguments(s),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),i?this:a}createCommand(t){return new y(t)}createHelp(){return Object.assign(new f,this.configureHelp())}configureHelp(t){return void 0===t?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return void 0===t?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return"string"!=typeof t&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error("Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()");return(e=e||{}).isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new u(t,e)}argument(t,e,n,i){const o=this.createArgument(t,e);return"function"==typeof n?o.default(i).argParser(n):o.default(n),this.addArgument(o),this}arguments(t){return t.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(t){const e=this.registeredArguments.slice(-1)[0];if(e?.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&void 0!==t.defaultValue&&void 0===t.parseArg)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if("boolean"==typeof t)return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const n=t??"help [command]",[,i,o]=n.match(/([^ ]+) *(.*)/),r=e??"display help for command",s=this.createCommand(i);return s.helpOption(!1),o&&s.arguments(o),r&&s.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=s,(t||e)&&this._initCommandGroup(s),this}addHelpCommand(t,e){return"object"!=typeof t?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(void 0===this._helpCommand&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){const n=["preSubcommand","preAction","postAction"];if(!n.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.\nExpecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return this._exitCallback=t||(t=>{if("commander.executeSubCommandAsync"!==t.code)throw t}),this}_exit(t,e,n){this._exitCallback&&this._exitCallback(new m(t,e,n)),l.exit(t)}action(t){return this._actionHandler=e=>{const n=this.registeredArguments.length,i=e.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),t.apply(this,i)},this}createOption(t,e){return new v(t,e)}_callParseArg(t,e,n,i){try{return t.parseArg(e,n)}catch(t){if("commander.invalidArgument"===t.code){const e=`${i} ${t.message}`;this.error(e,{exitCode:t.exitCode,code:t.code})}throw t}}_registerOption(t){const e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){const n=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'\n- already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){const e=t=>[t.name()].concat(t.aliases()),n=e(t).find(t=>this._findCommand(t));if(n){const i=e(this._findCommand(n)).join("|"),o=e(t).join("|");throw new Error(`cannot add command '${o}' as already have command '${i}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);const e=t.name(),n=t.attributeName();if(t.negate){const e=t.long.replace(/^--no-/,"--");this._findOption(e)||this.setOptionValueWithSource(n,void 0===t.defaultValue||t.defaultValue,"default")}else void 0!==t.defaultValue&&this.setOptionValueWithSource(n,t.defaultValue,"default");const i=(e,i,o)=>{null==e&&void 0!==t.presetArg&&(e=t.presetArg);const r=this.getOptionValue(n);null!==e&&t.parseArg?e=this._callParseArg(t,e,r,i):null!==e&&t.variadic&&(e=t._collectValue(e,r)),null==e&&(e=!t.negate&&(!(!t.isBoolean()&&!t.optional)||"")),this.setOptionValueWithSource(n,e,o)};return this.on("option:"+e,e=>{const n=`error: option '${t.flags}' argument '${e}' is invalid.`;i(e,n,"cli")}),t.envVar&&this.on("optionEnv:"+e,e=>{const n=`error: option '${t.flags}' value '${e}' from env '${t.envVar}' is invalid.`;i(e,n,"env")}),this}_optionEx(t,e,n,i,o){if("object"==typeof e&&e instanceof v)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const r=this.createOption(e,n);if(r.makeOptionMandatory(!!t.mandatory),"function"==typeof i)r.default(o).argParser(i);else if(i instanceof RegExp){const t=i;i=(e,n)=>{const i=t.exec(e);return i?i[0]:n},r.default(o).argParser(i)}else r.default(i);return this.addOption(r)}option(t,e,n,i){return this._optionEx({},t,e,n,i)}requiredOption(t,e,n,i){return this._optionEx({mandatory:!0},t,e,n,i)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,n){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=n,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(n=>{void 0!==n.getOptionValueSource(t)&&(e=n.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(void 0!==t&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},void 0===t&&void 0===e.from){l.versions?.electron&&(e.from="electron");const t=l.execArgv??[];(t.includes("-e")||t.includes("--eval")||t.includes("-p")||t.includes("--print"))&&(e.from="eval")}let n;switch(void 0===t&&(t=l.argv),this.rawArgs=t.slice(),e.from){case void 0:case"node":this._scriptPath=t[1],n=t.slice(2);break;case"electron":l.defaultApp?(this._scriptPath=t[1],n=t.slice(2)):n=t.slice(1);break;case"user":n=t.slice(0);break;case"eval":n=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(t,e){this._prepareForParse();const n=this._prepareUserArgs(t,e);return this._parseCommand([],n),this}async parseAsync(t,e){this._prepareForParse();const n=this._prepareUserArgs(t,e);return await this._parseCommand([],n),this}_prepareForParse(){null===this._savedState?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error("Can not call parse again when storeOptionsAsProperties is true.\n- 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(t,e,n){if(!h.existsSync(t))throw new Error(`'${t}' does not exist\n - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`)}_executeSubCommand(t,e){e=e.slice();let n=!1;const i=[".js",".ts",".tsx",".mjs",".cjs"];function o(t,e){const n=a.resolve(t,e);if(h.existsSync(n))return n;if(i.includes(a.extname(e)))return;const o=i.find(t=>h.existsSync(`${n}${t}`));return o?`${n}${o}`:void 0}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r,u=t._executableFile||`${this._name}-${t._name}`,c=this._executableDir||"";if(this._scriptPath){let t;try{t=h.realpathSync(this._scriptPath)}catch{t=this._scriptPath}c=a.resolve(a.dirname(t),c)}if(c){let e=o(c,u);if(!e&&!t._executableFile&&this._scriptPath){const n=a.basename(this._scriptPath,a.extname(this._scriptPath));n!==this._name&&(e=o(c,`${n}-${t._name}`))}u=e||u}n=i.includes(a.extname(u)),"win32"!==l.platform?n?(e.unshift(u),e=$(l.execArgv).concat(e),r=s.spawn(l.argv[0],e,{stdio:"inherit"})):r=s.spawn(u,e,{stdio:"inherit"}):(this._checkForMissingExecutable(u,c,t._name),e.unshift(u),e=$(l.execArgv).concat(e),r=s.spawn(l.execPath,e,{stdio:"inherit"})),r.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(t=>{l.on(t,()=>{!1===r.killed&&null===r.exitCode&&r.kill(t)})});const p=this._exitCallback;r.on("close",t=>{t=t??1,p?p(new m(t,"commander.executeSubCommandAsync","(close)")):l.exit(t)}),r.on("error",e=>{if("ENOENT"===e.code)this._checkForMissingExecutable(u,c,t._name);else if("EACCES"===e.code)throw new Error(`'${u}' not executable`);if(p){const t=new m(1,"commander.executeSubCommandAsync","(error)");t.nestedError=e,p(t)}else l.exit(1)}),this.runningCommand=r}_dispatchSubcommand(t,e,n){const i=this._findCommand(t);let o;return i||this.help({error:!0}),i._prepareForParse(),o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(!i._executableHandler)return i._parseCommand(e,n);this._executeSubCommand(i,e.concat(n))}),o}_dispatchHelpCommand(t){t||this.help();const e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&null==this.args[e]&&this.missingArgument(t.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const t=(t,e,n)=>{let i=e;if(null!==e&&t.parseArg){const o=`error: command-argument value '${e}' is invalid for argument '${t.name()}'.`;i=this._callParseArg(t,e,n,o)}return i};this._checkNumberOfArguments();const e=[];this.registeredArguments.forEach((n,i)=>{let o=n.defaultValue;n.variadic?i<this.args.length?(o=this.args.slice(i),n.parseArg&&(o=o.reduce((e,i)=>t(n,i,e),n.defaultValue))):void 0===o&&(o=[]):i<this.args.length&&(o=this.args[i],n.parseArg&&(o=t(n,o,n.defaultValue))),e[i]=o}),this.processedArgs=e}_chainOrCall(t,e){return t?.then&&"function"==typeof t.then?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let n=t;const i=[];return this._getCommandAndAncestors().reverse().filter(t=>void 0!==t._lifeCycleHooks[e]).forEach(t=>{t._lifeCycleHooks[e].forEach(e=>{i.push({hookedCommand:t,callback:e})})}),"postAction"===e&&i.reverse(),i.forEach(t=>{n=this._chainOrCall(n,()=>t.callback(t.hookedCommand,this))}),n}_chainOrCallSubCommandHook(t,e,n){let i=t;return void 0!==this._lifeCycleHooks[n]&&this._lifeCycleHooks[n].forEach(t=>{i=this._chainOrCall(i,()=>t(this,e))}),i}_parseCommand(t,e){const n=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(n.operands),e=n.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){let n;return i(),this._processArguments(),n=this._chainOrCallHooks(n,"preAction"),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(o,t,e)})),n=this._chainOrCallHooks(n,"postAction"),n}if(this.parent?.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&void 0===t.getOptionValue(e.attributeName())&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){const t=this.options.filter(t=>{const e=t.attributeName();return void 0!==this.getOptionValue(e)&&"default"!==this.getOptionValueSource(e)}),e=t.filter(t=>t.conflictsWith.length>0);e.forEach(e=>{const n=t.find(t=>e.conflictsWith.includes(t.attributeName()));n&&this._conflictingOption(e,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){const e=[],n=[];let i=e;function o(t){return t.length>1&&"-"===t[0]}const r=t=>!!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(t)&&!this._getCommandAndAncestors().some(t=>t.options.map(t=>t.short).some(t=>/^-\d$/.test(t)));let s=null,a=null,h=0;for(;h<t.length||a;){const l=a??t[h++];if(a=null,"--"===l){i===n&&i.push(l),i.push(...t.slice(h));break}if(!s||o(l)&&!r(l)){if(s=null,o(l)){const e=this._findOption(l);if(e){if(e.required){const n=t[h++];void 0===n&&this.optionMissingArgument(e),this.emit(`option:${e.name()}`,n)}else if(e.optional){let n=null;h<t.length&&(!o(t[h])||r(t[h]))&&(n=t[h++]),this.emit(`option:${e.name()}`,n)}else this.emit(`option:${e.name()}`);s=e.variadic?e:null;continue}}if(l.length>2&&"-"===l[0]&&"-"!==l[1]){const t=this._findOption(`-${l[1]}`);if(t){t.required||t.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${t.name()}`,l.slice(2)):(this.emit(`option:${t.name()}`),a=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){const t=l.indexOf("="),e=this._findOption(l.slice(0,t));if(e&&(e.required||e.optional)){this.emit(`option:${e.name()}`,l.slice(t+1));continue}}if(i!==e||!o(l)||0===this.commands.length&&r(l)||(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&0===e.length&&0===n.length){if(this._findCommand(l)){e.push(l),n.push(...t.slice(h));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){e.push(l,...t.slice(h));break}if(this._defaultCommandName){n.push(l,...t.slice(h));break}}if(this._passThroughOptions){i.push(l,...t.slice(h));break}i.push(l)}else this.emit(`option:${s.name()}`,l)}return{operands:e,unknown:n}}opts(){if(this._storeOptionsAsProperties){const t={},e=this.options.length;for(let n=0;n<e;n++){const e=this.options[n].attributeName();t[e]=e===this._versionOptionName?this._version:this[e]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}\n`,this._outputConfiguration.writeErr),"string"==typeof this._showHelpAfterError?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));const n=e||{},i=n.exitCode||1,o=n.code||"commander.error";this._exit(i,o,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in l.env){const e=t.attributeName();(void 0===this.getOptionValue(e)||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,l.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){const t=new C(this.options),e=t=>void 0!==this.getOptionValue(t)&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter(n=>void 0!==n.implied&&e(n.attributeName())&&t.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(t=>{Object.keys(t.implied).filter(t=>!e(t)).forEach(e=>{this.setOptionValueWithSource(e,t.implied[e],"implied")})})}missingArgument(t){const e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){const e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){const n=t=>{const e=t.attributeName(),n=this.getOptionValue(e),i=this.options.find(t=>t.negate&&e===t.attributeName()),o=this.options.find(t=>!t.negate&&e===t.attributeName());return i&&(void 0===i.presetArg&&!1===n||void 0!==i.presetArg&&n===i.presetArg)?i:o||t},i=t=>{const e=n(t),i=e.attributeName();return"env"===this.getOptionValueSource(i)?`environment variable '${e.envVar}'`:`option '${e.flags}'`},o=`error: ${i(t)} cannot be used with ${i(e)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{const t=i.createHelp().visibleOptions(i).filter(t=>t.long).map(t=>t.long);n=n.concat(t),i=i.parent}while(i&&!i._enablePositionalOptions);e=w(t,n)}const n=`error: unknown option '${t}'${e}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const e=this.registeredArguments.length,n=1===e?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${n} but got ${t.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let e="";if(this._showSuggestionAfterError){const n=[];this.createHelp().visibleCommands(this).forEach(t=>{n.push(t.name()),t.alias()&&n.push(t.alias())}),e=w(t,n)}const n=`error: unknown command '${t}'${e}`;this.error(n,{code:"commander.unknownCommand"})}version(t,e,n){if(void 0===t)return this._version;this._version=t,e=e||"-V, --version",n=n||"output the version number";const i=this.createOption(e,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${t}\n`),this._exit(0,"commander.version",t)}),this}description(t,e){return void 0===t&&void 0===e?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return void 0===t?this._summary:(this._summary=t,this)}alias(t){if(void 0===t)return this._aliases[0];let e=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");const n=this.parent?._findCommand(t);if(n){const e=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${e}'`)}return e._aliases.push(t),this}aliases(t){return void 0===t?this._aliases:(t.forEach(t=>this.alias(t)),this)}usage(t){if(void 0===t){if(this._usage)return this._usage;const t=this.registeredArguments.map(t=>c(t));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=t,this}name(t){return void 0===t?this._name:(this._name=t,this)}helpGroup(t){return void 0===t?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return void 0===t?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return void 0===t?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=a.basename(t,a.extname(t)),this}executableDir(t){return void 0===t?this._executableDir:(this._executableDir=t,this)}helpInformation(t){const e=this.createHelp(),n=this._getOutputContext(t);e.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});const i=e.formatHelp(this,e);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(t){const e=!!(t=t||{}).error;let n,i,o;return e?(n=t=>this._outputConfiguration.writeErr(t),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=t=>this._outputConfiguration.writeOut(t),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:e,write:t=>(i||(t=this._outputConfiguration.stripColor(t)),n(t)),hasColors:i,helpWidth:o}}outputHelp(t){let e;"function"==typeof t&&(e=t,t=void 0);const n=this._getOutputContext(t),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(t=>t.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:n.error});if(e&&(o=e(o),"string"!=typeof o&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(t=>t.emit("afterAllHelp",i))}helpOption(t,e){return"boolean"==typeof t?(t?(null===this._helpOption&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(l.exitCode??0);0===e&&t&&"function"!=typeof t&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){const n=["beforeAll","before","after","afterAll"];if(!n.includes(t))throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${n.join("', '")}'`);const i=`${t}Help`;return this.on(i,t=>{let n;n="function"==typeof e?e({error:t.error,command:t.command}):e,n&&t.write(`${n}\n`)}),this}_outputHelpIfRequested(t){const e=this._getHelpOption();e&&t.find(t=>e.is(t))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function $(t){return t.map(t=>{if(!t.startsWith("--inspect"))return t;let e,n,i="127.0.0.1",o="9229";return null!==(n=t.match(/^(--inspect(-brk)?)$/))?e=n[1]:null!==(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(e=n[1],/^\d+$/.test(n[3])?o=n[3]:i=n[3]):null!==(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(e=n[1],i=n[3],o=n[4]),e&&"0"!==o?`${e}=${i}:${parseInt(o)+1}`:t})}function x(){return!l.env.NO_COLOR&&"0"!==l.env.FORCE_COLOR&&"false"!==l.env.FORCE_COLOR&&(!(!l.env.FORCE_COLOR&&void 0===l.env.CLICOLOR_FORCE)||void 0)}return g.Command=y,g.useColor=x,g}(),{CommanderError:a,InvalidArgumentError:h}=p(),{Help:u}=_(),{Option:c}=A();return l.program=new s,l.createCommand=t=>new s(t),l.createOption=(t,e)=>new c(t,e),l.createArgument=(t,e)=>new r(t,e),l.Command=s,l.Option=c,l.Argument=r,l.Help=u,l.CommanderError=a,l.InvalidArgumentError=h,l.InvalidOptionArgumentError=h,l}(),x=s($);const{program:k,createCommand:H,createArgument:S,createOption:T,CommanderError:V,InvalidArgumentError:D,InvalidOptionArgumentError:P,Command:N,Argument:F,Option:G,Help:W}=x,I=n.resolve(__dirname,".."),j=JSON.parse(i.readFileSync(n.join(I,"package.json"),"utf8")),M=process.env.TASK_HANDOFF_NPM_COMMAND||"npm",R=new Set(["stable","beta","alpha"]);function q(t,n,i={}){const o=e.spawnSync(t,n,{encoding:"utf8",...i});if(0!==o.status){const e=[o.stdout,o.stderr].filter(Boolean).join("\n").trim();throw new Error(`${t} ${n.join(" ")} failed${e?`:\n${e}`:""}`)}return String(o.stdout||"").trim()}function L(t){const e={};if(!i.existsSync(t))return e;for(const n of i.readFileSync(t,"utf8").split(/\r?\n/)){if(!n||n.startsWith("#"))continue;const t=n.indexOf("=");t>0&&(e[n.slice(0,t)]=n.slice(t+1))}return e}function U(){const t="/etc/systemd/system/task-handoff-node-agent.service";return i.existsSync(t)&&i.readFileSync(t,"utf8").match(/^User=(.+)$/m)?.[1]||"root"}function B(t){const n=e.spawnSync("systemctl",["is-active",t],{encoding:"utf8"});return String(n.stdout||"unknown").trim()||"unknown"}function K(t,e){if(!R.has(t))throw new Error("--channel must be stable, beta, or alpha.");if(e&&!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(e))throw new Error("--to must be an exact semantic version.");return e||("stable"===t?"latest":t)}function J(t,e){const n=["view",`@task-handoff/server@${t}`,"version","--json"];e&&n.push("--registry",e);const i=JSON.parse(q(M,n));if("string"!=typeof i)throw new Error(`npm target ${t} did not resolve to one version.`);return i}function Y(){if("function"==typeof process.getuid&&0!==process.getuid())throw new Error("Run this command as root so system packages and services can be changed.")}function z(t){return[["--service-user",t.serviceUser],["--control-plane-data-dir",t.controlPlaneDataDir],["--node-agent-data-dir",t.nodeAgentDataDir],["--control-plane-host",t.controlPlaneHost],["--control-plane-port",t.controlPlanePort],["--node-agent-host",t.nodeAgentHost],["--node-agent-port",t.nodeAgentPort],["--node-agent-ipc-path",t.nodeAgentIpcPath],["--auth-mode",t.authMode],["--static-dir",t.staticDir]].flatMap(([t,e])=>void 0===e?[]:[t,e])}(async function(){const t=(new N).name("task-handoff").description("Manage a TaskHandoff server and run its installed runtimes.").version(j.version).showSuggestionAfterError();t.command("control-plane","Run the installed control-plane runtime.",{executableFile:"task-handoff-control-plane"}),t.command("node-agent","Run the installed node-agent runtime.",{executableFile:"task-handoff-node-agent"}),t.command("controlled-instance","Run the installed controlled-instance runtime.",{executableFile:"task-handoff-controlled-instance"}),t.command("install").description("Install or regenerate the server systemd services.").option("--service-user <user>").option("--control-plane-data-dir <path>").option("--node-agent-data-dir <path>").option("--control-plane-host <host>").option("--control-plane-port <port>").option("--node-agent-host <host>").option("--node-agent-port <port>").option("--node-agent-ipc-path <path>").option("--auth-mode <mode>").option("--static-dir <path>").action(t=>{Y(),q(process.execPath,[n.join(I,"bin","task-handoff-install-server"),...z(t)],{stdio:"inherit"})}),t.command("status").description("Show the installed version and service state.").action(()=>{console.log(`Package: @task-handoff/server ${j.version}`),console.log(`Node agent: ${B("task-handoff-node-agent.service")}`),console.log(`Control plane: ${B("task-handoff-control-plane.service")}`)}),t.command("check").description("Check npm for an available server version.").option("--channel <channel>","stable, beta, or alpha","stable").option("--registry <url>").action(t=>{const e=K(t.channel),n=J(e,t.registry);console.log(`Installed: ${j.version}`),console.log(`Available (${t.channel} channel, npm ${e}): ${n}`),console.log(n===j.version?"Up to date.":`Update available: task-handoff update --to ${n}`)}),t.command("update").description("Update the server package set and restart services safely.").option("--channel <channel>","stable, beta, or alpha","stable").option("--to <version>").option("--registry <url>").option("--force").action(async t=>{if(Y(),t.to&&process.argv.includes("--channel"))throw new Error("Use either --channel or --to, not both.");const e=K(t.channel,t.to),o=e===j.version?j.version:J(e,t.registry);if(o===j.version&&!t.force)return void console.log(`@task-handoff/server ${j.version} is already installed.`);const s=function(){const t="/run/task-handoff-server-update.lock";try{i.mkdirSync(t)}catch(t){if("EEXIST"===t?.code)throw new Error("Another TaskHandoff server update is already running.");throw t}return()=>i.rmSync(t,{recursive:!0,force:!0})}();try{const e=function(){let t=I;for(;t!==n.dirname(t);){if("node_modules"===n.basename(t)&&"lib"===n.basename(n.dirname(t)))return n.dirname(n.dirname(t));t=n.dirname(t)}throw new Error(`Cannot determine the npm global prefix from ${I}.`)}(),s=function(){const t=L("/etc/task-handoff/control-plane.env"),e=L("/etc/task-handoff/node-agent.env");return["--service-user",U(),"--control-plane-data-dir",t.TASK_HANDOFF_CONTROL_PLANE_DATA_DIR||"/var/lib/task-handoff/control-plane","--node-agent-data-dir",e.TASK_HANDOFF_NODE_AGENT_DATA_DIR||"/var/lib/task-handoff/node-agent","--control-plane-host",t.TASK_HANDOFF_CONTROL_PLANE_HOST||"0.0.0.0","--control-plane-port",t.TASK_HANDOFF_CONTROL_PLANE_PORT||"8081","--node-agent-host",e.TASK_HANDOFF_NODE_AGENT_HOST||"127.0.0.1","--node-agent-port",e.TASK_HANDOFF_NODE_AGENT_PORT||"8091","--node-agent-ipc-path",e.TASK_HANDOFF_NODE_AGENT_IPC_PATH||"/run/task-handoff/node-agent.sock","--auth-mode",t.TASK_HANDOFF_CONTROL_PLANE_AUTH_MODE||"password"]}(),a=s[s.indexOf("--node-agent-ipc-path")+1],h=Number(s[s.indexOf("--control-plane-port")+1]),l=["install","--global","--prefix",e,`@task-handoff/server@${o}`];t.registry&&l.push("--registry",t.registry),console.log(`Updating @task-handoff/server ${j.version} -> ${o}`),q(M,l,{stdio:"inherit"}),q(n.join(e,"bin","task-handoff"),["install",...s],{stdio:"inherit"}),q("systemctl",["restart","task-handoff-node-agent.service"]),function(t,e=3e4){const n=Date.now()+e;for(;Date.now()<n;){try{if(i.statSync(t).isSocket())return}catch{}Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,250)}throw new Error(`Node agent socket was not ready after ${e}ms: ${t}`)}(a),q("systemctl",["restart","task-handoff-control-plane.service"]),await function(t,e=3e4){return new Promise((n,i)=>{const o=Date.now()+e,s=()=>{const e=r.get({host:"127.0.0.1",port:t,path:"/api/health",timeout:1e3},t=>{if(t.resume(),200===t.statusCode)return n();a()});e.on("timeout",()=>e.destroy()),e.on("error",a)},a=()=>Date.now()>=o?i(new Error(`Control plane was not healthy on port ${t} after ${e}ms.`)):setTimeout(s,250);s()})}(h),console.log(`Updated TaskHandoff server to ${o}.`)}catch(t){throw console.error(`Update failed. To reinstall the previous version, run: npm install -g @task-handoff/server@${j.version}`),t}finally{s()}}),await t.parseAsync(process.argv)})().catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1});
package/package.json CHANGED
@@ -1,25 +1,24 @@
1
1
  {
2
2
  "name": "@task-handoff/server",
3
- "version": "0.0.3-alpha.4",
3
+ "version": "0.0.3-alpha.5",
4
4
  "description": "Complete TaskHandoff server package.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
7
7
  "bin": {
8
- "task-handoff-install-server": "bin/task-handoff-install-server",
9
- "task-handoff-server-install": "bin/task-handoff-install-server",
10
- "task-handoff-server": "bin/task-handoff-server"
8
+ "task-handoff": "bin/task-handoff"
11
9
  },
12
10
  "files": [
13
11
  "bin",
12
+ "dist",
14
13
  "README.md"
15
14
  ],
16
15
  "engines": {
17
16
  "node": ">=22.22.2"
18
17
  },
19
18
  "dependencies": {
20
- "@task-handoff/control-plane": "0.0.3-alpha.4",
21
- "@task-handoff/node-agent": "0.0.3-alpha.4",
22
- "@task-handoff/controlled-instance": "0.0.3-alpha.4"
19
+ "@task-handoff/control-plane": "0.0.3-alpha.5",
20
+ "@task-handoff/node-agent": "0.0.3-alpha.5",
21
+ "@task-handoff/controlled-instance": "0.0.3-alpha.5"
23
22
  },
24
23
  "publishConfig": {
25
24
  "access": "public"
@@ -1,226 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require("node:fs");
4
- const http = require("node:http");
5
- const path = require("node:path");
6
- const { spawnSync } = require("node:child_process");
7
-
8
- const packageRoot = path.resolve(__dirname, "..");
9
- const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
10
- const npmCommand = process.env.TASK_HANDOFF_NPM_COMMAND || "npm";
11
-
12
- function usage() {
13
- console.log(`Usage: task-handoff-server <command> [options]
14
-
15
- Commands:
16
- status Show installed version and service state
17
- check [options] Check npm for an available version
18
- update [options] Update from npm and restart services safely
19
-
20
- Update options:
21
- --channel <channel> npm channel: stable, beta, or alpha (default: stable)
22
- --to <version> Install an exact version instead of a channel
23
- --registry <url> Use a specific npm registry
24
- --force Reinstall even when the resolved version is unchanged
25
- `);
26
- }
27
-
28
- function run(command, args, options = {}) {
29
- const result = spawnSync(command, args, { encoding: "utf8", ...options });
30
- if (result.status !== 0) {
31
- const output = [result.stdout, result.stderr].filter(Boolean).join("\n").trim();
32
- throw new Error(`${command} ${args.join(" ")} failed${output ? `:\n${output}` : ""}`);
33
- }
34
- return String(result.stdout || "").trim();
35
- }
36
-
37
- function findGlobalPrefix() {
38
- let current = packageRoot;
39
- while (current !== path.dirname(current)) {
40
- if (path.basename(current) === "node_modules" && path.basename(path.dirname(current)) === "lib") {
41
- return path.dirname(path.dirname(current));
42
- }
43
- current = path.dirname(current);
44
- }
45
- throw new Error(`Cannot determine the npm global prefix from ${packageRoot}.`);
46
- }
47
-
48
- function parseEnvFile(file) {
49
- const values = {};
50
- if (!fs.existsSync(file)) return values;
51
- for (const line of fs.readFileSync(file, "utf8").split(/\r?\n/)) {
52
- if (!line || line.startsWith("#")) continue;
53
- const separator = line.indexOf("=");
54
- if (separator <= 0) continue;
55
- values[line.slice(0, separator)] = line.slice(separator + 1);
56
- }
57
- return values;
58
- }
59
-
60
- function serviceUser() {
61
- const unit = "/etc/systemd/system/task-handoff-node-agent.service";
62
- if (!fs.existsSync(unit)) return "root";
63
- const match = fs.readFileSync(unit, "utf8").match(/^User=(.+)$/m);
64
- return match?.[1] || "root";
65
- }
66
-
67
- function currentInstallOptions() {
68
- const controlPlane = parseEnvFile("/etc/task-handoff/control-plane.env");
69
- const nodeAgent = parseEnvFile("/etc/task-handoff/node-agent.env");
70
- return [
71
- "--service-user", serviceUser(),
72
- "--control-plane-data-dir", controlPlane.TASK_HANDOFF_CONTROL_PLANE_DATA_DIR || "/var/lib/task-handoff/control-plane",
73
- "--node-agent-data-dir", nodeAgent.TASK_HANDOFF_NODE_AGENT_DATA_DIR || "/var/lib/task-handoff/node-agent",
74
- "--control-plane-host", controlPlane.TASK_HANDOFF_CONTROL_PLANE_HOST || "0.0.0.0",
75
- "--control-plane-port", controlPlane.TASK_HANDOFF_CONTROL_PLANE_PORT || "8081",
76
- "--node-agent-host", nodeAgent.TASK_HANDOFF_NODE_AGENT_HOST || "127.0.0.1",
77
- "--node-agent-port", nodeAgent.TASK_HANDOFF_NODE_AGENT_PORT || "8091",
78
- "--node-agent-ipc-path", nodeAgent.TASK_HANDOFF_NODE_AGENT_IPC_PATH || "/run/task-handoff/node-agent.sock",
79
- "--auth-mode", controlPlane.TASK_HANDOFF_CONTROL_PLANE_AUTH_MODE || "password",
80
- ];
81
- }
82
-
83
- function systemctlState(service) {
84
- const result = spawnSync("systemctl", ["is-active", service], { encoding: "utf8" });
85
- return String(result.stdout || "unknown").trim() || "unknown";
86
- }
87
-
88
- function npmVersion(target, registry) {
89
- const args = ["view", `@task-handoff/server@${target}`, "version", "--json"];
90
- if (registry) args.push("--registry", registry);
91
- const value = JSON.parse(run(npmCommand, args));
92
- if (typeof value !== "string") throw new Error(`npm target ${target} did not resolve to one version.`);
93
- return value;
94
- }
95
-
96
- function npmTagForChannel(channel) {
97
- return channel === "stable" ? "latest" : channel;
98
- }
99
-
100
- function waitForSocket(socketPath, timeoutMs = 30000) {
101
- const deadline = Date.now() + timeoutMs;
102
- while (Date.now() < deadline) {
103
- try {
104
- if (fs.statSync(socketPath).isSocket()) return;
105
- } catch {}
106
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250);
107
- }
108
- throw new Error(`Node agent socket was not ready after ${timeoutMs}ms: ${socketPath}`);
109
- }
110
-
111
- function waitForHttp(port, timeoutMs = 30000) {
112
- return new Promise((resolve, reject) => {
113
- const deadline = Date.now() + timeoutMs;
114
- const attempt = () => {
115
- const request = http.get({ host: "127.0.0.1", port, path: "/api/health", timeout: 1000 }, (response) => {
116
- response.resume();
117
- if (response.statusCode === 200) return resolve();
118
- retry();
119
- });
120
- request.on("timeout", () => request.destroy());
121
- request.on("error", retry);
122
- };
123
- const retry = () => {
124
- if (Date.now() >= deadline) return reject(new Error(`Control plane was not healthy on port ${port} after ${timeoutMs}ms.`));
125
- setTimeout(attempt, 250);
126
- };
127
- attempt();
128
- });
129
- }
130
-
131
- function acquireLock() {
132
- const lock = "/run/task-handoff-server-update.lock";
133
- try {
134
- fs.mkdirSync(lock);
135
- } catch (error) {
136
- if (error.code === "EEXIST") throw new Error("Another TaskHandoff server update is already running.");
137
- throw error;
138
- }
139
- return () => fs.rmSync(lock, { recursive: true, force: true });
140
- }
141
-
142
- function parseOptions(args, allowExactVersion) {
143
- let channel = "stable";
144
- let channelExplicit = false;
145
- let exactVersion = "";
146
- let registry = "";
147
- let force = false;
148
- while (args.length) {
149
- const option = args.shift();
150
- if (option === "--channel") {
151
- channel = args.shift() || "";
152
- channelExplicit = true;
153
- }
154
- else if (option === "--to" && allowExactVersion) exactVersion = args.shift() || "";
155
- else if (option === "--registry") registry = args.shift() || "";
156
- else if (option === "--force" && allowExactVersion) force = true;
157
- else throw new Error(`Unknown option: ${option}`);
158
- }
159
- if (!new Set(["stable", "beta", "alpha"]).has(channel)) {
160
- throw new Error("--channel must be stable, beta, or alpha.");
161
- }
162
- if (channelExplicit && exactVersion) throw new Error("Use either --channel or --to, not both.");
163
- if (allowExactVersion && exactVersion && !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(exactVersion)) {
164
- throw new Error("--to must be an exact semantic version.");
165
- }
166
- return { target: exactVersion || npmTagForChannel(channel), channel, registry, force };
167
- }
168
-
169
- async function main() {
170
- const command = process.argv[2];
171
- if (!command || command === "help" || command === "--help" || command === "-h") {
172
- usage();
173
- return;
174
- }
175
- if (command === "status") {
176
- console.log(`Package: @task-handoff/server ${manifest.version}`);
177
- console.log(`Node agent: ${systemctlState("task-handoff-node-agent.service")}`);
178
- console.log(`Control plane: ${systemctlState("task-handoff-control-plane.service")}`);
179
- return;
180
- }
181
- if (command === "check") {
182
- const { target, channel, registry } = parseOptions(process.argv.slice(3), false);
183
- const available = npmVersion(target, registry);
184
- console.log(`Installed: ${manifest.version}`);
185
- console.log(`Available (${channel} channel, npm ${target}): ${available}`);
186
- console.log(available === manifest.version ? "Up to date." : `Update available: task-handoff-server update --to ${available}`);
187
- return;
188
- }
189
- if (command !== "update") throw new Error(`Unknown command: ${command}`);
190
- if (typeof process.getuid === "function" && process.getuid() !== 0) {
191
- throw new Error("Run updates as root so npm and systemd can be updated.");
192
- }
193
- const { target, registry, force } = parseOptions(process.argv.slice(3), true);
194
- const targetVersion = target === manifest.version ? manifest.version : npmVersion(target, registry);
195
- if (targetVersion === manifest.version && !force) {
196
- console.log(`@task-handoff/server ${manifest.version} is already installed.`);
197
- return;
198
- }
199
- const releaseLock = acquireLock();
200
- try {
201
- const prefix = findGlobalPrefix();
202
- const installOptions = currentInstallOptions();
203
- const nodeSocket = installOptions[installOptions.indexOf("--node-agent-ipc-path") + 1];
204
- const controlPlanePort = Number(installOptions[installOptions.indexOf("--control-plane-port") + 1]);
205
- console.log(`Updating @task-handoff/server ${manifest.version} -> ${targetVersion}`);
206
- const npmArgs = ["install", "--global", "--prefix", prefix, `@task-handoff/server@${targetVersion}`];
207
- if (registry) npmArgs.push("--registry", registry);
208
- run(npmCommand, npmArgs, { stdio: "inherit" });
209
- run(path.join(prefix, "bin", "task-handoff-install-server"), installOptions, { stdio: "inherit" });
210
- run("systemctl", ["restart", "task-handoff-node-agent.service"]);
211
- waitForSocket(nodeSocket);
212
- run("systemctl", ["restart", "task-handoff-control-plane.service"]);
213
- await waitForHttp(controlPlanePort);
214
- console.log(`Updated TaskHandoff server to ${targetVersion}.`);
215
- } catch (error) {
216
- console.error(`Update failed. To reinstall the previous version, run: npm install -g @task-handoff/server@${manifest.version}`);
217
- throw error;
218
- } finally {
219
- releaseLock();
220
- }
221
- }
222
-
223
- main().catch((error) => {
224
- console.error(`Error: ${error.message}`);
225
- process.exit(1);
226
- });