@controlvector/cv-agent 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.cjs +400 -19
- package/dist/bundle.cjs.map +4 -4
- package/dist/commands/agent.d.ts.map +1 -1
- package/dist/commands/agent.js +102 -2
- package/dist/commands/agent.js.map +1 -1
- package/dist/commands/deploy-manifest.d.ts +67 -0
- package/dist/commands/deploy-manifest.d.ts.map +1 -0
- package/dist/commands/deploy-manifest.js +211 -0
- package/dist/commands/deploy-manifest.js.map +1 -0
- package/dist/commands/git-safety.d.ts +29 -0
- package/dist/commands/git-safety.d.ts.map +1 -0
- package/dist/commands/git-safety.js +116 -0
- package/dist/commands/git-safety.js.map +1 -0
- package/dist/utils/api.d.ts +15 -1
- package/dist/utils/api.d.ts.map +1 -1
- package/dist/utils/api.js +12 -4
- package/dist/utils/api.js.map +1 -1
- package/dist/utils/config.d.ts +20 -0
- package/dist/utils/config.d.ts.map +1 -1
- package/dist/utils/config.js +15 -0
- package/dist/utils/config.js.map +1 -1
- package/package.json +1 -1
package/dist/bundle.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../node_modules/commander/lib/error.js", "../node_modules/commander/lib/argument.js", "../node_modules/commander/lib/help.js", "../node_modules/commander/lib/option.js", "../node_modules/commander/lib/suggestSimilar.js", "../node_modules/commander/lib/command.js", "../node_modules/commander/index.js", "../node_modules/commander/esm.mjs", "../src/commands/agent.ts", "../node_modules/chalk/source/vendor/ansi-styles/index.js", "../node_modules/chalk/source/vendor/supports-color/index.js", "../node_modules/chalk/source/utilities.js", "../node_modules/chalk/source/index.js", "../src/utils/credentials.ts", "../src/utils/api.ts", "../src/utils/output-parser.ts", "../src/commands/agent-git.ts", "../src/utils/display.ts", "../src/utils/retry.ts", "../src/utils/config.ts", "../src/commands/auth.ts", "../src/commands/remote.ts", "../src/commands/task.ts", "../src/commands/status.ts", "../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.length > 3 && this._name.slice(-3) === '...') {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n", "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(max, helper.subcommandTerm(command).length);\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(max, helper.argumentTerm(argument).length);\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n return `${option.description} (${extraInfo.join(', ')})`;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescripton = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescripton}`;\n }\n return extraDescripton;\n }\n return argument.description;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth || 80;\n const itemIndentWidth = 2;\n const itemSeparatorWidth = 2; // between term and description\n function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(\n fullText,\n helpWidth - itemIndentWidth,\n termWidth + itemSeparatorWidth,\n );\n }\n return term;\n }\n function formatList(textArray) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n }\n\n // Usage\n let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.wrap(commandDescription, helpWidth, 0),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(\n helper.argumentTerm(argument),\n helper.argumentDescription(argument),\n );\n });\n if (argumentList.length > 0) {\n output = output.concat(['Arguments:', formatList(argumentList), '']);\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (optionList.length > 0) {\n output = output.concat(['Options:', formatList(optionList), '']);\n }\n\n if (this.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (globalOptionList.length > 0) {\n output = output.concat([\n 'Global Options:',\n formatList(globalOptionList),\n '',\n ]);\n }\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((cmd) => {\n return formatItem(\n helper.subcommandTerm(cmd),\n helper.subcommandDescription(cmd),\n );\n });\n if (commandList.length > 0) {\n output = output.concat(['Commands:', formatList(commandList), '']);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Wrap the given string to width characters per line, with lines after the first indented.\n * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n *\n * @param {string} str\n * @param {number} width\n * @param {number} indent\n * @param {number} [minColumnWidth=40]\n * @return {string}\n *\n */\n\n wrap(str, width, indent, minColumnWidth = 40) {\n // Full \\s characters, minus the linefeeds.\n const indents =\n ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n if (str.match(manualIndent)) return str;\n // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n const columnWidth = width - indent;\n if (columnWidth < minColumnWidth) return str;\n\n const leadingStr = str.slice(0, indent);\n const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n const indentString = ' '.repeat(indent);\n const zeroWidthSpace = '\\u200B';\n const breaks = `\\\\s${zeroWidthSpace}`;\n // Match line end (so empty lines don't collapse),\n // or as much text as will fit in column, or excess text up to first break.\n const regex = new RegExp(\n `\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,\n 'g',\n );\n const lines = columnText.match(regex) || [];\n return (\n leadingStr +\n lines\n .map((line, i) => {\n if (line === '\\n') return ''; // preserve empty lines\n return (i > 0 ? indentString : '') + line.trimEnd();\n })\n .join('\\n')\n );\n }\n}\n\nexports.Help = Help;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag;\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // Use original very loose parsing to maintain backwards compatibility for now,\n // which allowed for example unintended `-sw, --short-word` [sic].\n const flagParts = flags.split(/[ |,]+/);\n if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))\n shortFlag = flagParts.shift();\n longFlag = flagParts.shift();\n // Add support for lone short flag without significantly changing parsing!\n if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n shortFlag = longFlag;\n longFlag = undefined;\n }\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n", "const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = true;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n\n // see .configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n outputError: (str, write) => write(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n Object.assign(this._outputConfiguration, configuration);\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [fn] - custom argument processing function\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, fn, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof fn === 'function') {\n argument.default(defaultValue).argParser(fn);\n } else {\n argument.default(fn);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument && previousArgument.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n return this;\n }\n\n enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._concatValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch (err) {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' 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 - ${executableDirMessage}`;\n throw new Error(executableMissing);\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise && promise.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent && this.parent.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} argv\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(argv) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n const args = argv.slice();\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n // parse options\n let activeVariadicOption = null;\n while (args.length) {\n const arg = args.shift();\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args);\n break;\n }\n\n if (activeVariadicOption && !maybeOption(arg)) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args.shift();\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (args.length > 0 && !maybeOption(args[0])) {\n value = args.shift();\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option, emit and put back remainder of arg for further processing\n this.emit(`option:${option.name()}`);\n args.unshift(`-${arg.slice(2)}`);\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n if (maybeOption(arg)) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg);\n if (args.length > 0) operands.push(...args);\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg);\n if (args.length > 0) dest.push(...args);\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n if (helper.helpWidth === undefined) {\n helper.helpWidth =\n contextOptions && contextOptions.error\n ? this._outputConfiguration.getErrHelpWidth()\n : this._outputConfiguration.getOutHelpWidth();\n }\n return helper.formatHelp(this, helper);\n }\n\n /**\n * @private\n */\n\n _getHelpContext(contextOptions) {\n contextOptions = contextOptions || {};\n const context = { error: !!contextOptions.error };\n let write;\n if (context.error) {\n write = (arg) => this._outputConfiguration.writeErr(arg);\n } else {\n write = (arg) => this._outputConfiguration.writeOut(arg);\n }\n context.write = contextOptions.write || write;\n context.command = this;\n return context;\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n const context = this._getHelpContext(contextOptions);\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', context));\n this.emit('beforeHelp', context);\n\n let helpInformation = this.helpInformation(context);\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n context.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', context);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', context),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n this._helpOption = this._helpOption ?? undefined; // preserve existing option\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n flags = flags ?? '-h, --help';\n description = description ?? 'display help for command';\n this._helpOption = this.createOption(flags, description);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = process.exitCode || 0;\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\nexports.Command = Command;\n", "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n", "import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n", "/**\n * cva agent command\n *\n * Listens for tasks dispatched via CV-Hub and executes them\n * with Claude Code. The agent registers as an executor, polls for tasks,\n * and reports results back.\n *\n * Two execution modes:\n * --auto-approve: Uses Claude Code -p mode with --allowedTools (proven)\n * Default (relay): Spawns interactive Claude Code, relays permission prompts\n *\n * Usage:\n * cva agent # Start in relay mode\n * cva agent --auto-approve # Start in auto-approve mode\n * cva agent --machine z840-primary # Override machine name\n * cva agent --poll-interval 10 # Check every 10 seconds\n */\n\nimport { Command } from 'commander';\nimport { spawn, execSync, type ChildProcess } from 'node:child_process';\nimport chalk from 'chalk';\nimport {\n readCredentials,\n getMachineName,\n type CVHubCredentials,\n} from '../utils/credentials.js';\nimport {\n registerExecutor,\n resolveRepoId,\n pollForTask,\n startTask,\n completeTask,\n failTask,\n sendHeartbeat,\n sendTaskLog,\n markOffline,\n createTaskPrompt,\n pollPromptResponse,\n postTaskEvent,\n getEventResponse,\n getRedirects,\n} from '../utils/api.js';\nimport { parseClaudeCodeOutput } from '../utils/output-parser.js';\nimport {\n capturePreTaskState,\n capturePostTaskState,\n buildCompletionPayload,\n verifyGitRemote,\n} from './agent-git.js';\nimport {\n formatDuration,\n setTerminalTitle,\n printBanner,\n updateStatusLine,\n} from '../utils/display.js';\nimport { withRetry } from '../utils/retry.js';\nimport { readConfig } from '../utils/config.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type AuthStatus = 'authenticated' | 'expired' | 'not_configured' | 'api_key_fallback';\n\n/** Patterns that indicate Claude Code auth failure */\nexport const AUTH_ERROR_PATTERNS = [\n 'Not logged in',\n 'Please run /login',\n 'authentication required',\n 'unauthorized',\n 'expired token',\n 'not authenticated',\n 'login required',\n];\n\ninterface AgentOptions {\n machine?: string;\n pollInterval: string;\n workingDir: string;\n autoApprove: boolean;\n}\n\ninterface AgentState {\n executorId: string;\n currentTaskId: string | null;\n completedCount: number;\n failedCount: number;\n lastPoll: number;\n lastTaskEnd: number;\n running: boolean;\n authStatus: AuthStatus;\n machineName: string;\n}\n\ninterface Task {\n id: string;\n title: string;\n description?: string;\n task_type: string;\n priority: string;\n status: string;\n input?: { description?: string; context?: string; instructions?: string[]; constraints?: string[] };\n repository_id?: string;\n owner?: string;\n repo?: string;\n branch?: string;\n file_paths?: string[];\n timeout_at?: string;\n metadata?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Claude Code auth check & environment\n// ============================================================================\n\n/**\n * Check if a string contains Claude Code auth error patterns.\n * Exported for testing.\n */\nexport function containsAuthError(text: string): string | null {\n const lower = text.toLowerCase();\n for (const pattern of AUTH_ERROR_PATTERNS) {\n if (lower.includes(pattern.toLowerCase())) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Pre-flight check: verify Claude Code is authenticated.\n * Runs `claude --version` and checks output/stderr for auth errors.\n * Returns the detected auth status.\n */\nexport async function checkClaudeAuth(): Promise<{ status: AuthStatus; error?: string }> {\n try {\n const output = execSync('claude --version 2>&1', {\n encoding: 'utf8',\n timeout: 10_000,\n env: { ...process.env },\n });\n\n const authError = containsAuthError(output);\n if (authError) {\n return { status: 'expired', error: authError };\n }\n\n return { status: 'authenticated' };\n } catch (err: any) {\n const output = (err.stdout || '') + (err.stderr || '') + (err.message || '');\n const authError = containsAuthError(output);\n if (authError) {\n return { status: 'expired', error: authError };\n }\n // Binary not found or other error \u2014 not an auth issue per se\n return { status: 'not_configured', error: output.slice(0, 500) };\n }\n}\n\n/**\n * Build the environment for spawning Claude Code.\n * If an Anthropic API key is configured, inject it as ANTHROPIC_API_KEY.\n */\nexport async function getClaudeEnv(): Promise<{ env: NodeJS.ProcessEnv; usingApiKey: boolean }> {\n const env = { ...process.env };\n let usingApiKey = false;\n\n // Don't override if already set in environment\n if (!env.ANTHROPIC_API_KEY) {\n try {\n const config = await readConfig();\n if (config.anthropic_api_key) {\n env.ANTHROPIC_API_KEY = config.anthropic_api_key;\n usingApiKey = true;\n }\n } catch {\n // Config read failed \u2014 continue without API key\n }\n }\n\n return { env, usingApiKey };\n}\n\n/**\n * Build an actionable auth failure message with machine name and fix instructions.\n */\nexport function buildAuthFailureMessage(\n errorString: string,\n machineName: string,\n hasApiKeyFallback: boolean,\n): string {\n let msg = `CLAUDE_AUTH_REQUIRED: ${errorString}\\n`;\n msg += `Machine: ${machineName}\\n`;\n msg += `Fix: SSH into ${machineName} and run: claude /login\\n`;\n if (!hasApiKeyFallback) {\n msg += `Alternative: Set an API key fallback with: cva auth set-api-key sk-ant-...\\n`;\n }\n return msg;\n}\n\n// ============================================================================\n// Claude Code launcher\n// ============================================================================\n\nfunction buildClaudePrompt(task: Task): string {\n let prompt = '';\n prompt += `You are executing a task dispatched via CV-Hub.\\n\\n`;\n prompt += `## Task: ${task.title}\\n`;\n prompt += `Task ID: ${task.id}\\n`;\n prompt += `Priority: ${task.priority}\\n`;\n\n if (task.branch) prompt += `Branch: ${task.branch}\\n`;\n if (task.file_paths?.length) prompt += `Focus files: ${task.file_paths.join(', ')}\\n`;\n\n prompt += `\\n`;\n\n // Main instructions\n if (task.description) {\n prompt += task.description;\n } else if (task.input?.description) {\n prompt += task.input.description;\n }\n\n if (task.input?.context) {\n prompt += `\\n\\n## Context\\n${task.input.context}`;\n }\n\n if (task.input?.instructions?.length) {\n prompt += `\\n\\n## Instructions\\n`;\n task.input.instructions.forEach((i, idx) => {\n prompt += `${idx + 1}. ${i}\\n`;\n });\n }\n\n if (task.input?.constraints?.length) {\n prompt += `\\n\\n## Constraints\\n`;\n task.input.constraints.forEach(c => {\n prompt += `- ${c}\\n`;\n });\n }\n\n // Git & CV-Hub CLI instructions\n prompt += `\\n\\n## Git & CV-Hub Instructions\\n`;\n prompt += `You have the \\`cv\\` CLI (@controlvector/cv-git) available for all CV-Hub git operations.\\n`;\n prompt += `Use \\`cv\\` instead of raw \\`git\\` commands when interacting with CV-Hub repositories:\\n`;\n prompt += ` cv push # push to CV-Hub\\n`;\n prompt += ` cv pr create --title \"...\" # create pull request\\n`;\n prompt += ` cv issue list # list issues\\n`;\n prompt += ` cv repo info # repo details\\n`;\n prompt += `\\n`;\n prompt += `For standard git operations (commit, branch, diff, log, status), use regular \\`git\\` commands.\\n`;\n if (task.owner && task.repo) {\n prompt += `\\nTarget repository: ${task.owner}/${task.repo}\\n`;\n if (task.branch) prompt += `Target branch: ${task.branch}\\n`;\n }\n prompt += `\\n`;\n prompt += `IMPORTANT: Do NOT run \\`cva\\` commands. The \\`cva\\` binary is the agent daemon that launched you \u2014 calling it would cause recursion.\\n`;\n\n prompt += `\\n\\n---\\n`;\n prompt += `When complete, provide a brief summary of what you accomplished.\\n`;\n\n return prompt;\n}\n\n/** Shared reference to current child process so signal handlers can kill it */\nlet _activeChild: ChildProcess | null = null;\n\n/** Signal handling state */\nlet _sigintCount = 0;\nlet _sigintTimer: ReturnType<typeof setTimeout> | null = null;\nlet _signalHandlerInstalled = false;\n\nfunction installSignalHandlers(\n getState: () => AgentState,\n cleanup: () => Promise<void>,\n): void {\n if (_signalHandlerInstalled) return;\n _signalHandlerInstalled = true;\n\n process.on('SIGINT', async () => {\n if (!_activeChild) {\n console.log('\\n' + chalk.gray('Agent stopped.'));\n await cleanup();\n process.exit(0);\n }\n\n _sigintCount++;\n\n if (_sigintCount === 1) {\n console.log(`\\n${chalk.yellow('!')} Press Ctrl+C again within 3s to abort task.`);\n _sigintTimer = setTimeout(() => { _sigintCount = 0; }, 3000);\n return;\n }\n\n if (_sigintTimer) clearTimeout(_sigintTimer);\n console.log(`\\n${chalk.red('X')} Aborting task...`);\n try { _activeChild.kill('SIGKILL'); } catch {}\n _activeChild = null;\n _sigintCount = 0;\n });\n\n process.on('SIGTERM', async () => {\n console.log(`\\n${chalk.gray('Received SIGTERM, shutting down...')}`);\n if (_activeChild) {\n try { _activeChild.kill('SIGKILL'); } catch {}\n _activeChild = null;\n }\n await cleanup();\n process.exit(0);\n });\n}\n\n// ============================================================================\n// Permission handling\n// ============================================================================\n\n/** Tools to pre-approve when --auto-approve is active */\nconst ALLOWED_TOOLS = [\n 'Bash(*)', 'Read(*)', 'Write(*)', 'Edit(*)',\n 'Glob(*)', 'Grep(*)', 'WebFetch(*)', 'WebSearch(*)',\n 'NotebookEdit(*)', 'TodoWrite(*)',\n];\n\n/** Permission prompt patterns to detect in relay mode */\nconst PERMISSION_PATTERNS = [\n /Allow .+ to .+\\? \\(y\\/n\\)/,\n /Do you want to proceed\\? \\(y\\/n\\)/,\n /\\? \\(y\\/n\\)/,\n];\n\n// ============================================================================\n// Auto-approve mode launcher (proven, -p + --allowedTools)\n// ============================================================================\n\n/** Max output buffer size (200KB) \u2014 truncate to last 200KB if exceeded */\nconst MAX_OUTPUT_BYTES = 200 * 1024;\n\n/** Max size for output_final event content (50KB) */\nconst MAX_OUTPUT_FINAL_BYTES = 50 * 1024;\n\n/** Interval (in bytes) at which to post progress events with output chunks */\nconst OUTPUT_PROGRESS_INTERVAL = 4096;\n\nasync function launchAutoApproveMode(\n prompt: string,\n options: {\n cwd: string;\n creds?: CVHubCredentials;\n taskId?: string;\n executorId?: string;\n spawnEnv?: NodeJS.ProcessEnv;\n machineName?: string;\n },\n): Promise<{ exitCode: number; stderr: string; output: string; authFailure?: boolean }> {\n // Use a stable session ID so we can --continue if a question needs follow-up\n const sessionId = options.taskId\n ? options.taskId.replace(/-/g, '').slice(0, 32).padEnd(32, '0')\n .replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')\n : undefined;\n const pendingQuestionIds: string[] = [];\n\n let fullOutput = '';\n let lastProgressBytes = 0;\n\n const runOnce = (inputPrompt: string, isContinue: boolean): Promise<{ exitCode: number; stderr: string; output: string; authFailure: boolean }> => {\n return new Promise((resolve, reject) => {\n const args: string[] = isContinue\n ? ['-p', inputPrompt, '--continue', '--allowedTools', ...ALLOWED_TOOLS]\n : ['-p', inputPrompt, '--allowedTools', ...ALLOWED_TOOLS];\n\n if (sessionId && !isContinue) {\n args.push('--session-id', sessionId);\n }\n\n const child = spawn('claude', args, {\n cwd: options.cwd,\n stdio: ['inherit', 'pipe', 'pipe'],\n env: options.spawnEnv || { ...process.env },\n });\n\n _activeChild = child;\n let stderr = '';\n let lineBuffer = '';\n let authFailure = false;\n const spawnTime = Date.now();\n\n child.stdout?.on('data', (data: Buffer) => {\n const text = data.toString();\n process.stdout.write(data);\n\n // Accumulate full output (capped at MAX_OUTPUT_BYTES)\n fullOutput += text;\n if (fullOutput.length > MAX_OUTPUT_BYTES) {\n fullOutput = fullOutput.slice(-MAX_OUTPUT_BYTES);\n }\n\n // Early exit detection: check first 10s for auth errors\n if (Date.now() - spawnTime < 10_000) {\n const authError = containsAuthError(fullOutput + stderr);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure detected: \"${authError}\"`);\n console.log(chalk.yellow(` Killing process \u2014 it won't recover without re-authentication.`));\n if (options.machineName) {\n console.log(chalk.cyan(` Fix: SSH into ${options.machineName} and run: claude /login`));\n }\n try { child.kill('SIGTERM'); } catch {}\n return;\n }\n }\n\n if (options.creds && options.taskId) {\n lineBuffer += text;\n const lines = lineBuffer.split('\\n');\n lineBuffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const event = parseClaudeCodeOutput(line);\n if (event) {\n postTaskEvent(options.creds, options.taskId, {\n event_type: event.eventType,\n content: event.content,\n needs_response: event.needsResponse,\n }).then((created) => {\n if (event.needsResponse && created?.id) {\n pendingQuestionIds.push(created.id);\n }\n }).catch(() => {});\n }\n }\n\n // Post periodic progress with output chunk\n if (fullOutput.length - lastProgressBytes >= OUTPUT_PROGRESS_INTERVAL) {\n const chunk = fullOutput.slice(lastProgressBytes).slice(-OUTPUT_PROGRESS_INTERVAL);\n lastProgressBytes = fullOutput.length;\n if (options.executorId) {\n sendTaskLog(options.creds!, options.executorId, options.taskId!, 'progress',\n 'Claude Code output', { output_chunk: chunk }).catch(() => {});\n }\n // Also post as output event for cv_task_summary/stream visibility\n postTaskEvent(options.creds!, options.taskId!, {\n event_type: 'output',\n content: { chunk, byte_offset: lastProgressBytes },\n }).catch(() => {});\n }\n }\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n const text = data.toString();\n stderr += text;\n process.stderr.write(data);\n\n // Early exit detection on stderr too\n if (Date.now() - spawnTime < 10_000 && !authFailure) {\n const authError = containsAuthError(text);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure (stderr): \"${authError}\"`);\n try { child.kill('SIGTERM'); } catch {}\n }\n }\n });\n\n child.on('close', (code, signal) => {\n _activeChild = null;\n resolve({\n exitCode: signal === 'SIGKILL' ? 137 : (code ?? 1),\n stderr, output: fullOutput,\n authFailure,\n });\n });\n\n child.on('error', (err) => {\n _activeChild = null;\n reject(err);\n });\n });\n };\n\n // Initial run\n let result = await runOnce(prompt, false);\n\n // If there were unanswered questions and the task isn't aborted,\n // attempt to continue with responses (up to 3 follow-ups)\n if (options.creds && options.taskId && result.exitCode === 0) {\n let followUps = 0;\n while (pendingQuestionIds.length > 0 && followUps < 3) {\n const questionId = pendingQuestionIds.shift()!;\n console.log(chalk.gray(` [auto-approve] Waiting for planner response to question...`));\n\n const response = await pollForEventResponse(\n options.creds, options.taskId, questionId, 300_000,\n );\n\n if (response) {\n const responseText = typeof response === 'string' ? response : JSON.stringify(response);\n console.log(chalk.gray(` [auto-approve] Planner responded, continuing with --continue`));\n result = await runOnce(responseText, true);\n followUps++;\n } else {\n console.log(chalk.yellow(` [auto-approve] No response received, continuing without.`));\n break;\n }\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Relay mode launcher (interactive, permission prompts relayed to CV-Hub)\n// ============================================================================\n\nasync function launchRelayMode(\n prompt: string,\n options: {\n cwd: string;\n creds: CVHubCredentials;\n executorId: string;\n taskId: string;\n spawnEnv?: NodeJS.ProcessEnv;\n machineName?: string;\n },\n): Promise<{ exitCode: number; stderr: string; output: string; authFailure?: boolean }> {\n return new Promise((resolve, reject) => {\n // Spawn Claude Code in interactive mode (no -p flag)\n const child = spawn('claude', [], {\n cwd: options.cwd,\n stdio: ['pipe', 'pipe', 'pipe'],\n env: options.spawnEnv || { ...process.env },\n });\n\n _activeChild = child;\n let stderr = '';\n let stdoutBuffer = '';\n let fullOutput = '';\n let lastProgressBytes = 0;\n let authFailure = false;\n const spawnTime = Date.now();\n\n // Send the task prompt as initial input\n child.stdin?.write(prompt + '\\n');\n\n let lastRedirectCheck = Date.now();\n let lineBuffer = '';\n\n // Tee stdout to terminal while scanning for permission patterns + structured markers\n child.stdout?.on('data', async (data: Buffer) => {\n const text = data.toString();\n process.stdout.write(data); // Tee to terminal\n stdoutBuffer += text;\n\n // Accumulate full output (capped at MAX_OUTPUT_BYTES)\n fullOutput += text;\n if (fullOutput.length > MAX_OUTPUT_BYTES) {\n fullOutput = fullOutput.slice(-MAX_OUTPUT_BYTES);\n }\n\n // Early exit detection: check first 10s for auth errors\n if (Date.now() - spawnTime < 10_000 && !authFailure) {\n const authError = containsAuthError(fullOutput + stderr);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure detected: \"${authError}\"`);\n try { child.kill('SIGTERM'); } catch {}\n return;\n }\n }\n\n // Parse line-by-line for structured markers\n lineBuffer += text;\n const lines = lineBuffer.split('\\n');\n lineBuffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const event = parseClaudeCodeOutput(line);\n if (event) {\n try {\n const created = await postTaskEvent(options.creds, options.taskId, {\n event_type: event.eventType,\n content: event.content,\n needs_response: event.needsResponse,\n });\n\n // If question, wait for response via task events\n if (event.needsResponse && created?.id) {\n console.log(chalk.gray(` [stream] Question detected, waiting for planner response...`));\n const response = await pollForEventResponse(\n options.creds, options.taskId, created.id, 300_000,\n );\n if (response) {\n const responseText = typeof response === 'string' ? response : JSON.stringify(response);\n child.stdin?.write(responseText + '\\n');\n console.log(chalk.gray(` [stream] Planner responded.`));\n } else {\n child.stdin?.write('[No response received within timeout. Continue with your best judgment.]\\n');\n console.log(chalk.yellow(` [stream] Question timed out.`));\n }\n }\n } catch {\n // Non-fatal: don't block execution\n }\n }\n }\n\n // Post periodic progress with output chunk\n if (fullOutput.length - lastProgressBytes >= OUTPUT_PROGRESS_INTERVAL) {\n const chunk = fullOutput.slice(lastProgressBytes).slice(-OUTPUT_PROGRESS_INTERVAL);\n lastProgressBytes = fullOutput.length;\n sendTaskLog(options.creds, options.executorId, options.taskId, 'progress',\n 'Claude Code output', { output_chunk: chunk }).catch(() => {});\n // Also post as output event for cv_task_summary/stream visibility\n postTaskEvent(options.creds, options.taskId, {\n event_type: 'output',\n content: { chunk, byte_offset: lastProgressBytes },\n }).catch(() => {});\n }\n\n // Periodic redirect check (every 10 seconds)\n if (Date.now() - lastRedirectCheck > 10_000) {\n try {\n const redirects = await getRedirects(\n options.creds, options.taskId,\n new Date(lastRedirectCheck).toISOString(),\n );\n for (const redirect of redirects) {\n const instruction = redirect.content?.instruction;\n if (instruction) {\n child.stdin?.write(`\\n[REDIRECT FROM PLANNER]: ${instruction}\\n`);\n console.log(chalk.gray(` [stream] Redirect received from planner.`));\n }\n }\n } catch {\n // Non-fatal\n }\n lastRedirectCheck = Date.now();\n }\n\n // Check for permission prompts (existing relay logic)\n for (const pattern of PERMISSION_PATTERNS) {\n const match = stdoutBuffer.match(pattern);\n if (match) {\n const promptText = match[0];\n stdoutBuffer = ''; // Reset buffer after match\n\n try {\n await sendTaskLog(\n options.creds,\n options.executorId,\n options.taskId,\n 'info',\n `Permission prompt: ${promptText}`,\n { prompt_text: promptText },\n );\n\n const { prompt_id } = await createTaskPrompt(\n options.creds,\n options.executorId,\n options.taskId,\n promptText,\n 'approval',\n ['y', 'n'],\n );\n\n // Also emit as approval_request event\n postTaskEvent(options.creds, options.taskId, {\n event_type: 'approval_request',\n content: { prompt_text: promptText },\n needs_response: true,\n }).catch(() => {});\n\n const timeoutMs = 5 * 60 * 1000;\n const startPoll = Date.now();\n let answered = false;\n\n while (Date.now() - startPoll < timeoutMs) {\n await new Promise(r => setTimeout(r, 2000));\n\n try {\n const { response } = await pollPromptResponse(\n options.creds,\n options.executorId,\n options.taskId,\n prompt_id,\n );\n\n if (response !== null) {\n const answer = response.toLowerCase().startsWith('y') ? 'y' : 'n';\n child.stdin?.write(answer + '\\n');\n answered = true;\n console.log(chalk.gray(` [relay] User responded: ${answer}`));\n break;\n }\n } catch {\n // Poll error \u2014 continue\n }\n }\n\n if (!answered) {\n child.stdin?.write('n\\n');\n console.log(chalk.yellow(` [relay] Prompt timed out, denying.`));\n }\n } catch (err: any) {\n child.stdin?.write('n\\n');\n console.log(chalk.yellow(` [relay] Prompt relay error: ${err.message}, denying.`));\n }\n\n break;\n }\n }\n\n // Keep buffer manageable (only last 2KB)\n if (stdoutBuffer.length > 2048) {\n stdoutBuffer = stdoutBuffer.slice(-1024);\n }\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n const text = data.toString();\n stderr += text;\n process.stderr.write(data);\n\n // Early exit detection on stderr\n if (Date.now() - spawnTime < 10_000 && !authFailure) {\n const authError = containsAuthError(text);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure (stderr): \"${authError}\"`);\n try { child.kill('SIGTERM'); } catch {}\n }\n }\n });\n\n child.on('close', (code, signal) => {\n _activeChild = null;\n if (signal === 'SIGKILL') {\n resolve({ exitCode: 137, stderr, output: fullOutput, authFailure });\n } else {\n resolve({ exitCode: code ?? 1, stderr, output: fullOutput, authFailure });\n }\n });\n\n child.on('error', (err) => {\n _activeChild = null;\n reject(err);\n });\n });\n}\n\n// ============================================================================\n// Event response polling\n// ============================================================================\n\nasync function pollForEventResponse(\n creds: CVHubCredentials,\n taskId: string,\n eventId: string,\n timeoutMs: number,\n): Promise<unknown | null> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n await new Promise(r => setTimeout(r, 3000));\n try {\n const result = await getEventResponse(creds, taskId, eventId);\n if (result.response !== null) {\n return result.response;\n }\n } catch {\n // Continue polling\n }\n }\n return null;\n}\n\n// ============================================================================\n// Self-update handler\n// ============================================================================\n\nasync function handleSelfUpdate(\n task: Task,\n state: AgentState,\n creds: CVHubCredentials,\n): Promise<void> {\n const startTime = Date.now();\n try {\n await startTask(creds, state.executorId, task.id);\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle', 'Self-update started');\n\n const source = (task.input?.description || task.description || 'npm').trim();\n let output = '';\n\n if (source === 'npm' || source.startsWith('npm:')) {\n const pkg = source === 'npm' ? '@controlvector/cv-agent@latest' : source.replace('npm:', '');\n output = execSync(`npm install -g ${pkg} 2>&1`, { encoding: 'utf8', timeout: 120_000 });\n } else if (source.startsWith('git:')) {\n const repoPath = source.replace('git:', '');\n output = execSync(`cd ${repoPath} && git pull && npm install && npm run build && npm link 2>&1`, {\n encoding: 'utf8', timeout: 300_000,\n });\n } else {\n // Default: try npm\n output = execSync(`npm install -g @controlvector/cv-agent@latest 2>&1`, { encoding: 'utf8', timeout: 120_000 });\n }\n\n let newVersion = 'unknown';\n try {\n newVersion = execSync('cva --version 2>/dev/null || echo unknown', { encoding: 'utf8' }).trim();\n } catch {}\n\n // Post output as event so planner can see it\n postTaskEvent(creds, task.id, {\n event_type: 'output_final',\n content: { output: output.slice(-10000), new_version: newVersion },\n }).catch(() => {});\n\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n `Self-update completed. New version: ${newVersion}`, { output: output.slice(-5000) }, 100);\n\n await completeTask(creds, state.executorId, task.id, {\n summary: `Updated to ${newVersion}`,\n exit_code: 0,\n stats: { duration_seconds: Math.round((Date.now() - startTime) / 1000) },\n });\n state.completedCount++;\n\n // Restart if requested\n if (task.input?.constraints?.includes('restart')) {\n console.log(chalk.yellow('Restarting agent with updated binary...'));\n const args = process.argv.slice(1).join(' ');\n execSync(`nohup cva ${args} > /tmp/cva-restart.log 2>&1 &`, { stdio: 'ignore' });\n process.exit(0);\n }\n } catch (err: any) {\n sendTaskLog(creds, state.executorId, task.id, 'error', `Self-update failed: ${err.message}`);\n try { await failTask(creds, state.executorId, task.id, err.message); } catch {}\n state.failedCount++;\n } finally {\n state.currentTaskId = null;\n state.lastTaskEnd = Date.now();\n }\n}\n\n// ============================================================================\n// Main agent loop\n// ============================================================================\n\nasync function runAgent(options: AgentOptions): Promise<void> {\n const creds = await readCredentials();\n\n if (!creds.CV_HUB_API) {\n creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n }\n\n if (!creds.CV_HUB_PAT) {\n console.log();\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n console.log();\n console.log(chalk.bold('Quick setup:'));\n console.log(` ${chalk.cyan('cva auth login')} # Authenticate`);\n console.log(` ${chalk.cyan('cd ~/project/my-project')} # Go to your project`);\n console.log(` ${chalk.cyan('cva agent')} # Start listening`);\n console.log();\n process.exit(1);\n }\n\n // Claude Code check (binary + auth pre-flight)\n try {\n execSync('claude --version', { stdio: 'pipe', timeout: 5000 });\n } catch {\n console.log();\n console.log(chalk.red('Claude Code CLI not found.') + ' Install it first:');\n console.log(` ${chalk.cyan('npm install -g @anthropic-ai/claude-code')}`);\n console.log();\n process.exit(1);\n }\n\n // Pre-flight auth check\n const { env: claudeEnv, usingApiKey } = await getClaudeEnv();\n const authCheck = await checkClaudeAuth();\n let currentAuthStatus: AuthStatus = authCheck.status;\n\n if (authCheck.status === 'expired') {\n if (usingApiKey) {\n console.log(chalk.yellow('!') + ' Claude Code OAuth expired, but API key fallback is configured.');\n currentAuthStatus = 'api_key_fallback';\n } else {\n console.log();\n console.log(chalk.red('Claude Code auth expired: ') + chalk.yellow(authCheck.error || 'unknown'));\n console.log(` Fix: Run ${chalk.cyan('claude /login')} to re-authenticate.`);\n console.log(` Alternative: ${chalk.cyan('cva auth set-api-key sk-ant-...')} for API key fallback.`);\n console.log();\n console.log(chalk.gray('Agent will start but pause task claims until auth is resolved.'));\n console.log();\n }\n } else if (usingApiKey) {\n console.log(chalk.gray(' Using Anthropic API key from config as fallback.'));\n currentAuthStatus = 'api_key_fallback';\n }\n\n // cv-git check (warn, don't block)\n try {\n execSync('cv --version', { stdio: 'pipe', timeout: 5000 });\n } catch {\n console.log(chalk.yellow('!') + ' cv-git CLI not found. Claude Code will fall back to raw git commands.');\n console.log(` Install it: ${chalk.cyan('npm install -g @controlvector/cv-git')}`);\n console.log();\n }\n\n const machineName = options.machine || await getMachineName();\n const pollInterval = Math.max(3, parseInt(options.pollInterval, 10)) * 1000;\n const workingDir = options.workingDir === '.' ? process.cwd() : options.workingDir;\n\n if (!options.machine) {\n const credCheck = await readCredentials();\n if (!credCheck.CV_HUB_MACHINE_NAME) {\n console.log();\n console.log(chalk.yellow('!') + ` No machine name set. Registering as \"${chalk.bold(machineName)}\".`);\n console.log(chalk.gray(` Use --machine <name> to override.`));\n console.log();\n }\n }\n\n // Auto-detect CV-Hub repository from git remote\n let detectedRepoId: string | undefined;\n try {\n const remoteUrl = execSync('git remote get-url origin 2>/dev/null', {\n cwd: workingDir,\n encoding: 'utf8',\n timeout: 5000,\n }).trim();\n\n const cvHubMatch = remoteUrl.match(\n /git\\.hub\\.controlvector\\.io[:/]([^/]+)\\/([^/.]+)/\n );\n\n if (cvHubMatch) {\n const [, repoOwner, repoSlug] = cvHubMatch;\n try {\n const repoData = await resolveRepoId(creds, repoOwner, repoSlug);\n if (repoData?.id) {\n detectedRepoId = repoData.id;\n console.log(chalk.gray(` Repo: ${repoOwner}/${repoSlug}`));\n }\n } catch {\n // API call failed \u2014 register without repo binding\n }\n }\n } catch {\n // Not a git repo or no origin remote \u2014 that's fine\n }\n\n // Register executor\n const executor = await withRetry(\n () => registerExecutor(creds, machineName, workingDir, detectedRepoId),\n 'Executor registration',\n );\n\n // Display banner\n const mode = options.autoApprove ? 'auto-approve' : 'relay';\n console.log();\n console.log(chalk.bold('CVA \u2014 CV-Hub Agent'));\n console.log(` Machine: ${chalk.cyan(machineName)}`);\n console.log(` Executor: ${chalk.gray(executor.id)}`);\n console.log(` API: ${chalk.gray(creds.CV_HUB_API)}`);\n console.log(` Dir: ${chalk.gray(workingDir)}`);\n console.log(` Polling: every ${options.pollInterval}s`);\n console.log(` Mode: ${chalk.cyan(mode)}`);\n console.log(` Ctrl+C to stop`);\n console.log();\n console.log(chalk.cyan('Listening for tasks...'));\n console.log();\n\n const state: AgentState = {\n executorId: executor.id,\n currentTaskId: null,\n completedCount: 0,\n failedCount: 0,\n lastPoll: Date.now(),\n lastTaskEnd: Date.now(),\n running: true,\n authStatus: currentAuthStatus,\n machineName,\n };\n\n installSignalHandlers(\n () => state,\n async () => {\n state.running = false;\n await markOffline(creds, state.executorId);\n },\n );\n\n // Main loop\n while (state.running) {\n try {\n // If auth is expired (no fallback), re-check periodically instead of claiming tasks\n if (state.authStatus === 'expired') {\n const recheck = await checkClaudeAuth();\n if (recheck.status === 'authenticated') {\n state.authStatus = 'authenticated';\n console.log(`\\n${chalk.green('\u2713')} Claude Code auth restored. Resuming task claims.`);\n } else {\n // Still expired \u2014 heartbeat but don't poll for tasks\n sendHeartbeat(creds, state.executorId, undefined, undefined, state.authStatus).catch(() => {});\n await new Promise(r => setTimeout(r, pollInterval));\n continue;\n }\n }\n\n const task = await withRetry(\n () => pollForTask(creds, state.executorId),\n 'Task poll',\n );\n state.lastPoll = Date.now();\n\n if (task) {\n await executeTask(task, state, creds, options, claudeEnv);\n } else {\n updateStatusLine(\n formatDuration(Date.now() - state.lastTaskEnd),\n formatDuration(Date.now() - state.lastPoll),\n state.completedCount,\n state.failedCount,\n );\n }\n } catch (err: any) {\n console.log(`\\n${chalk.red('!')} Error: ${err.message}`);\n }\n\n await new Promise(r => setTimeout(r, pollInterval));\n }\n}\n\nasync function executeTask(\n task: Task,\n state: AgentState,\n creds: CVHubCredentials,\n options: AgentOptions,\n claudeEnv?: NodeJS.ProcessEnv,\n): Promise<void> {\n const startTime = Date.now();\n state.currentTaskId = task.id;\n\n // Handle system update tasks \u2014 no Claude Code, just self-update\n if (task.task_type === '_system_update') {\n await handleSelfUpdate(task, state, creds);\n return;\n }\n\n // Clear status line\n process.stdout.write('\\r\\x1b[K');\n\n // Task received\n console.log(`\uD83D\uDCE5 ${chalk.bold.cyan('RECEIVED')} \u2014 Task: ${task.title} (${task.priority})`);\n\n // Task header\n console.log(chalk.bold('\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510'));\n console.log(chalk.bold(`\u2502 Task: ${(task.title || '').substring(0, 53).padEnd(53)}\u2502`));\n console.log(chalk.bold(`\u2502 ID: ${task.id.padEnd(55)}\u2502`));\n console.log(chalk.bold(`\u2502 Priority: ${task.priority.padEnd(49)}\u2502`));\n console.log(chalk.bold('\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518'));\n console.log();\n\n // Mark task as running\n try {\n await startTask(creds, state.executorId, task.id);\n setTerminalTitle(`cva: ${task.title} (starting...)`);\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle', 'Task started, launching Claude Code');\n } catch (err: any) {\n console.log(chalk.red(`Failed to start task: ${err.message}`));\n state.currentTaskId = null;\n return;\n }\n\n // Heartbeat timer\n const heartbeatTimer = setInterval(async () => {\n try {\n const elapsed = formatDuration(Date.now() - startTime);\n setTerminalTitle(`cva: ${task.title} (${elapsed})`);\n await sendHeartbeat(creds, state.executorId, task.id, `Claude Code running (${elapsed} elapsed)`, state.authStatus);\n } catch {}\n }, 30_000);\n\n // Timeout timer\n let timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n if (task.timeout_at) {\n const timeoutMs = new Date(task.timeout_at).getTime() - Date.now();\n if (timeoutMs > 0) {\n timeoutTimer = setTimeout(() => {\n console.log(`\\n${chalk.red('Timeout')} Task timed out after ${formatDuration(timeoutMs)}`);\n }, timeoutMs);\n }\n }\n\n // Capture pre-task git state\n const preGitState = capturePreTaskState(options.workingDir);\n\n // Verify/fix git remote\n const gitHost = (creds.CV_HUB_API || 'https://api.hub.controlvector.io')\n .replace(/^https?:\\/\\//, '')\n .replace(/^api\\./, 'git.');\n const remoteInfo = verifyGitRemote(options.workingDir, task, gitHost);\n if (remoteInfo) {\n console.log(chalk.gray(` Git remote: ${remoteInfo.remoteName} -> ${remoteInfo.remoteUrl}`));\n }\n\n // Build prompt and launch\n const prompt = buildClaudePrompt(task);\n\n try {\n const mode = options.autoApprove ? 'auto-approve' : 'relay';\n console.log(`\uD83D\uDE80 ${chalk.bold.green('RUNNING')} \u2014 Launching Claude Code (${mode})...`);\n if (options.autoApprove) {\n console.log(chalk.gray(' Allowed tools: ') + ALLOWED_TOOLS.join(', '));\n }\n console.log(chalk.gray('-'.repeat(60)));\n\n let result: { exitCode: number; stderr: string; output: string; authFailure?: boolean };\n\n if (options.autoApprove) {\n result = await launchAutoApproveMode(prompt, {\n cwd: options.workingDir,\n creds,\n taskId: task.id,\n executorId: state.executorId,\n spawnEnv: claudeEnv,\n machineName: state.machineName,\n });\n } else {\n result = await launchRelayMode(prompt, {\n cwd: options.workingDir,\n creds,\n executorId: state.executorId,\n taskId: task.id,\n spawnEnv: claudeEnv,\n machineName: state.machineName,\n });\n }\n\n console.log(chalk.gray('\\n' + '-'.repeat(60)));\n\n // Capture post-task git state\n const postGitState = capturePostTaskState(options.workingDir, preGitState);\n const payload = buildCompletionPayload(result.exitCode, preGitState, postGitState, startTime, result.output);\n const elapsed = formatDuration(Date.now() - startTime);\n const allChangedFiles = [\n ...postGitState.filesAdded,\n ...postGitState.filesModified,\n ...postGitState.filesDeleted,\n ];\n\n // Emit completion event via task events\n postTaskEvent(creds, task.id, {\n event_type: 'completed',\n content: {\n exit_code: result.exitCode,\n duration_seconds: Math.round((Date.now() - startTime) / 1000),\n files_changed: allChangedFiles.length,\n },\n }).catch(() => {});\n\n if (result.exitCode === 0) {\n if (allChangedFiles.length > 0) {\n sendTaskLog(creds, state.executorId, task.id, 'git',\n `${allChangedFiles.length} file(s) changed (+${postGitState.linesAdded}/-${postGitState.linesDeleted})`,\n { added: postGitState.filesAdded.slice(0, 10), modified: postGitState.filesModified.slice(0, 10), deleted: postGitState.filesDeleted.slice(0, 10) });\n }\n\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n `Claude Code completed successfully (${elapsed})`, undefined, 100);\n\n console.log();\n console.log(`\u2705 ${chalk.bold.green('COMPLETED')} \u2014 Duration: ${elapsed}`);\n printBanner('COMPLETED', elapsed, allChangedFiles, postGitState.headSha);\n\n // Post final output as event for planner visibility\n postTaskEvent(creds, task.id, {\n event_type: 'output_final',\n content: {\n output: result.output.slice(-MAX_OUTPUT_FINAL_BYTES),\n exit_code: result.exitCode,\n duration_seconds: Math.round((Date.now() - startTime) / 1000),\n },\n }).catch(() => {});\n\n await withRetry(\n () => completeTask(creds, state.executorId, task.id, payload as unknown as Record<string, unknown>),\n 'Report completion',\n );\n state.completedCount++;\n\n console.log(chalk.gray(' Reported to CV-Hub.'));\n } else if (result.exitCode === 137) {\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n 'Task aborted by user (Ctrl+C)');\n\n console.log();\n console.log(`\u23F9 ${chalk.bold.yellow('ABORTED')} \u2014 Duration: ${elapsed}`);\n printBanner('ABORTED', elapsed, [], null);\n\n try {\n await failTask(creds, state.executorId, task.id, 'Aborted by user (Ctrl+C)');\n } catch {}\n state.failedCount++;\n } else if (result.authFailure) {\n // Auth failure \u2014 produce actionable error message\n const authErrorStr = containsAuthError(result.output + result.stderr) || 'auth failure';\n const hasApiKey = !!(claudeEnv?.ANTHROPIC_API_KEY);\n const authMsg = buildAuthFailureMessage(authErrorStr, state.machineName, hasApiKey);\n\n sendTaskLog(creds, state.executorId, task.id, 'error', authMsg);\n\n console.log();\n console.log(`\uD83D\uDD11 ${chalk.bold.red('AUTH FAILED')} \u2014 Claude Code is not authenticated`);\n console.log(chalk.yellow(` ${authMsg.replace(/\\n/g, '\\n ')}`));\n\n // Emit specific auth failure event\n postTaskEvent(creds, task.id, {\n event_type: 'auth_failure',\n content: {\n error: authErrorStr,\n machine: state.machineName,\n fix_command: `claude /login`,\n api_key_configured: hasApiKey,\n },\n }).catch(() => {});\n\n await withRetry(\n () => failTask(creds, state.executorId, task.id, authMsg),\n 'Report auth failure',\n );\n state.failedCount++;\n\n // Set auth status to expired so we stop claiming tasks\n state.authStatus = 'expired';\n console.log(chalk.yellow(' Pausing task claims until auth is restored.'));\n } else {\n const stderrTail = result.stderr.trim().slice(-500);\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n `Claude Code exited with code ${result.exitCode} (${elapsed})`,\n stderrTail ? { stderr_tail: stderrTail } : undefined);\n\n console.log();\n console.log(`\u274C ${chalk.bold.red('FAILED')} \u2014 Duration: ${elapsed} (exit code ${result.exitCode})`);\n printBanner('FAILED', elapsed, allChangedFiles, postGitState.headSha);\n\n const errorDetail = result.stderr.trim()\n ? `${result.stderr.trim().slice(-1500)}\\n\\nExit code ${result.exitCode} after ${elapsed}.`\n : `Claude Code exited with code ${result.exitCode} after ${elapsed}.`;\n\n await withRetry(\n () => failTask(creds, state.executorId, task.id, errorDetail),\n 'Report failure',\n );\n state.failedCount++;\n }\n } catch (err: any) {\n console.log(`\\n${chalk.red('!')} Task error: ${err.message}`);\n\n sendTaskLog(creds, state.executorId, task.id, 'error',\n `Agent error: ${err.message}`);\n\n try {\n await failTask(creds, state.executorId, task.id, err.message);\n } catch {}\n state.failedCount++;\n } finally {\n clearInterval(heartbeatTimer);\n if (timeoutTimer) clearTimeout(timeoutTimer);\n state.currentTaskId = null;\n state.lastTaskEnd = Date.now();\n }\n\n setTerminalTitle('cva: listening...');\n console.log();\n console.log(chalk.cyan('Listening for tasks...'));\n console.log();\n}\n\n// ============================================================================\n// Command definition\n// ============================================================================\n\nexport function agentCommand(): Command {\n const cmd = new Command('agent');\n cmd.description('Listen for tasks dispatched via CV-Hub and execute them with Claude Code');\n\n cmd.option('--machine <name>', 'Override auto-detected machine name');\n cmd.option('--poll-interval <seconds>', 'How often to check for tasks, minimum 3 (default: 5)', '5');\n cmd.option('--working-dir <path>', 'Working directory for Claude Code (default: current directory)', '.');\n cmd.option('--auto-approve', 'Pre-approve all tool permissions (uses -p mode)', false);\n\n cmd.action(async (opts: AgentOptions) => {\n await runAgent(opts);\n });\n\n return cmd;\n}\n", "const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n", "import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-ghostty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'wezterm') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n", "// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n", "import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` \u2192 `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n", "/**\n * CV-Hub credentials file utilities\n *\n * Reads/writes the CV-Hub credentials file (~/.config/cv-hub/credentials)\n * which uses simple KEY=VALUE format (sourced by shell hooks).\n */\n\nimport { promises as fs } from 'fs';\nimport { homedir } from 'os';\nimport { join, dirname } from 'path';\nimport * as os from 'os';\n\n/** Standard paths to search for credentials, in priority order */\nexport const CREDENTIAL_PATHS = [\n join(homedir(), '.config', 'cv-hub', 'credentials'),\n '/root/.config/cv-hub/credentials',\n];\n\nexport interface CVHubCredentials {\n CV_HUB_PAT?: string;\n CV_HUB_API?: string;\n CV_HUB_MACHINE_NAME?: string;\n CV_HUB_ORG_OVERRIDE?: string;\n CV_HUB_DEBUG?: string;\n [key: string]: string | undefined;\n}\n\n/**\n * Find the first existing credentials file path\n */\nexport async function findCredentialFile(): Promise<string | null> {\n for (const p of CREDENTIAL_PATHS) {\n try {\n await fs.access(p);\n return p;\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/**\n * Read and parse the CV-Hub credentials file.\n * Parses KEY=VALUE lines, ignoring comments (#) and empty lines.\n */\nexport async function readCredentials(): Promise<CVHubCredentials> {\n const credPath = await findCredentialFile();\n if (!credPath) {\n return {};\n }\n\n try {\n const content = await fs.readFile(credPath, 'utf-8');\n return parseCredentials(content);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse credential file content into key-value pairs.\n */\nexport function parseCredentials(content: string): CVHubCredentials {\n const result: CVHubCredentials = {};\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const eqIdx = trimmed.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = trimmed.slice(0, eqIdx).trim();\n const value = trimmed.slice(eqIdx + 1).trim();\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Write or update a single field in the credentials file.\n * Preserves existing fields, comments, and ordering.\n * If the file doesn't exist, creates it with secure permissions.\n */\nexport async function writeCredentialField(key: string, value: string): Promise<string> {\n let credPath = await findCredentialFile();\n\n if (!credPath) {\n // Create the default credentials file\n credPath = CREDENTIAL_PATHS[0];\n await fs.mkdir(dirname(credPath), { recursive: true });\n await fs.writeFile(credPath, `${key}=${value}\\n`, { mode: 0o600 });\n return credPath;\n }\n\n let content: string;\n try {\n content = await fs.readFile(credPath, 'utf-8');\n } catch {\n content = '';\n }\n\n const lines = content.split('\\n');\n let found = false;\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim();\n if (trimmed.startsWith('#') || !trimmed) continue;\n\n const eqIdx = trimmed.indexOf('=');\n if (eqIdx === -1) continue;\n\n const lineKey = trimmed.slice(0, eqIdx).trim();\n if (lineKey === key) {\n lines[i] = `${key}=${value}`;\n found = true;\n break;\n }\n }\n\n if (!found) {\n // Append \u2014 ensure there's a trailing newline before adding\n if (content.length > 0 && !content.endsWith('\\n')) {\n lines.push('');\n }\n lines.push(`${key}=${value}`);\n }\n\n // Ensure file ends with newline\n let newContent = lines.join('\\n');\n if (!newContent.endsWith('\\n')) {\n newContent += '\\n';\n }\n\n await fs.writeFile(credPath, newContent, { mode: 0o600 });\n return credPath;\n}\n\n/**\n * Get the machine name for this host.\n * Priority: CV_HUB_MACHINE_NAME from credentials > os.hostname()\n * Cleans the value: lowercase, trim, replace spaces with hyphens.\n */\nexport async function getMachineName(): Promise<string> {\n const creds = await readCredentials();\n const raw = creds.CV_HUB_MACHINE_NAME || os.hostname();\n return cleanMachineName(raw);\n}\n\n/**\n * Clean a machine name: lowercase, trim, replace spaces with hyphens.\n */\nexport function cleanMachineName(name: string): string {\n return name.trim().toLowerCase().replace(/\\s+/g, '-');\n}\n", "/**\n * CV-Hub API client for the cva agent.\n *\n * Extracted from cv-git agent.ts with additional endpoints for\n * listing executors, tasks, logs, and creating repos.\n */\n\nimport type { CVHubCredentials } from './credentials.js';\n\n// ============================================================================\n// Core API call\n// ============================================================================\n\nexport async function apiCall(\n creds: CVHubCredentials,\n method: string,\n path: string,\n body?: unknown,\n): Promise<Response> {\n const url = `${creds.CV_HUB_API}${path}`;\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${creds.CV_HUB_PAT}`,\n 'Content-Type': 'application/json',\n };\n return fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n}\n\n// ============================================================================\n// Executor lifecycle\n// ============================================================================\n\nexport async function registerExecutor(\n creds: CVHubCredentials,\n machineName: string,\n workingDir: string,\n repositoryId?: string,\n): Promise<{ id: string; name: string }> {\n const body: Record<string, unknown> = {\n name: `cva:${machineName}`,\n machine_name: machineName,\n type: 'claude_code',\n workspace_root: workingDir,\n capabilities: {\n tools: ['bash', 'read', 'write', 'edit', 'glob', 'grep'],\n maxConcurrentTasks: 1,\n },\n };\n\n if (repositoryId) {\n body.repository_id = repositoryId;\n }\n\n const res = await apiCall(creds, 'POST', '/api/v1/executors', body);\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Failed to register executor: ${res.status} ${err}`);\n }\n\n const data = await res.json() as any;\n return { id: data.executor.id, name: data.executor.name };\n}\n\nexport async function resolveRepoId(\n creds: CVHubCredentials,\n owner: string,\n repo: string,\n): Promise<{ id: string; slug: string } | null> {\n try {\n const res = await apiCall(creds, 'GET', `/api/v1/repos/${owner}/${repo}`);\n if (!res.ok) return null;\n const data = await res.json() as any;\n return data.repository\n ? { id: data.repository.id, slug: data.repository.slug }\n : null;\n } catch {\n return null;\n }\n}\n\nexport async function markOffline(\n creds: CVHubCredentials,\n executorId: string,\n): Promise<void> {\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/offline`).catch(() => {});\n}\n\n// ============================================================================\n// Task lifecycle\n// ============================================================================\n\nexport async function pollForTask(\n creds: CVHubCredentials,\n executorId: string,\n): Promise<any | null> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/poll`);\n if (!res.ok) throw new Error(`Poll failed: ${res.status}`);\n const data = await res.json() as any;\n return data.task || null;\n}\n\nexport async function startTask(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n): Promise<void> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/start`);\n if (!res.ok) throw new Error(`Start failed: ${res.status}`);\n}\n\nexport async function completeTask(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n result: Record<string, unknown>,\n): Promise<void> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/complete`, result);\n if (!res.ok) throw new Error(`Complete failed: ${res.status}`);\n}\n\nexport async function failTask(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n error: string,\n): Promise<void> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/fail`, { error });\n if (!res.ok) throw new Error(`Fail failed: ${res.status}`);\n}\n\nexport async function sendHeartbeat(\n creds: CVHubCredentials,\n executorId: string,\n taskId?: string,\n message?: string,\n authStatus?: string,\n): Promise<void> {\n const body: Record<string, unknown> | undefined = authStatus ? { auth_status: authStatus } : undefined;\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/heartbeat`, body).catch(() => {});\n if (taskId) {\n const taskBody = message ? { message, log_type: 'heartbeat' } : undefined;\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/heartbeat`, taskBody).catch(() => {});\n }\n}\n\nexport async function sendTaskLog(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n logType: string,\n message: string,\n details?: Record<string, unknown>,\n progressPct?: number,\n): Promise<void> {\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/log`, {\n log_type: logType,\n message,\n ...(details ? { details } : {}),\n ...(progressPct !== undefined ? { progress_pct: progressPct } : {}),\n }).catch(() => {});\n}\n\n// ============================================================================\n// Prompt relay (for relay mode)\n// ============================================================================\n\nexport async function createTaskPrompt(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n promptText: string,\n promptType: string = 'approval',\n options?: string[],\n context?: Record<string, unknown>,\n): Promise<{ prompt_id: string }> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/prompt`, {\n type: promptType,\n text: promptText,\n ...(options ? { options } : {}),\n ...(context ? { context } : {}),\n });\n if (!res.ok) throw new Error(`Create prompt failed: ${res.status}`);\n return await res.json() as { prompt_id: string };\n}\n\nexport async function pollPromptResponse(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n promptId: string,\n): Promise<{ response: string | null }> {\n const res = await apiCall(creds, 'GET', `/api/v1/executors/${executorId}/tasks/${taskId}/prompts/${promptId}`);\n if (!res.ok) throw new Error(`Poll prompt failed: ${res.status}`);\n const data = await res.json() as any;\n return { response: data.response ?? null };\n}\n\n// ============================================================================\n// New listing endpoints\n// ============================================================================\n\nexport async function listExecutors(\n creds: CVHubCredentials,\n): Promise<any[]> {\n const res = await apiCall(creds, 'GET', '/api/v1/executors');\n if (!res.ok) throw new Error(`List executors failed: ${res.status}`);\n const data = await res.json() as any;\n return data.executors || [];\n}\n\nexport async function listTasks(\n creds: CVHubCredentials,\n status?: string,\n): Promise<any[]> {\n const qs = status ? `?status=${encodeURIComponent(status)}` : '';\n const res = await apiCall(creds, 'GET', `/api/v1/tasks${qs}`);\n if (!res.ok) throw new Error(`List tasks failed: ${res.status}`);\n const data = await res.json() as any;\n return data.tasks || [];\n}\n\nexport async function getTask(\n creds: CVHubCredentials,\n taskId: string,\n): Promise<any> {\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}`);\n if (!res.ok) throw new Error(`Get task failed: ${res.status}`);\n const data = await res.json() as any;\n return data.task;\n}\n\nexport async function getTaskLogs(\n creds: CVHubCredentials,\n taskId: string,\n): Promise<any[]> {\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}/logs`);\n if (!res.ok) throw new Error(`Get task logs failed: ${res.status}`);\n const data = await res.json() as any;\n return data.logs || [];\n}\n\n// ============================================================================\n// Task events (structured streaming events)\n// ============================================================================\n\nexport async function postTaskEvent(\n creds: CVHubCredentials,\n taskId: string,\n event: {\n event_type: string;\n content: Record<string, unknown> | string;\n needs_response?: boolean;\n },\n): Promise<{ id: string; event_type: string }> {\n const res = await apiCall(creds, 'POST', `/api/v1/tasks/${taskId}/events`, event);\n if (!res.ok) throw new Error(`Post event failed: ${res.status}`);\n return await res.json() as any;\n}\n\nexport async function getEventResponse(\n creds: CVHubCredentials,\n taskId: string,\n eventId: string,\n): Promise<{ response: unknown | null; responded_at: string | null }> {\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}/events?after_id=&limit=200`);\n if (!res.ok) throw new Error(`Get events failed: ${res.status}`);\n const events = await res.json() as any[];\n const event = events.find((e: any) => e.id === eventId);\n return {\n response: event?.response ?? null,\n responded_at: event?.respondedAt ?? event?.responded_at ?? null,\n };\n}\n\nexport async function getRedirects(\n creds: CVHubCredentials,\n taskId: string,\n afterTimestamp?: string,\n): Promise<Array<{ id: string; content: { instruction: string } }>> {\n const qs = afterTimestamp ? `?after_timestamp=${encodeURIComponent(afterTimestamp)}` : '';\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}/events${qs}`);\n if (!res.ok) return [];\n const events = await res.json() as any[];\n return events\n .filter((e: any) => (e.eventType ?? e.event_type) === 'redirect')\n .map((e: any) => ({ id: e.id, content: e.content }));\n}\n\n// ============================================================================\n// Repository management\n// ============================================================================\n\nexport async function createRepo(\n creds: CVHubCredentials,\n name: string,\n description?: string,\n): Promise<any> {\n const res = await apiCall(creds, 'POST', '/api/v1/repos', {\n name,\n ...(description ? { description } : {}),\n });\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Create repo failed: ${res.status} ${err}`);\n }\n return await res.json();\n}\n", "/**\n * Structured Output Parser\n *\n * Parses Claude Code stdout for structured markers emitted by enriched task prompts.\n *\n * Markers:\n * [THINKING] <text> \u2192 event_type: 'thinking'\n * [DECISION] <text> \u2192 event_type: 'decision'\n * [QUESTION] <text> \u2192 event_type: 'question', needs_response: true\n * [PROGRESS] <text> \u2192 event_type: 'progress'\n *\n * Also detects:\n * - File write tool use \u2192 event_type: 'file_change'\n * - Error output \u2192 event_type: 'error'\n */\n\nexport interface ParsedEvent {\n eventType: string;\n content: string | Record<string, unknown>;\n needsResponse: boolean;\n}\n\n/**\n * Parse a single line of Claude Code output for structured markers.\n * Returns null if the line contains no recognized marker.\n */\nexport function parseClaudeCodeOutput(line: string): ParsedEvent | null {\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n // Match [THINKING] ...\n const thinkingMatch = trimmed.match(/^\\[THINKING\\]\\s*(.+)/);\n if (thinkingMatch) {\n return { eventType: 'thinking', content: thinkingMatch[1], needsResponse: false };\n }\n\n // Match [DECISION] ...\n const decisionMatch = trimmed.match(/^\\[DECISION\\]\\s*(.+)/);\n if (decisionMatch) {\n return { eventType: 'decision', content: decisionMatch[1], needsResponse: false };\n }\n\n // Match [QUESTION] ...\n const questionMatch = trimmed.match(/^\\[QUESTION\\]\\s*(.+)/);\n if (questionMatch) {\n return { eventType: 'question', content: questionMatch[1], needsResponse: true };\n }\n\n // Match [PROGRESS] ...\n const progressMatch = trimmed.match(/^\\[PROGRESS\\]\\s*(.+)/);\n if (progressMatch) {\n return { eventType: 'progress', content: progressMatch[1], needsResponse: false };\n }\n\n // Detect file changes from Claude Code tool use output\n // Patterns: \"Created file: ...\", \"Modified: ...\", \"Wrote to ...\", \"Deleted ...\"\n const fileChangeMatch = trimmed.match(\n /(?:Created|Modified|Wrote to|Deleted)\\s+(?:file:\\s*)?(.+)/i,\n );\n if (fileChangeMatch) {\n const action = trimmed.split(/\\s/)[0].toLowerCase();\n return {\n eventType: 'file_change',\n content: { path: fileChangeMatch[1].trim(), action },\n needsResponse: false,\n };\n }\n\n // Detect errors\n const errorMatch = trimmed.match(/^(?:Error|FATAL|FAILED|panic|Traceback)/i);\n if (errorMatch) {\n return { eventType: 'error', content: trimmed, needsResponse: false };\n }\n\n return null;\n}\n", "/**\n * Git state tracking for the cva agent.\n *\n * Captures pre-task and post-task git state so the agent can report\n * structured diffs, commit info, and file change details back to CV-Hub.\n */\n\nimport { execSync } from 'node:child_process';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PreTaskState {\n headSha: string | null;\n branch: string | null;\n remote: string | null;\n workingDir: string;\n}\n\nexport interface PostTaskState {\n headSha: string | null;\n branch: string | null;\n filesAdded: string[];\n filesModified: string[];\n filesDeleted: string[];\n linesAdded: number;\n linesDeleted: number;\n commitMessages: string[];\n pushStatus: 'success' | 'not_pushed' | 'failed' | 'no_remote';\n pushRemote: string | null;\n}\n\nexport interface TaskCompletionPayload {\n summary: string;\n output: string;\n commit: {\n sha: string | null;\n branch: string | null;\n remote: string | null;\n push_status: string;\n messages: string[];\n };\n files: {\n added: string[];\n modified: string[];\n deleted: string[];\n total_changed: number;\n };\n stats: {\n lines_added: number;\n lines_deleted: number;\n duration_seconds: number;\n };\n exit_code: number;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Run a git command, return trimmed stdout or null on failure */\nexport function gitExec(cmd: string, cwd: string): string | null {\n try {\n return execSync(cmd, { cwd, encoding: 'utf-8', timeout: 10000 }).trim();\n } catch {\n return null;\n }\n}\n\n// ============================================================================\n// Pre-task state\n// ============================================================================\n\nexport function capturePreTaskState(cwd: string): PreTaskState {\n return {\n headSha: gitExec('git rev-parse HEAD', cwd),\n branch: gitExec('git rev-parse --abbrev-ref HEAD', cwd),\n remote: gitExec('git remote get-url origin', cwd),\n workingDir: cwd,\n };\n}\n\n// ============================================================================\n// Post-task state\n// ============================================================================\n\nexport function capturePostTaskState(cwd: string, preState: PreTaskState): PostTaskState {\n const headSha = gitExec('git rev-parse HEAD', cwd);\n const branch = gitExec('git rev-parse --abbrev-ref HEAD', cwd);\n\n let filesAdded: string[] = [];\n let filesModified: string[] = [];\n let filesDeleted: string[] = [];\n let linesAdded = 0;\n let linesDeleted = 0;\n let commitMessages: string[] = [];\n\n if (preState.headSha && headSha && preState.headSha !== headSha) {\n const diffOutput = gitExec(\n `git diff --name-status ${preState.headSha}..${headSha}`,\n cwd,\n );\n\n if (diffOutput) {\n for (const line of diffOutput.split('\\n')) {\n const [status, ...pathParts] = line.split('\\t');\n const filepath = pathParts.join('\\t');\n if (!filepath) continue;\n\n if (status === 'A') filesAdded.push(filepath);\n else if (status === 'M') filesModified.push(filepath);\n else if (status === 'D') filesDeleted.push(filepath);\n else if (status?.startsWith('R')) {\n filesDeleted.push(pathParts[0]);\n if (pathParts[1]) filesAdded.push(pathParts[1]);\n }\n }\n }\n\n const statOutput = gitExec(\n `git diff --shortstat ${preState.headSha}..${headSha}`,\n cwd,\n );\n if (statOutput) {\n const addMatch = statOutput.match(/(\\d+) insertion/);\n const delMatch = statOutput.match(/(\\d+) deletion/);\n linesAdded = addMatch ? parseInt(addMatch[1], 10) : 0;\n linesDeleted = delMatch ? parseInt(delMatch[1], 10) : 0;\n }\n\n const logOutput = gitExec(\n `git log --oneline ${preState.headSha}..${headSha}`,\n cwd,\n );\n if (logOutput) {\n commitMessages = logOutput.split('\\n').filter(Boolean);\n }\n } else if (!preState.headSha && headSha) {\n const allFiles = gitExec('git ls-files', cwd);\n if (allFiles) {\n filesAdded = allFiles.split('\\n').filter(Boolean);\n }\n } else {\n const statusOutput = gitExec('git status --porcelain', cwd);\n if (statusOutput) {\n for (const line of statusOutput.split('\\n')) {\n const status = line.substring(0, 2).trim();\n const filepath = line.substring(3);\n if (!filepath) continue;\n\n if (status === '??' || status === 'A') filesAdded.push(filepath);\n else if (status === 'M') filesModified.push(filepath);\n else if (status === 'D') filesDeleted.push(filepath);\n }\n }\n }\n\n let pushStatus: PostTaskState['pushStatus'] = 'not_pushed';\n let pushRemote: string | null = null;\n\n const remote = gitExec('git remote get-url origin', cwd);\n if (!remote) {\n pushStatus = 'no_remote';\n } else {\n pushRemote = remote;\n if (headSha && branch) {\n const remoteRef = gitExec(`git ls-remote origin ${branch}`, cwd);\n if (remoteRef && remoteRef.includes(headSha)) {\n pushStatus = 'success';\n }\n }\n }\n\n return {\n headSha,\n branch,\n filesAdded,\n filesModified,\n filesDeleted,\n linesAdded,\n linesDeleted,\n commitMessages,\n pushStatus,\n pushRemote,\n };\n}\n\n// ============================================================================\n// Structured completion payload\n// ============================================================================\n\nexport function buildCompletionPayload(\n exitCode: number,\n preState: PreTaskState,\n postState: PostTaskState,\n startTime: number,\n output: string = '',\n): TaskCompletionPayload {\n const durationSec = Math.floor((Date.now() - startTime) / 1000);\n const durationStr = durationSec >= 60\n ? `${Math.floor(durationSec / 60)}m ${durationSec % 60}s`\n : `${durationSec}s`;\n\n const totalChanged =\n postState.filesAdded.length +\n postState.filesModified.length +\n postState.filesDeleted.length;\n\n const parts: string[] = [`Completed in ${durationStr}.`];\n\n if (totalChanged > 0) {\n parts.push(\n `${totalChanged} file(s) changed (+${postState.linesAdded}/-${postState.linesDeleted}).`,\n );\n } else {\n parts.push('No file changes detected.');\n }\n\n if (postState.headSha && postState.headSha !== preState.headSha) {\n parts.push(`Commit: ${postState.headSha.substring(0, 8)}`);\n }\n\n if (postState.pushStatus === 'success') {\n parts.push('Pushed to remote.');\n } else if (postState.pushStatus === 'not_pushed') {\n parts.push('Not pushed to remote.');\n }\n\n return {\n summary: parts.join(' '),\n output,\n commit: {\n sha: postState.headSha,\n branch: postState.branch,\n remote: postState.pushRemote,\n push_status: postState.pushStatus,\n messages: postState.commitMessages,\n },\n files: {\n added: postState.filesAdded,\n modified: postState.filesModified,\n deleted: postState.filesDeleted,\n total_changed: totalChanged,\n },\n stats: {\n lines_added: postState.linesAdded,\n lines_deleted: postState.linesDeleted,\n duration_seconds: durationSec,\n },\n exit_code: exitCode,\n };\n}\n\n// ============================================================================\n// Git remote verification\n// ============================================================================\n\nexport function verifyGitRemote(\n cwd: string,\n task: { owner?: string; repo?: string },\n gitHost: string,\n): { remoteName: string; remoteUrl: string } | null {\n if (!task.owner || !task.repo) return null;\n\n const expectedRemote = `https://${gitHost}/${task.owner}/${task.repo}.git`;\n const currentRemote = gitExec('git remote get-url origin', cwd);\n\n if (!currentRemote) {\n try {\n execSync(`git remote add origin ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch { /* remote may already exist without URL */ }\n return { remoteName: 'origin', remoteUrl: expectedRemote };\n }\n\n if (currentRemote === expectedRemote) {\n return { remoteName: 'origin', remoteUrl: expectedRemote };\n }\n\n if (currentRemote.includes(gitHost)) {\n try {\n execSync(`git remote set-url origin ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch {}\n return { remoteName: 'origin', remoteUrl: expectedRemote };\n }\n\n const cvRemote = gitExec('git remote get-url cv-hub', cwd);\n if (!cvRemote) {\n try {\n execSync(`git remote add cv-hub ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch {}\n } else if (cvRemote !== expectedRemote) {\n try {\n execSync(`git remote set-url cv-hub ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch {}\n }\n return { remoteName: 'cv-hub', remoteUrl: expectedRemote };\n}\n", "/**\n * Display helpers for the cva agent.\n */\n\nimport chalk from 'chalk';\n\nexport function formatDuration(ms: number): string {\n const s = Math.floor(ms / 1000);\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n const rem = s % 60;\n if (m < 60) return `${m}m ${rem}s`;\n const h = Math.floor(m / 60);\n return `${h}h ${m % 60}m`;\n}\n\nexport function setTerminalTitle(title: string): void {\n if (process.stdout.isTTY) {\n process.stdout.write(`\\x1b]0;${title}\\x07`);\n }\n}\n\nexport function printBanner(\n status: 'COMPLETED' | 'FAILED' | 'ABORTED',\n elapsed: string,\n changedFiles: string[],\n commitSha: string | null,\n): void {\n const color = status === 'COMPLETED' ? chalk.green : status === 'ABORTED' ? chalk.yellow : chalk.red;\n const icon = status === 'COMPLETED' ? '\u2705' : status === 'ABORTED' ? '\u23F9' : '\u274C';\n\n console.log(color('\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510'));\n console.log(color(`\u2502 ${icon} ${status.padEnd(57)}\u2502`));\n console.log(color(`\u2502 Duration: ${elapsed.padEnd(49)}\u2502`));\n if (changedFiles.length > 0) {\n const shown = changedFiles.slice(0, 3);\n const fileStr = shown.join(', ') + (changedFiles.length > 3 ? ` and ${changedFiles.length - 3} more` : '');\n console.log(color(`\u2502 Files: ${fileStr.substring(0, 51).padEnd(51)}\u2502`));\n }\n if (commitSha) {\n console.log(color(`\u2502 Commit: ${commitSha.substring(0, 8).padEnd(51)}\u2502`));\n }\n console.log(color('\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518'));\n}\n\nexport function updateStatusLine(\n idle: string,\n poll: string,\n completedCount: number,\n failedCount: number,\n): void {\n const line = `\\r${chalk.cyan('\uD83D\uDD04')} Listening... (${idle} idle) | Last poll: ${poll} ago | Completed: ${completedCount} | Failed: ${failedCount}`;\n process.stdout.write(`\\r\\x1b[K${line}`);\n}\n", "/**\n * Retry logic for API calls.\n */\n\nimport chalk from 'chalk';\n\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n label: string,\n maxRetries = 3,\n): Promise<T> {\n for (let i = 0; i < maxRetries; i++) {\n try {\n return await fn();\n } catch (err: any) {\n if (i === maxRetries - 1) throw err;\n const delay = (i + 1) * 5;\n console.log(`\\n${chalk.yellow('\u26A0')} ${label} failed, retrying in ${delay}s... (${err.message})`);\n await new Promise(r => setTimeout(r, delay * 1000));\n }\n }\n throw new Error('unreachable');\n}\n", "/**\n * Agent config at ~/.config/cva/config.json\n */\n\nimport { promises as fs } from 'fs';\nimport { homedir } from 'os';\nimport { join, dirname } from 'path';\n\nexport interface CvaConfig {\n defaultApiUrl?: string;\n defaultPollInterval?: number;\n autoApprove?: boolean;\n anthropic_api_key?: string;\n [key: string]: unknown;\n}\n\nexport function getConfigPath(): string {\n return join(homedir(), '.config', 'cva', 'config.json');\n}\n\nexport async function readConfig(): Promise<CvaConfig> {\n try {\n const content = await fs.readFile(getConfigPath(), 'utf-8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\nexport async function writeConfig(config: CvaConfig): Promise<void> {\n const configPath = getConfigPath();\n await fs.mkdir(dirname(configPath), { recursive: true });\n await fs.writeFile(configPath, JSON.stringify(config, null, 2) + '\\n', { mode: 0o600 });\n}\n", "/**\n * cva auth login / cva auth status\n *\n * Manages CV-Hub authentication credentials.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport {\n readCredentials,\n writeCredentialField,\n} from '../utils/credentials.js';\nimport { apiCall } from '../utils/api.js';\nimport { readConfig, writeConfig } from '../utils/config.js';\n\nasync function authLogin(opts: { token?: string; apiUrl?: string }): Promise<void> {\n const token = opts.token || await promptForToken();\n const apiUrl = opts.apiUrl || 'https://api.hub.controlvector.io';\n\n // Validate the token\n console.log(chalk.gray('Validating token...'));\n try {\n const res = await fetch(`${apiUrl}/api/auth/me`, {\n headers: { 'Authorization': `Bearer ${token}` },\n });\n\n if (!res.ok) {\n console.log(chalk.red('Invalid token.') + ` API returned ${res.status}`);\n process.exit(1);\n }\n\n const data = await res.json() as any;\n const username = data.user?.username || data.user?.email || 'unknown';\n\n // Save credentials\n await writeCredentialField('CV_HUB_PAT', token);\n await writeCredentialField('CV_HUB_API', apiUrl);\n\n console.log(chalk.green('Authenticated') + ` as ${chalk.bold(username)}`);\n console.log(chalk.gray(`Token saved to ~/.config/cv-hub/credentials`));\n } catch (err: any) {\n console.log(chalk.red('Connection failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nasync function promptForToken(): Promise<string> {\n // Simple stdin read for token\n const readline = await import('node:readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question('Enter your CV-Hub PAT token: ', (answer: string) => {\n rl.close();\n const token = answer.trim();\n if (!token) {\n console.log(chalk.red('No token provided.'));\n process.exit(1);\n }\n resolve(token);\n });\n });\n}\n\nasync function authStatus(): Promise<void> {\n const creds = await readCredentials();\n\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.yellow('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n return;\n }\n\n const apiUrl = creds.CV_HUB_API || 'https://api.hub.controlvector.io';\n const maskedToken = creds.CV_HUB_PAT.substring(0, 8) + '...' + creds.CV_HUB_PAT.slice(-4);\n\n console.log(`API: ${chalk.cyan(apiUrl)}`);\n console.log(`Token: ${chalk.gray(maskedToken)}`);\n\n // Verify token\n try {\n const res = await fetch(`${apiUrl}/api/auth/me`, {\n headers: { 'Authorization': `Bearer ${creds.CV_HUB_PAT}` },\n });\n\n if (res.ok) {\n const data = await res.json() as any;\n const username = data.user?.username || data.user?.email || 'unknown';\n console.log(`User: ${chalk.green(username)}`);\n console.log(`Status: ${chalk.green('valid')}`);\n } else {\n console.log(`Status: ${chalk.red('invalid')} (${res.status})`);\n }\n } catch (err: any) {\n console.log(`Status: ${chalk.red('unreachable')} (${err.message})`);\n }\n}\n\nasync function authSetApiKey(key: string): Promise<void> {\n if (!key.startsWith('sk-ant-')) {\n console.log(chalk.red('Invalid API key.') + ' Anthropic API keys start with sk-ant-');\n process.exit(1);\n }\n\n const config = await readConfig();\n config.anthropic_api_key = key;\n await writeConfig(config);\n\n const masked = key.substring(0, 10) + '...' + key.slice(-4);\n console.log(chalk.green('API key saved') + ` (${masked})`);\n console.log(chalk.gray('This key will be used as fallback when Claude Code OAuth expires.'));\n}\n\nasync function authRemoveApiKey(): Promise<void> {\n const config = await readConfig();\n if (!config.anthropic_api_key) {\n console.log(chalk.yellow('No API key configured.'));\n return;\n }\n delete config.anthropic_api_key;\n await writeConfig(config);\n console.log(chalk.green('API key removed.'));\n}\n\nexport function authCommand(): Command {\n const cmd = new Command('auth');\n cmd.description('Manage CV-Hub authentication');\n\n cmd\n .command('login')\n .description('Authenticate with CV-Hub using a PAT token')\n .option('--token <token>', 'PAT token (or enter interactively)')\n .option('--api-url <url>', 'CV-Hub API URL', 'https://api.hub.controlvector.io')\n .action(authLogin);\n\n cmd\n .command('status')\n .description('Show current authentication status')\n .action(authStatus);\n\n cmd\n .command('set-api-key')\n .description('Set Anthropic API key as fallback for Claude Code OAuth')\n .argument('<key>', 'Anthropic API key (sk-ant-...)')\n .action(authSetApiKey);\n\n cmd\n .command('remove-api-key')\n .description('Remove stored Anthropic API key')\n .action(authRemoveApiKey);\n\n return cmd;\n}\n", "/**\n * cva remote add / cva remote setup\n *\n * Manages CV-Hub git remotes for the current repository.\n */\n\nimport { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport chalk from 'chalk';\nimport { readCredentials } from '../utils/credentials.js';\nimport { createRepo } from '../utils/api.js';\n\nfunction getGitHost(apiUrl: string): string {\n return apiUrl\n .replace(/^https?:\\/\\//, '')\n .replace(/^api\\./, 'git.');\n}\n\nasync function remoteAdd(ownerRepo: string): Promise<void> {\n const creds = await readCredentials();\n const apiUrl = creds.CV_HUB_API || 'https://api.hub.controlvector.io';\n const gitHost = getGitHost(apiUrl);\n\n const [owner, repo] = ownerRepo.split('/');\n if (!owner || !repo) {\n console.log(chalk.red('Invalid format.') + ' Use: cva remote add <owner>/<repo>');\n process.exit(1);\n }\n\n const remoteUrl = `https://${gitHost}/${owner}/${repo}.git`;\n\n // Check if cvhub remote already exists\n try {\n const existing = execSync('git remote get-url cvhub', { encoding: 'utf-8', timeout: 5000 }).trim();\n if (existing === remoteUrl) {\n console.log(chalk.gray(`Remote 'cvhub' already set to ${remoteUrl}`));\n return;\n }\n // Update it\n execSync(`git remote set-url cvhub ${remoteUrl}`, { timeout: 5000 });\n console.log(chalk.green('Updated') + ` remote 'cvhub' -> ${remoteUrl}`);\n } catch {\n // Add new remote\n try {\n execSync(`git remote add cvhub ${remoteUrl}`, { timeout: 5000 });\n console.log(chalk.green('Added') + ` remote 'cvhub' -> ${remoteUrl}`);\n } catch (err: any) {\n console.log(chalk.red('Failed to add remote:') + ` ${err.message}`);\n process.exit(1);\n }\n }\n}\n\nasync function remoteSetup(ownerRepo: string): Promise<void> {\n const creds = await readCredentials();\n\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n\n if (!creds.CV_HUB_API) {\n creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n }\n\n const [owner, repo] = ownerRepo.split('/');\n if (!owner || !repo) {\n console.log(chalk.red('Invalid format.') + ' Use: cva remote setup <owner>/<repo>');\n process.exit(1);\n }\n\n // Create repo on CV-Hub\n console.log(chalk.gray(`Creating repository ${ownerRepo} on CV-Hub...`));\n try {\n await createRepo(creds, repo);\n console.log(chalk.green('Created') + ` repository ${ownerRepo}`);\n } catch (err: any) {\n if (err.message.includes('409') || err.message.includes('already exists')) {\n console.log(chalk.gray(`Repository ${ownerRepo} already exists.`));\n } else {\n console.log(chalk.red('Failed to create repo:') + ` ${err.message}`);\n process.exit(1);\n }\n }\n\n // Add the remote\n await remoteAdd(ownerRepo);\n}\n\nexport function remoteCommand(): Command {\n const cmd = new Command('remote');\n cmd.description('Manage CV-Hub git remotes');\n\n cmd\n .command('add <owner/repo>')\n .description('Add cvhub remote to current git repo')\n .action(remoteAdd);\n\n cmd\n .command('setup <owner/repo>')\n .description('Create repo on CV-Hub and add cvhub remote')\n .action(remoteSetup);\n\n return cmd;\n}\n", "/**\n * cva task list / cva task logs\n *\n * View tasks and task logs from CV-Hub.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readCredentials } from '../utils/credentials.js';\nimport { listTasks, getTask, getTaskLogs } from '../utils/api.js';\n\nasync function taskList(opts: { status?: string }): Promise<void> {\n const creds = await readCredentials();\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n if (!creds.CV_HUB_API) creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n\n try {\n const tasks = await listTasks(creds, opts.status);\n\n if (tasks.length === 0) {\n console.log(chalk.gray('No tasks found.'));\n return;\n }\n\n // Table output\n const statusColors: Record<string, (s: string) => string> = {\n pending: chalk.yellow,\n assigned: chalk.blue,\n running: chalk.cyan,\n completed: chalk.green,\n failed: chalk.red,\n cancelled: chalk.gray,\n waiting_for_input: chalk.magenta,\n };\n\n for (const t of tasks) {\n const colorFn = statusColors[t.status] || chalk.white;\n const status = colorFn(t.status.padEnd(18));\n const title = (t.title || '').substring(0, 50);\n const id = chalk.gray(t.id.substring(0, 8));\n const age = t.created_at ? chalk.gray(timeSince(new Date(t.created_at))) : '';\n console.log(`${id} ${status} ${title} ${age}`);\n }\n\n console.log(chalk.gray(`\\n${tasks.length} task(s)`));\n } catch (err: any) {\n console.log(chalk.red('Failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nasync function taskLogs(taskId: string): Promise<void> {\n const creds = await readCredentials();\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n if (!creds.CV_HUB_API) creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n\n try {\n const logs = await getTaskLogs(creds, taskId);\n\n if (logs.length === 0) {\n // Fallback: show task detail\n console.log(chalk.gray('No logs found. Showing task detail:'));\n const task = await getTask(creds, taskId);\n console.log(JSON.stringify(task, null, 2));\n return;\n }\n\n const typeColors: Record<string, (s: string) => string> = {\n lifecycle: chalk.blue,\n heartbeat: chalk.gray,\n progress: chalk.cyan,\n git: chalk.green,\n error: chalk.red,\n info: chalk.white,\n };\n\n for (const log of logs) {\n const colorFn = typeColors[log.log_type] || chalk.white;\n const type = colorFn(`[${log.log_type}]`.padEnd(14));\n const time = chalk.gray(new Date(log.created_at).toLocaleTimeString());\n const pct = log.progress_pct !== null && log.progress_pct !== undefined\n ? chalk.yellow(` ${log.progress_pct}%`)\n : '';\n console.log(`${time} ${type} ${log.message}${pct}`);\n }\n } catch (err: any) {\n console.log(chalk.red('Failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nfunction timeSince(date: Date): string {\n const seconds = Math.floor((Date.now() - date.getTime()) / 1000);\n if (seconds < 60) return `${seconds}s ago`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.floor(hours / 24);\n return `${days}d ago`;\n}\n\nexport function taskCommand(): Command {\n const cmd = new Command('task');\n cmd.description('View tasks and task logs');\n\n cmd\n .command('list')\n .description('List tasks')\n .option('--status <status>', 'Filter by status (e.g. running,completed)')\n .action(taskList);\n\n cmd\n .command('logs <taskId>')\n .description('View logs for a task')\n .action(taskLogs);\n\n return cmd;\n}\n", "/**\n * cva status\n *\n * Show registered executors and their current status.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readCredentials } from '../utils/credentials.js';\nimport { listExecutors } from '../utils/api.js';\n\nasync function showStatus(): Promise<void> {\n const creds = await readCredentials();\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n if (!creds.CV_HUB_API) creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n\n try {\n const executors = await listExecutors(creds);\n\n if (executors.length === 0) {\n console.log(chalk.gray('No executors registered.'));\n return;\n }\n\n const statusColors: Record<string, (s: string) => string> = {\n online: chalk.green,\n offline: chalk.gray,\n busy: chalk.yellow,\n error: chalk.red,\n };\n\n console.log(chalk.bold('Executors:'));\n console.log();\n\n for (const e of executors) {\n const colorFn = statusColors[e.status] || chalk.white;\n const status = colorFn(e.status.padEnd(10));\n const name = chalk.cyan(e.name || e.machine_name || 'unknown');\n const id = chalk.gray(e.id.substring(0, 8));\n const heartbeat = e.last_heartbeat_at\n ? chalk.gray(`last seen ${timeSince(new Date(e.last_heartbeat_at))}`)\n : chalk.gray('never');\n const workspace = e.workspace_root ? chalk.gray(` | ${e.workspace_root}`) : '';\n\n console.log(` ${id} ${status} ${name} ${heartbeat}${workspace}`);\n }\n\n console.log(chalk.gray(`\\n${executors.length} executor(s)`));\n } catch (err: any) {\n console.log(chalk.red('Failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nfunction timeSince(date: Date): string {\n const seconds = Math.floor((Date.now() - date.getTime()) / 1000);\n if (seconds < 60) return `${seconds}s ago`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.floor(hours / 24);\n return `${days}d ago`;\n}\n\nexport function statusCommand(): Command {\n const cmd = new Command('status');\n cmd.description('Show registered executors and their status');\n cmd.action(showStatus);\n return cmd;\n}\n", "/**\n * cva \u2014 CV-Hub Agent CLI\n *\n * Standalone agent daemon that bridges Claude Code with CV-Hub task dispatch.\n * Binary: cva\n * Package: @controlvector/cv-agent\n */\n\nimport { Command } from 'commander';\nimport { agentCommand } from './commands/agent.js';\nimport { authCommand } from './commands/auth.js';\nimport { remoteCommand } from './commands/remote.js';\nimport { taskCommand } from './commands/task.js';\nimport { statusCommand } from './commands/status.js';\n\ndeclare const __CVA_VERSION__: string;\n\nconst program = new Command();\n\nprogram\n .name('cva')\n .description('CV-Hub Agent \u2014 bridges Claude Code with CV-Hub task dispatch')\n .version(typeof __CVA_VERSION__ !== 'undefined' ? __CVA_VERSION__ : '1.1.0');\n\nprogram.addCommand(agentCommand());\nprogram.addCommand(authCommand());\nprogram.addCommand(remoteCommand());\nprogram.addCommand(taskCommand());\nprogram.addCommand(statusCommand());\n\nprogram.parse(process.argv);\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,wCAAAA,UAAA;AAGA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;AAAA,MACrB;AAAA,IACF;AAKA,QAAMC,wBAAN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M,UAAU,EAAE;AACrC,MAAI,QAAQ,GAAI,QAAO,GAAG,KAAK;AAC/B,QAAM,OAAO,KAAK,MAAM,QAAQ,EAAE;AAClC,SAAO,GAAG,IAAI;AAChB;AAEO,SAAS,gBAAyB;AACvC,QAAM,MAAM,IAAI,QAAQ,QAAQ;AAChC,MAAI,YAAY,4CAA4C;AAC5D,MAAI,OAAO,UAAU;AACrB,SAAO;AACT;;;ACxDA,IAAMC,WAAU,IAAI,QAAQ;AAE5BA,SACG,KAAK,KAAK,EACV,YAAY,mEAA8D,EAC1E,QAAQ,OAAyC,UAAkB,OAAO;AAE7EA,SAAQ,WAAW,aAAa,CAAC;AACjCA,SAAQ,WAAW,YAAY,CAAC;AAChCA,SAAQ,WAAW,cAAc,CAAC;AAClCA,SAAQ,WAAW,YAAY,CAAC;AAChCA,SAAQ,WAAW,cAAc,CAAC;AAElCA,SAAQ,MAAM,QAAQ,IAAI;",
|
|
6
|
-
"names": ["exports", "CommanderError", "InvalidArgumentError", "exports", "InvalidArgumentError", "Argument", "exports", "Help", "cmd", "exports", "InvalidArgumentError", "Option", "str", "exports", "exports", "fs", "process", "Argument", "CommanderError", "Help", "Option", "Command", "option", "path", "exports", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "commander", "import_node_child_process", "process", "os", "tty", "styles", "chalk", "styles", "os", "fs", "authStatus", "import_fs", "import_os", "import_path", "fs", "env", "import_node_child_process", "timeSince", "program"]
|
|
3
|
+
"sources": ["../node_modules/commander/lib/error.js", "../node_modules/commander/lib/argument.js", "../node_modules/commander/lib/help.js", "../node_modules/commander/lib/option.js", "../node_modules/commander/lib/suggestSimilar.js", "../node_modules/commander/lib/command.js", "../node_modules/commander/index.js", "../node_modules/commander/esm.mjs", "../src/commands/agent.ts", "../node_modules/chalk/source/vendor/ansi-styles/index.js", "../node_modules/chalk/source/vendor/supports-color/index.js", "../node_modules/chalk/source/utilities.js", "../node_modules/chalk/source/index.js", "../src/utils/credentials.ts", "../src/utils/api.ts", "../src/utils/output-parser.ts", "../src/commands/agent-git.ts", "../src/utils/display.ts", "../src/utils/retry.ts", "../src/utils/config.ts", "../src/commands/git-safety.ts", "../src/commands/deploy-manifest.ts", "../src/commands/auth.ts", "../src/commands/remote.ts", "../src/commands/task.ts", "../src/commands/status.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.length > 3 && this._name.slice(-3) === '...') {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n", "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(max, helper.subcommandTerm(command).length);\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(max, helper.argumentTerm(argument).length);\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n return `${option.description} (${extraInfo.join(', ')})`;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescripton = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescripton}`;\n }\n return extraDescripton;\n }\n return argument.description;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth || 80;\n const itemIndentWidth = 2;\n const itemSeparatorWidth = 2; // between term and description\n function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(\n fullText,\n helpWidth - itemIndentWidth,\n termWidth + itemSeparatorWidth,\n );\n }\n return term;\n }\n function formatList(textArray) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n }\n\n // Usage\n let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.wrap(commandDescription, helpWidth, 0),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(\n helper.argumentTerm(argument),\n helper.argumentDescription(argument),\n );\n });\n if (argumentList.length > 0) {\n output = output.concat(['Arguments:', formatList(argumentList), '']);\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (optionList.length > 0) {\n output = output.concat(['Options:', formatList(optionList), '']);\n }\n\n if (this.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (globalOptionList.length > 0) {\n output = output.concat([\n 'Global Options:',\n formatList(globalOptionList),\n '',\n ]);\n }\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((cmd) => {\n return formatItem(\n helper.subcommandTerm(cmd),\n helper.subcommandDescription(cmd),\n );\n });\n if (commandList.length > 0) {\n output = output.concat(['Commands:', formatList(commandList), '']);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Wrap the given string to width characters per line, with lines after the first indented.\n * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n *\n * @param {string} str\n * @param {number} width\n * @param {number} indent\n * @param {number} [minColumnWidth=40]\n * @return {string}\n *\n */\n\n wrap(str, width, indent, minColumnWidth = 40) {\n // Full \\s characters, minus the linefeeds.\n const indents =\n ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n if (str.match(manualIndent)) return str;\n // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n const columnWidth = width - indent;\n if (columnWidth < minColumnWidth) return str;\n\n const leadingStr = str.slice(0, indent);\n const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n const indentString = ' '.repeat(indent);\n const zeroWidthSpace = '\\u200B';\n const breaks = `\\\\s${zeroWidthSpace}`;\n // Match line end (so empty lines don't collapse),\n // or as much text as will fit in column, or excess text up to first break.\n const regex = new RegExp(\n `\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,\n 'g',\n );\n const lines = columnText.match(regex) || [];\n return (\n leadingStr +\n lines\n .map((line, i) => {\n if (line === '\\n') return ''; // preserve empty lines\n return (i > 0 ? indentString : '') + line.trimEnd();\n })\n .join('\\n')\n );\n }\n}\n\nexports.Help = Help;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag;\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // Use original very loose parsing to maintain backwards compatibility for now,\n // which allowed for example unintended `-sw, --short-word` [sic].\n const flagParts = flags.split(/[ |,]+/);\n if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))\n shortFlag = flagParts.shift();\n longFlag = flagParts.shift();\n // Add support for lone short flag without significantly changing parsing!\n if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n shortFlag = longFlag;\n longFlag = undefined;\n }\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n", "const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = true;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n\n // see .configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n outputError: (str, write) => write(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n Object.assign(this._outputConfiguration, configuration);\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [fn] - custom argument processing function\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, fn, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof fn === 'function') {\n argument.default(defaultValue).argParser(fn);\n } else {\n argument.default(fn);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument && previousArgument.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n return this;\n }\n\n enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._concatValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch (err) {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' 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 - ${executableDirMessage}`;\n throw new Error(executableMissing);\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise && promise.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent && this.parent.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} argv\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(argv) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n const args = argv.slice();\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n // parse options\n let activeVariadicOption = null;\n while (args.length) {\n const arg = args.shift();\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args);\n break;\n }\n\n if (activeVariadicOption && !maybeOption(arg)) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args.shift();\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (args.length > 0 && !maybeOption(args[0])) {\n value = args.shift();\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option, emit and put back remainder of arg for further processing\n this.emit(`option:${option.name()}`);\n args.unshift(`-${arg.slice(2)}`);\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n if (maybeOption(arg)) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg);\n if (args.length > 0) operands.push(...args);\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg);\n if (args.length > 0) dest.push(...args);\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n if (helper.helpWidth === undefined) {\n helper.helpWidth =\n contextOptions && contextOptions.error\n ? this._outputConfiguration.getErrHelpWidth()\n : this._outputConfiguration.getOutHelpWidth();\n }\n return helper.formatHelp(this, helper);\n }\n\n /**\n * @private\n */\n\n _getHelpContext(contextOptions) {\n contextOptions = contextOptions || {};\n const context = { error: !!contextOptions.error };\n let write;\n if (context.error) {\n write = (arg) => this._outputConfiguration.writeErr(arg);\n } else {\n write = (arg) => this._outputConfiguration.writeOut(arg);\n }\n context.write = contextOptions.write || write;\n context.command = this;\n return context;\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n const context = this._getHelpContext(contextOptions);\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', context));\n this.emit('beforeHelp', context);\n\n let helpInformation = this.helpInformation(context);\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n context.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', context);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', context),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n this._helpOption = this._helpOption ?? undefined; // preserve existing option\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n flags = flags ?? '-h, --help';\n description = description ?? 'display help for command';\n this._helpOption = this.createOption(flags, description);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = process.exitCode || 0;\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\nexports.Command = Command;\n", "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n", "import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n", "/**\n * cva agent command\n *\n * Listens for tasks dispatched via CV-Hub and executes them\n * with Claude Code. The agent registers as an executor, polls for tasks,\n * and reports results back.\n *\n * Two execution modes:\n * --auto-approve: Uses Claude Code -p mode with --allowedTools (proven)\n * Default (relay): Spawns interactive Claude Code, relays permission prompts\n *\n * Usage:\n * cva agent # Start in relay mode\n * cva agent --auto-approve # Start in auto-approve mode\n * cva agent --machine z840-primary # Override machine name\n * cva agent --poll-interval 10 # Check every 10 seconds\n */\n\nimport { Command } from 'commander';\nimport { spawn, execSync, type ChildProcess } from 'node:child_process';\nimport chalk from 'chalk';\nimport {\n readCredentials,\n getMachineName,\n type CVHubCredentials,\n} from '../utils/credentials.js';\nimport {\n registerExecutor,\n resolveRepoId,\n pollForTask,\n startTask,\n completeTask,\n failTask,\n sendHeartbeat,\n sendTaskLog,\n markOffline,\n createTaskPrompt,\n pollPromptResponse,\n postTaskEvent,\n getEventResponse,\n getRedirects,\n} from '../utils/api.js';\nimport { parseClaudeCodeOutput } from '../utils/output-parser.js';\nimport {\n capturePreTaskState,\n capturePostTaskState,\n buildCompletionPayload,\n verifyGitRemote,\n} from './agent-git.js';\nimport {\n formatDuration,\n setTerminalTitle,\n printBanner,\n updateStatusLine,\n} from '../utils/display.js';\nimport { withRetry } from '../utils/retry.js';\nimport {\n readConfig,\n readWorkspaceConfig,\n type ExecutorRole,\n type DispatchGuard,\n type ExecutorIntegration,\n} from '../utils/config.js';\nimport { gitSafetyNet } from './git-safety.js';\nimport { postTaskDeploy } from './deploy-manifest.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type AuthStatus = 'authenticated' | 'expired' | 'not_configured' | 'api_key_fallback';\n\n/** Patterns that indicate Claude Code auth failure */\nexport const AUTH_ERROR_PATTERNS = [\n 'Not logged in',\n 'Please run /login',\n 'authentication required',\n 'unauthorized',\n 'expired token',\n 'not authenticated',\n 'login required',\n];\n\ninterface AgentOptions {\n machine?: string;\n pollInterval: string;\n workingDir: string;\n autoApprove: boolean;\n role?: ExecutorRole;\n integration?: string;\n integrationDescription?: string;\n integrationPort?: string;\n safeTasks?: string;\n dispatchGuard?: DispatchGuard;\n tags?: string;\n ownerProject?: string;\n}\n\ninterface AgentState {\n executorId: string;\n currentTaskId: string | null;\n completedCount: number;\n failedCount: number;\n lastPoll: number;\n lastTaskEnd: number;\n running: boolean;\n authStatus: AuthStatus;\n machineName: string;\n}\n\ninterface Task {\n id: string;\n title: string;\n description?: string;\n task_type: string;\n priority: string;\n status: string;\n input?: { description?: string; context?: string; instructions?: string[]; constraints?: string[] };\n repository_id?: string;\n owner?: string;\n repo?: string;\n branch?: string;\n file_paths?: string[];\n timeout_at?: string;\n metadata?: Record<string, unknown>;\n}\n\n// ============================================================================\n// Claude Code auth check & environment\n// ============================================================================\n\n/**\n * Check if a string contains Claude Code auth error patterns.\n * Exported for testing.\n */\nexport function containsAuthError(text: string): string | null {\n const lower = text.toLowerCase();\n for (const pattern of AUTH_ERROR_PATTERNS) {\n if (lower.includes(pattern.toLowerCase())) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Pre-flight check: verify Claude Code is authenticated.\n * Runs `claude --version` and checks output/stderr for auth errors.\n * Returns the detected auth status.\n */\nexport async function checkClaudeAuth(): Promise<{ status: AuthStatus; error?: string }> {\n try {\n const output = execSync('claude --version 2>&1', {\n encoding: 'utf8',\n timeout: 10_000,\n env: { ...process.env },\n });\n\n const authError = containsAuthError(output);\n if (authError) {\n return { status: 'expired', error: authError };\n }\n\n return { status: 'authenticated' };\n } catch (err: any) {\n const output = (err.stdout || '') + (err.stderr || '') + (err.message || '');\n const authError = containsAuthError(output);\n if (authError) {\n return { status: 'expired', error: authError };\n }\n // Binary not found or other error \u2014 not an auth issue per se\n return { status: 'not_configured', error: output.slice(0, 500) };\n }\n}\n\n/**\n * Build the environment for spawning Claude Code.\n * If an Anthropic API key is configured, inject it as ANTHROPIC_API_KEY.\n */\nexport async function getClaudeEnv(): Promise<{ env: NodeJS.ProcessEnv; usingApiKey: boolean }> {\n const env = { ...process.env };\n let usingApiKey = false;\n\n // Don't override if already set in environment\n if (!env.ANTHROPIC_API_KEY) {\n try {\n const config = await readConfig();\n if (config.anthropic_api_key) {\n env.ANTHROPIC_API_KEY = config.anthropic_api_key;\n usingApiKey = true;\n }\n } catch {\n // Config read failed \u2014 continue without API key\n }\n }\n\n return { env, usingApiKey };\n}\n\n/**\n * Build an actionable auth failure message with machine name and fix instructions.\n */\nexport function buildAuthFailureMessage(\n errorString: string,\n machineName: string,\n hasApiKeyFallback: boolean,\n): string {\n let msg = `CLAUDE_AUTH_REQUIRED: ${errorString}\\n`;\n msg += `Machine: ${machineName}\\n`;\n msg += `Fix: SSH into ${machineName} and run: claude /login\\n`;\n if (!hasApiKeyFallback) {\n msg += `Alternative: Set an API key fallback with: cva auth set-api-key sk-ant-...\\n`;\n }\n return msg;\n}\n\n// ============================================================================\n// Claude Code launcher\n// ============================================================================\n\nfunction buildClaudePrompt(task: Task): string {\n let prompt = '';\n prompt += `You are executing a task dispatched via CV-Hub.\\n\\n`;\n prompt += `## Task: ${task.title}\\n`;\n prompt += `Task ID: ${task.id}\\n`;\n prompt += `Priority: ${task.priority}\\n`;\n\n if (task.branch) prompt += `Branch: ${task.branch}\\n`;\n if (task.file_paths?.length) prompt += `Focus files: ${task.file_paths.join(', ')}\\n`;\n\n prompt += `\\n`;\n\n // Main instructions\n if (task.description) {\n prompt += task.description;\n } else if (task.input?.description) {\n prompt += task.input.description;\n }\n\n if (task.input?.context) {\n prompt += `\\n\\n## Context\\n${task.input.context}`;\n }\n\n if (task.input?.instructions?.length) {\n prompt += `\\n\\n## Instructions\\n`;\n task.input.instructions.forEach((i, idx) => {\n prompt += `${idx + 1}. ${i}\\n`;\n });\n }\n\n if (task.input?.constraints?.length) {\n prompt += `\\n\\n## Constraints\\n`;\n task.input.constraints.forEach(c => {\n prompt += `- ${c}\\n`;\n });\n }\n\n // Git & CV-Hub CLI instructions\n prompt += `\\n\\n## Git & CV-Hub Instructions\\n`;\n prompt += `You have the \\`cv\\` CLI (@controlvector/cv-git) available for all CV-Hub git operations.\\n`;\n prompt += `Use \\`cv\\` instead of raw \\`git\\` commands when interacting with CV-Hub repositories:\\n`;\n prompt += ` cv push # push to CV-Hub\\n`;\n prompt += ` cv pr create --title \"...\" # create pull request\\n`;\n prompt += ` cv issue list # list issues\\n`;\n prompt += ` cv repo info # repo details\\n`;\n prompt += `\\n`;\n prompt += `For standard git operations (commit, branch, diff, log, status), use regular \\`git\\` commands.\\n`;\n if (task.owner && task.repo) {\n prompt += `\\nTarget repository: ${task.owner}/${task.repo}\\n`;\n if (task.branch) prompt += `Target branch: ${task.branch}\\n`;\n }\n prompt += `\\n`;\n prompt += `IMPORTANT: Do NOT run \\`cva\\` commands. The \\`cva\\` binary is the agent daemon that launched you \u2014 calling it would cause recursion.\\n`;\n\n prompt += `\\n\\n---\\n`;\n prompt += `When complete, provide a brief summary of what you accomplished.\\n`;\n\n return prompt;\n}\n\n/** Shared reference to current child process so signal handlers can kill it */\nlet _activeChild: ChildProcess | null = null;\n\n/** Signal handling state */\nlet _sigintCount = 0;\nlet _sigintTimer: ReturnType<typeof setTimeout> | null = null;\nlet _signalHandlerInstalled = false;\n\nfunction installSignalHandlers(\n getState: () => AgentState,\n cleanup: () => Promise<void>,\n): void {\n if (_signalHandlerInstalled) return;\n _signalHandlerInstalled = true;\n\n process.on('SIGINT', async () => {\n if (!_activeChild) {\n console.log('\\n' + chalk.gray('Agent stopped.'));\n await cleanup();\n process.exit(0);\n }\n\n _sigintCount++;\n\n if (_sigintCount === 1) {\n console.log(`\\n${chalk.yellow('!')} Press Ctrl+C again within 3s to abort task.`);\n _sigintTimer = setTimeout(() => { _sigintCount = 0; }, 3000);\n return;\n }\n\n if (_sigintTimer) clearTimeout(_sigintTimer);\n console.log(`\\n${chalk.red('X')} Aborting task...`);\n try { _activeChild.kill('SIGKILL'); } catch {}\n _activeChild = null;\n _sigintCount = 0;\n });\n\n process.on('SIGTERM', async () => {\n console.log(`\\n${chalk.gray('Received SIGTERM, shutting down...')}`);\n if (_activeChild) {\n try { _activeChild.kill('SIGKILL'); } catch {}\n _activeChild = null;\n }\n await cleanup();\n process.exit(0);\n });\n}\n\n// ============================================================================\n// Permission handling\n// ============================================================================\n\n/** Tools to pre-approve when --auto-approve is active */\nconst ALLOWED_TOOLS = [\n 'Bash(*)', 'Read(*)', 'Write(*)', 'Edit(*)',\n 'Glob(*)', 'Grep(*)', 'WebFetch(*)', 'WebSearch(*)',\n 'NotebookEdit(*)', 'TodoWrite(*)',\n];\n\n/** Permission prompt patterns to detect in relay mode */\nconst PERMISSION_PATTERNS = [\n /Allow .+ to .+\\? \\(y\\/n\\)/,\n /Do you want to proceed\\? \\(y\\/n\\)/,\n /\\? \\(y\\/n\\)/,\n];\n\n// ============================================================================\n// Auto-approve mode launcher (proven, -p + --allowedTools)\n// ============================================================================\n\n/** Max output buffer size (200KB) \u2014 truncate to last 200KB if exceeded */\nconst MAX_OUTPUT_BYTES = 200 * 1024;\n\n/** Max size for output_final event content (50KB) */\nconst MAX_OUTPUT_FINAL_BYTES = 50 * 1024;\n\n/** Interval (in bytes) at which to post progress events with output chunks */\nconst OUTPUT_PROGRESS_INTERVAL = 4096;\n\nasync function launchAutoApproveMode(\n prompt: string,\n options: {\n cwd: string;\n creds?: CVHubCredentials;\n taskId?: string;\n executorId?: string;\n spawnEnv?: NodeJS.ProcessEnv;\n machineName?: string;\n },\n): Promise<{ exitCode: number; stderr: string; output: string; authFailure?: boolean }> {\n // Use a stable session ID so we can --continue if a question needs follow-up\n const sessionId = options.taskId\n ? options.taskId.replace(/-/g, '').slice(0, 32).padEnd(32, '0')\n .replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')\n : undefined;\n const pendingQuestionIds: string[] = [];\n\n let fullOutput = '';\n let lastProgressBytes = 0;\n\n const runOnce = (inputPrompt: string, isContinue: boolean): Promise<{ exitCode: number; stderr: string; output: string; authFailure: boolean }> => {\n return new Promise((resolve, reject) => {\n const args: string[] = isContinue\n ? ['-p', inputPrompt, '--continue', '--allowedTools', ...ALLOWED_TOOLS]\n : ['-p', inputPrompt, '--allowedTools', ...ALLOWED_TOOLS];\n\n if (sessionId && !isContinue) {\n args.push('--session-id', sessionId);\n }\n\n const child = spawn('claude', args, {\n cwd: options.cwd,\n stdio: ['inherit', 'pipe', 'pipe'],\n env: options.spawnEnv || { ...process.env },\n });\n\n _activeChild = child;\n let stderr = '';\n let lineBuffer = '';\n let authFailure = false;\n const spawnTime = Date.now();\n\n child.stdout?.on('data', (data: Buffer) => {\n const text = data.toString();\n process.stdout.write(data);\n\n // Accumulate full output (capped at MAX_OUTPUT_BYTES)\n fullOutput += text;\n if (fullOutput.length > MAX_OUTPUT_BYTES) {\n fullOutput = fullOutput.slice(-MAX_OUTPUT_BYTES);\n }\n\n // Early exit detection: check first 10s for auth errors\n if (Date.now() - spawnTime < 10_000) {\n const authError = containsAuthError(fullOutput + stderr);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure detected: \"${authError}\"`);\n console.log(chalk.yellow(` Killing process \u2014 it won't recover without re-authentication.`));\n if (options.machineName) {\n console.log(chalk.cyan(` Fix: SSH into ${options.machineName} and run: claude /login`));\n }\n try { child.kill('SIGTERM'); } catch {}\n return;\n }\n }\n\n if (options.creds && options.taskId) {\n lineBuffer += text;\n const lines = lineBuffer.split('\\n');\n lineBuffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const event = parseClaudeCodeOutput(line);\n if (event) {\n postTaskEvent(options.creds, options.taskId, {\n event_type: event.eventType,\n content: event.content,\n needs_response: event.needsResponse,\n }).then((created) => {\n if (event.needsResponse && created?.id) {\n pendingQuestionIds.push(created.id);\n }\n }).catch(() => {});\n }\n }\n\n // Post periodic progress with output chunk\n if (fullOutput.length - lastProgressBytes >= OUTPUT_PROGRESS_INTERVAL) {\n const chunk = fullOutput.slice(lastProgressBytes).slice(-OUTPUT_PROGRESS_INTERVAL);\n lastProgressBytes = fullOutput.length;\n if (options.executorId) {\n sendTaskLog(options.creds!, options.executorId, options.taskId!, 'progress',\n 'Claude Code output', { output_chunk: chunk }).catch(() => {});\n }\n // Also post as output event for cv_task_summary/stream visibility\n postTaskEvent(options.creds!, options.taskId!, {\n event_type: 'output',\n content: { chunk, byte_offset: lastProgressBytes },\n }).catch(() => {});\n }\n }\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n const text = data.toString();\n stderr += text;\n process.stderr.write(data);\n\n // Early exit detection on stderr too\n if (Date.now() - spawnTime < 10_000 && !authFailure) {\n const authError = containsAuthError(text);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure (stderr): \"${authError}\"`);\n try { child.kill('SIGTERM'); } catch {}\n }\n }\n });\n\n child.on('close', (code, signal) => {\n _activeChild = null;\n resolve({\n exitCode: signal === 'SIGKILL' ? 137 : (code ?? 1),\n stderr, output: fullOutput,\n authFailure,\n });\n });\n\n child.on('error', (err) => {\n _activeChild = null;\n reject(err);\n });\n });\n };\n\n // Initial run\n let result = await runOnce(prompt, false);\n\n // If there were unanswered questions and the task isn't aborted,\n // attempt to continue with responses (up to 3 follow-ups)\n if (options.creds && options.taskId && result.exitCode === 0) {\n let followUps = 0;\n while (pendingQuestionIds.length > 0 && followUps < 3) {\n const questionId = pendingQuestionIds.shift()!;\n console.log(chalk.gray(` [auto-approve] Waiting for planner response to question...`));\n\n const response = await pollForEventResponse(\n options.creds, options.taskId, questionId, 300_000,\n );\n\n if (response) {\n const responseText = typeof response === 'string' ? response : JSON.stringify(response);\n console.log(chalk.gray(` [auto-approve] Planner responded, continuing with --continue`));\n result = await runOnce(responseText, true);\n followUps++;\n } else {\n console.log(chalk.yellow(` [auto-approve] No response received, continuing without.`));\n break;\n }\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Relay mode launcher (interactive, permission prompts relayed to CV-Hub)\n// ============================================================================\n\nasync function launchRelayMode(\n prompt: string,\n options: {\n cwd: string;\n creds: CVHubCredentials;\n executorId: string;\n taskId: string;\n spawnEnv?: NodeJS.ProcessEnv;\n machineName?: string;\n },\n): Promise<{ exitCode: number; stderr: string; output: string; authFailure?: boolean }> {\n return new Promise((resolve, reject) => {\n // Spawn Claude Code in interactive mode (no -p flag)\n const child = spawn('claude', [], {\n cwd: options.cwd,\n stdio: ['pipe', 'pipe', 'pipe'],\n env: options.spawnEnv || { ...process.env },\n });\n\n _activeChild = child;\n let stderr = '';\n let stdoutBuffer = '';\n let fullOutput = '';\n let lastProgressBytes = 0;\n let authFailure = false;\n const spawnTime = Date.now();\n\n // Send the task prompt as initial input\n child.stdin?.write(prompt + '\\n');\n\n let lastRedirectCheck = Date.now();\n let lineBuffer = '';\n\n // Tee stdout to terminal while scanning for permission patterns + structured markers\n child.stdout?.on('data', async (data: Buffer) => {\n const text = data.toString();\n process.stdout.write(data); // Tee to terminal\n stdoutBuffer += text;\n\n // Accumulate full output (capped at MAX_OUTPUT_BYTES)\n fullOutput += text;\n if (fullOutput.length > MAX_OUTPUT_BYTES) {\n fullOutput = fullOutput.slice(-MAX_OUTPUT_BYTES);\n }\n\n // Early exit detection: check first 10s for auth errors\n if (Date.now() - spawnTime < 10_000 && !authFailure) {\n const authError = containsAuthError(fullOutput + stderr);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure detected: \"${authError}\"`);\n try { child.kill('SIGTERM'); } catch {}\n return;\n }\n }\n\n // Parse line-by-line for structured markers\n lineBuffer += text;\n const lines = lineBuffer.split('\\n');\n lineBuffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const event = parseClaudeCodeOutput(line);\n if (event) {\n try {\n const created = await postTaskEvent(options.creds, options.taskId, {\n event_type: event.eventType,\n content: event.content,\n needs_response: event.needsResponse,\n });\n\n // If question, wait for response via task events\n if (event.needsResponse && created?.id) {\n console.log(chalk.gray(` [stream] Question detected, waiting for planner response...`));\n const response = await pollForEventResponse(\n options.creds, options.taskId, created.id, 300_000,\n );\n if (response) {\n const responseText = typeof response === 'string' ? response : JSON.stringify(response);\n child.stdin?.write(responseText + '\\n');\n console.log(chalk.gray(` [stream] Planner responded.`));\n } else {\n child.stdin?.write('[No response received within timeout. Continue with your best judgment.]\\n');\n console.log(chalk.yellow(` [stream] Question timed out.`));\n }\n }\n } catch {\n // Non-fatal: don't block execution\n }\n }\n }\n\n // Post periodic progress with output chunk\n if (fullOutput.length - lastProgressBytes >= OUTPUT_PROGRESS_INTERVAL) {\n const chunk = fullOutput.slice(lastProgressBytes).slice(-OUTPUT_PROGRESS_INTERVAL);\n lastProgressBytes = fullOutput.length;\n sendTaskLog(options.creds, options.executorId, options.taskId, 'progress',\n 'Claude Code output', { output_chunk: chunk }).catch(() => {});\n // Also post as output event for cv_task_summary/stream visibility\n postTaskEvent(options.creds, options.taskId, {\n event_type: 'output',\n content: { chunk, byte_offset: lastProgressBytes },\n }).catch(() => {});\n }\n\n // Periodic redirect check (every 10 seconds)\n if (Date.now() - lastRedirectCheck > 10_000) {\n try {\n const redirects = await getRedirects(\n options.creds, options.taskId,\n new Date(lastRedirectCheck).toISOString(),\n );\n for (const redirect of redirects) {\n const instruction = redirect.content?.instruction;\n if (instruction) {\n child.stdin?.write(`\\n[REDIRECT FROM PLANNER]: ${instruction}\\n`);\n console.log(chalk.gray(` [stream] Redirect received from planner.`));\n }\n }\n } catch {\n // Non-fatal\n }\n lastRedirectCheck = Date.now();\n }\n\n // Check for permission prompts (existing relay logic)\n for (const pattern of PERMISSION_PATTERNS) {\n const match = stdoutBuffer.match(pattern);\n if (match) {\n const promptText = match[0];\n stdoutBuffer = ''; // Reset buffer after match\n\n try {\n await sendTaskLog(\n options.creds,\n options.executorId,\n options.taskId,\n 'info',\n `Permission prompt: ${promptText}`,\n { prompt_text: promptText },\n );\n\n const { prompt_id } = await createTaskPrompt(\n options.creds,\n options.executorId,\n options.taskId,\n promptText,\n 'approval',\n ['y', 'n'],\n );\n\n // Also emit as approval_request event\n postTaskEvent(options.creds, options.taskId, {\n event_type: 'approval_request',\n content: { prompt_text: promptText },\n needs_response: true,\n }).catch(() => {});\n\n const timeoutMs = 5 * 60 * 1000;\n const startPoll = Date.now();\n let answered = false;\n\n while (Date.now() - startPoll < timeoutMs) {\n await new Promise(r => setTimeout(r, 2000));\n\n try {\n const { response } = await pollPromptResponse(\n options.creds,\n options.executorId,\n options.taskId,\n prompt_id,\n );\n\n if (response !== null) {\n const answer = response.toLowerCase().startsWith('y') ? 'y' : 'n';\n child.stdin?.write(answer + '\\n');\n answered = true;\n console.log(chalk.gray(` [relay] User responded: ${answer}`));\n break;\n }\n } catch {\n // Poll error \u2014 continue\n }\n }\n\n if (!answered) {\n child.stdin?.write('n\\n');\n console.log(chalk.yellow(` [relay] Prompt timed out, denying.`));\n }\n } catch (err: any) {\n child.stdin?.write('n\\n');\n console.log(chalk.yellow(` [relay] Prompt relay error: ${err.message}, denying.`));\n }\n\n break;\n }\n }\n\n // Keep buffer manageable (only last 2KB)\n if (stdoutBuffer.length > 2048) {\n stdoutBuffer = stdoutBuffer.slice(-1024);\n }\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n const text = data.toString();\n stderr += text;\n process.stderr.write(data);\n\n // Early exit detection on stderr\n if (Date.now() - spawnTime < 10_000 && !authFailure) {\n const authError = containsAuthError(text);\n if (authError) {\n authFailure = true;\n console.log(`\\n${chalk.red('!')} Claude Code auth failure (stderr): \"${authError}\"`);\n try { child.kill('SIGTERM'); } catch {}\n }\n }\n });\n\n child.on('close', (code, signal) => {\n _activeChild = null;\n if (signal === 'SIGKILL') {\n resolve({ exitCode: 137, stderr, output: fullOutput, authFailure });\n } else {\n resolve({ exitCode: code ?? 1, stderr, output: fullOutput, authFailure });\n }\n });\n\n child.on('error', (err) => {\n _activeChild = null;\n reject(err);\n });\n });\n}\n\n// ============================================================================\n// Event response polling\n// ============================================================================\n\nasync function pollForEventResponse(\n creds: CVHubCredentials,\n taskId: string,\n eventId: string,\n timeoutMs: number,\n): Promise<unknown | null> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n await new Promise(r => setTimeout(r, 3000));\n try {\n const result = await getEventResponse(creds, taskId, eventId);\n if (result.response !== null) {\n return result.response;\n }\n } catch {\n // Continue polling\n }\n }\n return null;\n}\n\n// ============================================================================\n// Self-update handler\n// ============================================================================\n\nasync function handleSelfUpdate(\n task: Task,\n state: AgentState,\n creds: CVHubCredentials,\n): Promise<void> {\n const startTime = Date.now();\n try {\n await startTask(creds, state.executorId, task.id);\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle', 'Self-update started');\n\n const source = (task.input?.description || task.description || 'npm').trim();\n let output = '';\n\n if (source === 'npm' || source.startsWith('npm:')) {\n const pkg = source === 'npm' ? '@controlvector/cv-agent@latest' : source.replace('npm:', '');\n output = execSync(`npm install -g ${pkg} 2>&1`, { encoding: 'utf8', timeout: 120_000 });\n } else if (source.startsWith('git:')) {\n const repoPath = source.replace('git:', '');\n output = execSync(`cd ${repoPath} && git pull && npm install && npm run build && npm link 2>&1`, {\n encoding: 'utf8', timeout: 300_000,\n });\n } else {\n // Default: try npm\n output = execSync(`npm install -g @controlvector/cv-agent@latest 2>&1`, { encoding: 'utf8', timeout: 120_000 });\n }\n\n let newVersion = 'unknown';\n try {\n newVersion = execSync('cva --version 2>/dev/null || echo unknown', { encoding: 'utf8' }).trim();\n } catch {}\n\n // Post output as event so planner can see it\n postTaskEvent(creds, task.id, {\n event_type: 'output_final',\n content: { output: output.slice(-10000), new_version: newVersion },\n }).catch(() => {});\n\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n `Self-update completed. New version: ${newVersion}`, { output: output.slice(-5000) }, 100);\n\n await completeTask(creds, state.executorId, task.id, {\n summary: `Updated to ${newVersion}`,\n exit_code: 0,\n stats: { duration_seconds: Math.round((Date.now() - startTime) / 1000) },\n });\n state.completedCount++;\n\n // Restart if requested\n if (task.input?.constraints?.includes('restart')) {\n console.log(chalk.yellow('Restarting agent with updated binary...'));\n const args = process.argv.slice(1).join(' ');\n execSync(`nohup cva ${args} > /tmp/cva-restart.log 2>&1 &`, { stdio: 'ignore' });\n process.exit(0);\n }\n } catch (err: any) {\n sendTaskLog(creds, state.executorId, task.id, 'error', `Self-update failed: ${err.message}`);\n try { await failTask(creds, state.executorId, task.id, err.message); } catch {}\n state.failedCount++;\n } finally {\n state.currentTaskId = null;\n state.lastTaskEnd = Date.now();\n }\n}\n\n// ============================================================================\n// Main agent loop\n// ============================================================================\n\nasync function runAgent(options: AgentOptions): Promise<void> {\n const creds = await readCredentials();\n\n if (!creds.CV_HUB_API) {\n creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n }\n\n if (!creds.CV_HUB_PAT) {\n console.log();\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n console.log();\n console.log(chalk.bold('Quick setup:'));\n console.log(` ${chalk.cyan('cva auth login')} # Authenticate`);\n console.log(` ${chalk.cyan('cd ~/project/my-project')} # Go to your project`);\n console.log(` ${chalk.cyan('cva agent')} # Start listening`);\n console.log();\n process.exit(1);\n }\n\n // Claude Code check (binary + auth pre-flight)\n try {\n execSync('claude --version', { stdio: 'pipe', timeout: 5000 });\n } catch {\n console.log();\n console.log(chalk.red('Claude Code CLI not found.') + ' Install it first:');\n console.log(` ${chalk.cyan('npm install -g @anthropic-ai/claude-code')}`);\n console.log();\n process.exit(1);\n }\n\n // Pre-flight auth check\n const { env: claudeEnv, usingApiKey } = await getClaudeEnv();\n const authCheck = await checkClaudeAuth();\n let currentAuthStatus: AuthStatus = authCheck.status;\n\n if (authCheck.status === 'expired') {\n if (usingApiKey) {\n console.log(chalk.yellow('!') + ' Claude Code OAuth expired, but API key fallback is configured.');\n currentAuthStatus = 'api_key_fallback';\n } else {\n console.log();\n console.log(chalk.red('Claude Code auth expired: ') + chalk.yellow(authCheck.error || 'unknown'));\n console.log(` Fix: Run ${chalk.cyan('claude /login')} to re-authenticate.`);\n console.log(` Alternative: ${chalk.cyan('cva auth set-api-key sk-ant-...')} for API key fallback.`);\n console.log();\n console.log(chalk.gray('Agent will start but pause task claims until auth is resolved.'));\n console.log();\n }\n } else if (usingApiKey) {\n console.log(chalk.gray(' Using Anthropic API key from config as fallback.'));\n currentAuthStatus = 'api_key_fallback';\n }\n\n // cv-git check (warn, don't block)\n try {\n execSync('cv --version', { stdio: 'pipe', timeout: 5000 });\n } catch {\n console.log(chalk.yellow('!') + ' cv-git CLI not found. Claude Code will fall back to raw git commands.');\n console.log(` Install it: ${chalk.cyan('npm install -g @controlvector/cv-git')}`);\n console.log();\n }\n\n const machineName = options.machine || await getMachineName();\n const pollInterval = Math.max(3, parseInt(options.pollInterval, 10)) * 1000;\n const workingDir = options.workingDir === '.' ? process.cwd() : options.workingDir;\n\n if (!options.machine) {\n const credCheck = await readCredentials();\n if (!credCheck.CV_HUB_MACHINE_NAME) {\n console.log();\n console.log(chalk.yellow('!') + ` No machine name set. Registering as \"${chalk.bold(machineName)}\".`);\n console.log(chalk.gray(` Use --machine <name> to override.`));\n console.log();\n }\n }\n\n // Auto-detect CV-Hub repository from git remote\n let detectedRepoId: string | undefined;\n try {\n const remoteUrl = execSync('git remote get-url origin 2>/dev/null', {\n cwd: workingDir,\n encoding: 'utf8',\n timeout: 5000,\n }).trim();\n\n const cvHubMatch = remoteUrl.match(\n /git\\.hub\\.controlvector\\.io[:/]([^/]+)\\/([^/.]+)/\n );\n\n if (cvHubMatch) {\n const [, repoOwner, repoSlug] = cvHubMatch;\n try {\n const repoData = await resolveRepoId(creds, repoOwner, repoSlug);\n if (repoData?.id) {\n detectedRepoId = repoData.id;\n console.log(chalk.gray(` Repo: ${repoOwner}/${repoSlug}`));\n }\n } catch {\n // API call failed \u2014 register without repo binding\n }\n }\n } catch {\n // Not a git repo or no origin remote \u2014 that's fine\n }\n\n // Resolve executor identity metadata\n // Priority: CLI flags > workspace .cva/agent.json > global config\n const wsConfig = await readWorkspaceConfig(workingDir);\n const globalConfig = await readConfig();\n\n const role = (options.role || wsConfig.role || globalConfig.role || 'development') as ExecutorRole;\n const dispatchGuard = (options.dispatchGuard || wsConfig.dispatch_guard || globalConfig.dispatch_guard || 'open') as DispatchGuard;\n const tags = (options.tags?.split(',') || wsConfig.tags || globalConfig.tags)?.map((t: string) => t.trim()).filter(Boolean);\n const ownerProject = options.ownerProject || wsConfig.owner_project || globalConfig.owner_project;\n\n let integration: ExecutorIntegration | undefined;\n if (options.integration || wsConfig.integration) {\n if (options.integration) {\n // Build from CLI flags\n const safeTasks = options.safeTasks?.split(',').map(t => t.trim()).filter(Boolean);\n const unsafeTasks = safeTasks\n ? ['code_change', 'deploy', 'test', 'custom'].filter(t => !safeTasks.includes(t))\n : undefined;\n integration = {\n system: options.integration,\n description: options.integrationDescription || `Integrated into ${options.integration}`,\n service_port: options.integrationPort ? parseInt(options.integrationPort, 10) : undefined,\n safe_task_types: safeTasks,\n unsafe_task_types: unsafeTasks,\n };\n } else if (wsConfig.integration) {\n integration = wsConfig.integration;\n }\n }\n\n const executorMeta: import('../utils/api.js').ExecutorRegistrationMetadata = {\n role,\n dispatch_guard: dispatchGuard,\n tags,\n owner_project: ownerProject,\n integration,\n };\n\n // Display identity in banner\n if (role !== 'development') {\n console.log(chalk.yellow(` Role: ${role}`));\n }\n if (integration) {\n console.log(chalk.yellow(` Integration: ${integration.system}${integration.service_port ? ` (port ${integration.service_port})` : ''}`));\n }\n if (dispatchGuard !== 'open') {\n const guardIcon = dispatchGuard === 'locked' ? '\uD83D\uDD12' : '\u26A0\uFE0F';\n console.log(chalk.yellow(` Guard: ${guardIcon} ${dispatchGuard}`));\n }\n\n // Register executor\n const executor = await withRetry(\n () => registerExecutor(creds, machineName, workingDir, detectedRepoId, executorMeta),\n 'Executor registration',\n );\n\n // Display banner\n const mode = options.autoApprove ? 'auto-approve' : 'relay';\n console.log();\n console.log(chalk.bold('CVA \u2014 CV-Hub Agent'));\n console.log(` Machine: ${chalk.cyan(machineName)}`);\n console.log(` Executor: ${chalk.gray(executor.id)}`);\n console.log(` API: ${chalk.gray(creds.CV_HUB_API)}`);\n console.log(` Dir: ${chalk.gray(workingDir)}`);\n console.log(` Polling: every ${options.pollInterval}s`);\n console.log(` Mode: ${chalk.cyan(mode)}`);\n console.log(` Ctrl+C to stop`);\n console.log();\n console.log(chalk.cyan('Listening for tasks...'));\n console.log();\n\n const state: AgentState = {\n executorId: executor.id,\n currentTaskId: null,\n completedCount: 0,\n failedCount: 0,\n lastPoll: Date.now(),\n lastTaskEnd: Date.now(),\n running: true,\n authStatus: currentAuthStatus,\n machineName,\n };\n\n installSignalHandlers(\n () => state,\n async () => {\n state.running = false;\n await markOffline(creds, state.executorId);\n },\n );\n\n // Main loop\n while (state.running) {\n try {\n // If auth is expired (no fallback), re-check periodically instead of claiming tasks\n if (state.authStatus === 'expired') {\n const recheck = await checkClaudeAuth();\n if (recheck.status === 'authenticated') {\n state.authStatus = 'authenticated';\n console.log(`\\n${chalk.green('\u2713')} Claude Code auth restored. Resuming task claims.`);\n } else {\n // Still expired \u2014 heartbeat but don't poll for tasks\n sendHeartbeat(creds, state.executorId, undefined, undefined, state.authStatus).catch(() => {});\n await new Promise(r => setTimeout(r, pollInterval));\n continue;\n }\n }\n\n const task = await withRetry(\n () => pollForTask(creds, state.executorId),\n 'Task poll',\n );\n state.lastPoll = Date.now();\n\n if (task) {\n await executeTask(task, state, creds, options, claudeEnv);\n } else {\n updateStatusLine(\n formatDuration(Date.now() - state.lastTaskEnd),\n formatDuration(Date.now() - state.lastPoll),\n state.completedCount,\n state.failedCount,\n );\n }\n } catch (err: any) {\n console.log(`\\n${chalk.red('!')} Error: ${err.message}`);\n }\n\n await new Promise(r => setTimeout(r, pollInterval));\n }\n}\n\nasync function executeTask(\n task: Task,\n state: AgentState,\n creds: CVHubCredentials,\n options: AgentOptions,\n claudeEnv?: NodeJS.ProcessEnv,\n): Promise<void> {\n const startTime = Date.now();\n state.currentTaskId = task.id;\n\n // Handle system update tasks \u2014 no Claude Code, just self-update\n if (task.task_type === '_system_update') {\n await handleSelfUpdate(task, state, creds);\n return;\n }\n\n // Clear status line\n process.stdout.write('\\r\\x1b[K');\n\n // Task received\n console.log(`\uD83D\uDCE5 ${chalk.bold.cyan('RECEIVED')} \u2014 Task: ${task.title} (${task.priority})`);\n\n // Task header\n console.log(chalk.bold('\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510'));\n console.log(chalk.bold(`\u2502 Task: ${(task.title || '').substring(0, 53).padEnd(53)}\u2502`));\n console.log(chalk.bold(`\u2502 ID: ${task.id.padEnd(55)}\u2502`));\n console.log(chalk.bold(`\u2502 Priority: ${task.priority.padEnd(49)}\u2502`));\n console.log(chalk.bold('\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518'));\n console.log();\n\n // Mark task as running\n try {\n await startTask(creds, state.executorId, task.id);\n setTerminalTitle(`cva: ${task.title} (starting...)`);\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle', 'Task started, launching Claude Code');\n } catch (err: any) {\n console.log(chalk.red(`Failed to start task: ${err.message}`));\n state.currentTaskId = null;\n return;\n }\n\n // Heartbeat timer\n const heartbeatTimer = setInterval(async () => {\n try {\n const elapsed = formatDuration(Date.now() - startTime);\n setTerminalTitle(`cva: ${task.title} (${elapsed})`);\n await sendHeartbeat(creds, state.executorId, task.id, `Claude Code running (${elapsed} elapsed)`, state.authStatus);\n } catch {}\n }, 30_000);\n\n // Timeout timer\n let timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n if (task.timeout_at) {\n const timeoutMs = new Date(task.timeout_at).getTime() - Date.now();\n if (timeoutMs > 0) {\n timeoutTimer = setTimeout(() => {\n console.log(`\\n${chalk.red('Timeout')} Task timed out after ${formatDuration(timeoutMs)}`);\n }, timeoutMs);\n }\n }\n\n // Capture pre-task git state\n const preGitState = capturePreTaskState(options.workingDir);\n\n // Verify/fix git remote\n const gitHost = (creds.CV_HUB_API || 'https://api.hub.controlvector.io')\n .replace(/^https?:\\/\\//, '')\n .replace(/^api\\./, 'git.');\n const remoteInfo = verifyGitRemote(options.workingDir, task, gitHost);\n if (remoteInfo) {\n console.log(chalk.gray(` Git remote: ${remoteInfo.remoteName} -> ${remoteInfo.remoteUrl}`));\n }\n\n // Build prompt and launch\n const prompt = buildClaudePrompt(task);\n\n try {\n const mode = options.autoApprove ? 'auto-approve' : 'relay';\n console.log(`\uD83D\uDE80 ${chalk.bold.green('RUNNING')} \u2014 Launching Claude Code (${mode})...`);\n if (options.autoApprove) {\n console.log(chalk.gray(' Allowed tools: ') + ALLOWED_TOOLS.join(', '));\n }\n console.log(chalk.gray('-'.repeat(60)));\n\n let result: { exitCode: number; stderr: string; output: string; authFailure?: boolean };\n\n if (options.autoApprove) {\n result = await launchAutoApproveMode(prompt, {\n cwd: options.workingDir,\n creds,\n taskId: task.id,\n executorId: state.executorId,\n spawnEnv: claudeEnv,\n machineName: state.machineName,\n });\n } else {\n result = await launchRelayMode(prompt, {\n cwd: options.workingDir,\n creds,\n executorId: state.executorId,\n taskId: task.id,\n spawnEnv: claudeEnv,\n machineName: state.machineName,\n });\n }\n\n console.log(chalk.gray('\\n' + '-'.repeat(60)));\n\n // \u2500\u2500 Git Safety Net \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Ensure everything Claude Code touched is committed and pushed.\n // This runs even if Claude Code already committed \u2014 it catches:\n // - Untracked files Claude forgot to add\n // - Modified files Claude forgot to stage\n // - Commits Claude made but forgot to push\n if (result.exitCode === 0 || result.exitCode === 1) {\n try {\n const gitSafety = gitSafetyNet(\n options.workingDir, task.title, task.id, task.branch,\n );\n if (gitSafety.hadChanges) {\n sendTaskLog(creds, state.executorId, task.id, 'git',\n `Safety net: committed ${gitSafety.filesAdded + gitSafety.filesModified} files (${gitSafety.commitSha || 'ok'})`,\n { added: gitSafety.filesAdded, modified: gitSafety.filesModified, deleted: gitSafety.filesDeleted });\n } else if (gitSafety.pushed) {\n sendTaskLog(creds, state.executorId, task.id, 'git', 'Safety net: pushed unpushed commits');\n }\n if (gitSafety.error) {\n sendTaskLog(creds, state.executorId, task.id, 'info', `Git safety warning: ${gitSafety.error}`);\n }\n } catch (gitErr: any) {\n // Non-fatal \u2014 don't fail the task over git safety\n sendTaskLog(creds, state.executorId, task.id, 'info', `Git safety net error: ${gitErr.message}`);\n }\n }\n\n // Capture post-task git state (AFTER safety net so it includes safety net commits)\n const postGitState = capturePostTaskState(options.workingDir, preGitState);\n const payload = buildCompletionPayload(result.exitCode, preGitState, postGitState, startTime, result.output);\n const elapsed = formatDuration(Date.now() - startTime);\n const allChangedFiles = [\n ...postGitState.filesAdded,\n ...postGitState.filesModified,\n ...postGitState.filesDeleted,\n ];\n\n // \u2500\u2500 Post-Task Deploy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // If .cva/deploy.json exists, run build \u2192 migrate \u2192 restart \u2192 verify\n let deployResult: { deployed: boolean; error?: string; rolledBack?: boolean } | undefined;\n if (result.exitCode === 0) {\n try {\n const logFn = (type: string, msg: string) => {\n sendTaskLog(creds, state.executorId, task.id, type, msg);\n };\n deployResult = await postTaskDeploy(options.workingDir, task.id, logFn);\n if (deployResult.deployed) {\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle', 'Post-task deploy: verified');\n } else if (deployResult.error) {\n sendTaskLog(creds, state.executorId, task.id, 'error',\n `Post-task deploy failed: ${deployResult.error}${deployResult.rolledBack ? ' (rolled back)' : ''}`);\n }\n } catch (deployErr: any) {\n sendTaskLog(creds, state.executorId, task.id, 'info', `Deploy manifest error: ${deployErr.message}`);\n }\n }\n\n // Emit completion event via task events\n postTaskEvent(creds, task.id, {\n event_type: 'completed',\n content: {\n exit_code: result.exitCode,\n duration_seconds: Math.round((Date.now() - startTime) / 1000),\n files_changed: allChangedFiles.length,\n },\n }).catch(() => {});\n\n if (result.exitCode === 0) {\n if (allChangedFiles.length > 0) {\n sendTaskLog(creds, state.executorId, task.id, 'git',\n `${allChangedFiles.length} file(s) changed (+${postGitState.linesAdded}/-${postGitState.linesDeleted})`,\n { added: postGitState.filesAdded.slice(0, 10), modified: postGitState.filesModified.slice(0, 10), deleted: postGitState.filesDeleted.slice(0, 10) });\n }\n\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n `Claude Code completed successfully (${elapsed})`, undefined, 100);\n\n console.log();\n console.log(`\u2705 ${chalk.bold.green('COMPLETED')} \u2014 Duration: ${elapsed}`);\n printBanner('COMPLETED', elapsed, allChangedFiles, postGitState.headSha);\n\n // Post final output as event for planner visibility\n postTaskEvent(creds, task.id, {\n event_type: 'output_final',\n content: {\n output: result.output.slice(-MAX_OUTPUT_FINAL_BYTES),\n exit_code: result.exitCode,\n duration_seconds: Math.round((Date.now() - startTime) / 1000),\n },\n }).catch(() => {});\n\n await withRetry(\n () => completeTask(creds, state.executorId, task.id, payload as unknown as Record<string, unknown>),\n 'Report completion',\n );\n state.completedCount++;\n\n console.log(chalk.gray(' Reported to CV-Hub.'));\n } else if (result.exitCode === 137) {\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n 'Task aborted by user (Ctrl+C)');\n\n console.log();\n console.log(`\u23F9 ${chalk.bold.yellow('ABORTED')} \u2014 Duration: ${elapsed}`);\n printBanner('ABORTED', elapsed, [], null);\n\n try {\n await failTask(creds, state.executorId, task.id, 'Aborted by user (Ctrl+C)');\n } catch {}\n state.failedCount++;\n } else if (result.authFailure) {\n // Auth failure \u2014 produce actionable error message\n const authErrorStr = containsAuthError(result.output + result.stderr) || 'auth failure';\n const hasApiKey = !!(claudeEnv?.ANTHROPIC_API_KEY);\n const authMsg = buildAuthFailureMessage(authErrorStr, state.machineName, hasApiKey);\n\n sendTaskLog(creds, state.executorId, task.id, 'error', authMsg);\n\n console.log();\n console.log(`\uD83D\uDD11 ${chalk.bold.red('AUTH FAILED')} \u2014 Claude Code is not authenticated`);\n console.log(chalk.yellow(` ${authMsg.replace(/\\n/g, '\\n ')}`));\n\n // Emit specific auth failure event\n postTaskEvent(creds, task.id, {\n event_type: 'auth_failure',\n content: {\n error: authErrorStr,\n machine: state.machineName,\n fix_command: `claude /login`,\n api_key_configured: hasApiKey,\n },\n }).catch(() => {});\n\n await withRetry(\n () => failTask(creds, state.executorId, task.id, authMsg),\n 'Report auth failure',\n );\n state.failedCount++;\n\n // Set auth status to expired so we stop claiming tasks\n state.authStatus = 'expired';\n console.log(chalk.yellow(' Pausing task claims until auth is restored.'));\n } else {\n const stderrTail = result.stderr.trim().slice(-500);\n sendTaskLog(creds, state.executorId, task.id, 'lifecycle',\n `Claude Code exited with code ${result.exitCode} (${elapsed})`,\n stderrTail ? { stderr_tail: stderrTail } : undefined);\n\n console.log();\n console.log(`\u274C ${chalk.bold.red('FAILED')} \u2014 Duration: ${elapsed} (exit code ${result.exitCode})`);\n printBanner('FAILED', elapsed, allChangedFiles, postGitState.headSha);\n\n const errorDetail = result.stderr.trim()\n ? `${result.stderr.trim().slice(-1500)}\\n\\nExit code ${result.exitCode} after ${elapsed}.`\n : `Claude Code exited with code ${result.exitCode} after ${elapsed}.`;\n\n await withRetry(\n () => failTask(creds, state.executorId, task.id, errorDetail),\n 'Report failure',\n );\n state.failedCount++;\n }\n } catch (err: any) {\n console.log(`\\n${chalk.red('!')} Task error: ${err.message}`);\n\n sendTaskLog(creds, state.executorId, task.id, 'error',\n `Agent error: ${err.message}`);\n\n try {\n await failTask(creds, state.executorId, task.id, err.message);\n } catch {}\n state.failedCount++;\n } finally {\n clearInterval(heartbeatTimer);\n if (timeoutTimer) clearTimeout(timeoutTimer);\n state.currentTaskId = null;\n state.lastTaskEnd = Date.now();\n }\n\n setTerminalTitle('cva: listening...');\n console.log();\n console.log(chalk.cyan('Listening for tasks...'));\n console.log();\n}\n\n// ============================================================================\n// Command definition\n// ============================================================================\n\nexport function agentCommand(): Command {\n const cmd = new Command('agent');\n cmd.description('Listen for tasks dispatched via CV-Hub and execute them with Claude Code');\n\n cmd.option('--machine <name>', 'Override auto-detected machine name');\n cmd.option('--poll-interval <seconds>', 'How often to check for tasks, minimum 3 (default: 5)', '5');\n cmd.option('--working-dir <path>', 'Working directory for Claude Code (default: current directory)', '.');\n cmd.option('--auto-approve', 'Pre-approve all tool permissions (uses -p mode)', false);\n cmd.option('--role <role>', 'Executor role: development, production, ci, staging');\n cmd.option('--integration <system>', 'System this executor is integrated into (e.g. nyx-forge)');\n cmd.option('--integration-description <desc>', 'Description of the integration');\n cmd.option('--integration-port <port>', 'Port the integrated service runs on');\n cmd.option('--safe-tasks <types>', 'Comma-separated task types safe for this executor (e.g. review,research)');\n cmd.option('--dispatch-guard <guard>', 'Dispatch guard: open, confirm, locked (default: open)');\n cmd.option('--tags <tags>', 'Comma-separated tags for this executor');\n cmd.option('--owner-project <project>', 'Project this executor belongs to');\n\n cmd.action(async (opts: AgentOptions) => {\n await runAgent(opts);\n });\n\n return cmd;\n}\n", "const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n", "import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-ghostty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'wezterm') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n", "// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n", "import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` \u2192 `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n", "/**\n * CV-Hub credentials file utilities\n *\n * Reads/writes the CV-Hub credentials file (~/.config/cv-hub/credentials)\n * which uses simple KEY=VALUE format (sourced by shell hooks).\n */\n\nimport { promises as fs } from 'fs';\nimport { homedir } from 'os';\nimport { join, dirname } from 'path';\nimport * as os from 'os';\n\n/** Standard paths to search for credentials, in priority order */\nexport const CREDENTIAL_PATHS = [\n join(homedir(), '.config', 'cv-hub', 'credentials'),\n '/root/.config/cv-hub/credentials',\n];\n\nexport interface CVHubCredentials {\n CV_HUB_PAT?: string;\n CV_HUB_API?: string;\n CV_HUB_MACHINE_NAME?: string;\n CV_HUB_ORG_OVERRIDE?: string;\n CV_HUB_DEBUG?: string;\n [key: string]: string | undefined;\n}\n\n/**\n * Find the first existing credentials file path\n */\nexport async function findCredentialFile(): Promise<string | null> {\n for (const p of CREDENTIAL_PATHS) {\n try {\n await fs.access(p);\n return p;\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/**\n * Read and parse the CV-Hub credentials file.\n * Parses KEY=VALUE lines, ignoring comments (#) and empty lines.\n */\nexport async function readCredentials(): Promise<CVHubCredentials> {\n const credPath = await findCredentialFile();\n if (!credPath) {\n return {};\n }\n\n try {\n const content = await fs.readFile(credPath, 'utf-8');\n return parseCredentials(content);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse credential file content into key-value pairs.\n */\nexport function parseCredentials(content: string): CVHubCredentials {\n const result: CVHubCredentials = {};\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const eqIdx = trimmed.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = trimmed.slice(0, eqIdx).trim();\n const value = trimmed.slice(eqIdx + 1).trim();\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Write or update a single field in the credentials file.\n * Preserves existing fields, comments, and ordering.\n * If the file doesn't exist, creates it with secure permissions.\n */\nexport async function writeCredentialField(key: string, value: string): Promise<string> {\n let credPath = await findCredentialFile();\n\n if (!credPath) {\n // Create the default credentials file\n credPath = CREDENTIAL_PATHS[0];\n await fs.mkdir(dirname(credPath), { recursive: true });\n await fs.writeFile(credPath, `${key}=${value}\\n`, { mode: 0o600 });\n return credPath;\n }\n\n let content: string;\n try {\n content = await fs.readFile(credPath, 'utf-8');\n } catch {\n content = '';\n }\n\n const lines = content.split('\\n');\n let found = false;\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim();\n if (trimmed.startsWith('#') || !trimmed) continue;\n\n const eqIdx = trimmed.indexOf('=');\n if (eqIdx === -1) continue;\n\n const lineKey = trimmed.slice(0, eqIdx).trim();\n if (lineKey === key) {\n lines[i] = `${key}=${value}`;\n found = true;\n break;\n }\n }\n\n if (!found) {\n // Append \u2014 ensure there's a trailing newline before adding\n if (content.length > 0 && !content.endsWith('\\n')) {\n lines.push('');\n }\n lines.push(`${key}=${value}`);\n }\n\n // Ensure file ends with newline\n let newContent = lines.join('\\n');\n if (!newContent.endsWith('\\n')) {\n newContent += '\\n';\n }\n\n await fs.writeFile(credPath, newContent, { mode: 0o600 });\n return credPath;\n}\n\n/**\n * Get the machine name for this host.\n * Priority: CV_HUB_MACHINE_NAME from credentials > os.hostname()\n * Cleans the value: lowercase, trim, replace spaces with hyphens.\n */\nexport async function getMachineName(): Promise<string> {\n const creds = await readCredentials();\n const raw = creds.CV_HUB_MACHINE_NAME || os.hostname();\n return cleanMachineName(raw);\n}\n\n/**\n * Clean a machine name: lowercase, trim, replace spaces with hyphens.\n */\nexport function cleanMachineName(name: string): string {\n return name.trim().toLowerCase().replace(/\\s+/g, '-');\n}\n", "/**\n * CV-Hub API client for the cva agent.\n *\n * Extracted from cv-git agent.ts with additional endpoints for\n * listing executors, tasks, logs, and creating repos.\n */\n\nimport type { CVHubCredentials } from './credentials.js';\n\n// ============================================================================\n// Core API call\n// ============================================================================\n\nexport async function apiCall(\n creds: CVHubCredentials,\n method: string,\n path: string,\n body?: unknown,\n): Promise<Response> {\n const url = `${creds.CV_HUB_API}${path}`;\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${creds.CV_HUB_PAT}`,\n 'Content-Type': 'application/json',\n };\n return fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n}\n\n// ============================================================================\n// Executor lifecycle\n// ============================================================================\n\nexport interface ExecutorRegistrationMetadata {\n role?: string;\n integration?: {\n system: string;\n description?: string;\n service_port?: number;\n safe_task_types?: string[];\n unsafe_task_types?: string[];\n self_referential?: boolean;\n };\n tags?: string[];\n owner_project?: string;\n dispatch_guard?: string;\n}\n\nexport async function registerExecutor(\n creds: CVHubCredentials,\n machineName: string,\n workingDir: string,\n repositoryId?: string,\n metadata?: ExecutorRegistrationMetadata,\n): Promise<{ id: string; name: string }> {\n const body: Record<string, unknown> = {\n name: `cva:${machineName}`,\n machine_name: machineName,\n type: 'claude_code',\n workspace_root: workingDir,\n capabilities: {\n tools: ['bash', 'read', 'write', 'edit', 'glob', 'grep'],\n maxConcurrentTasks: 1,\n },\n };\n\n if (repositoryId) {\n body.repository_id = repositoryId;\n }\n\n // Executor identity metadata\n if (metadata?.role) body.role = metadata.role;\n if (metadata?.dispatch_guard) body.dispatch_guard = metadata.dispatch_guard;\n if (metadata?.tags) body.tags = metadata.tags;\n if (metadata?.owner_project) body.owner_project = metadata.owner_project;\n if (metadata?.integration) body.integration = metadata.integration;\n\n const res = await apiCall(creds, 'POST', '/api/v1/executors', body);\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Failed to register executor: ${res.status} ${err}`);\n }\n\n const data = await res.json() as any;\n return { id: data.executor.id, name: data.executor.name };\n}\n\nexport async function resolveRepoId(\n creds: CVHubCredentials,\n owner: string,\n repo: string,\n): Promise<{ id: string; slug: string } | null> {\n try {\n const res = await apiCall(creds, 'GET', `/api/v1/repos/${owner}/${repo}`);\n if (!res.ok) return null;\n const data = await res.json() as any;\n return data.repository\n ? { id: data.repository.id, slug: data.repository.slug }\n : null;\n } catch {\n return null;\n }\n}\n\nexport async function markOffline(\n creds: CVHubCredentials,\n executorId: string,\n): Promise<void> {\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/offline`).catch(() => {});\n}\n\n// ============================================================================\n// Task lifecycle\n// ============================================================================\n\nexport async function pollForTask(\n creds: CVHubCredentials,\n executorId: string,\n): Promise<any | null> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/poll`);\n if (!res.ok) throw new Error(`Poll failed: ${res.status}`);\n const data = await res.json() as any;\n return data.task || null;\n}\n\nexport async function startTask(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n): Promise<void> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/start`);\n if (!res.ok) throw new Error(`Start failed: ${res.status}`);\n}\n\nexport async function completeTask(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n result: Record<string, unknown>,\n): Promise<void> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/complete`, result);\n if (!res.ok) throw new Error(`Complete failed: ${res.status}`);\n}\n\nexport async function failTask(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n error: string,\n): Promise<void> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/fail`, { error });\n if (!res.ok) throw new Error(`Fail failed: ${res.status}`);\n}\n\nexport async function sendHeartbeat(\n creds: CVHubCredentials,\n executorId: string,\n taskId?: string,\n message?: string,\n authStatus?: string,\n): Promise<void> {\n const body: Record<string, unknown> | undefined = authStatus ? { auth_status: authStatus } : undefined;\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/heartbeat`, body).catch(() => {});\n if (taskId) {\n const taskBody = message ? { message, log_type: 'heartbeat' } : undefined;\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/heartbeat`, taskBody).catch(() => {});\n }\n}\n\nexport async function sendTaskLog(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n logType: string,\n message: string,\n details?: Record<string, unknown>,\n progressPct?: number,\n): Promise<void> {\n await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/log`, {\n log_type: logType,\n message,\n ...(details ? { details } : {}),\n ...(progressPct !== undefined ? { progress_pct: progressPct } : {}),\n }).catch(() => {});\n}\n\n// ============================================================================\n// Prompt relay (for relay mode)\n// ============================================================================\n\nexport async function createTaskPrompt(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n promptText: string,\n promptType: string = 'approval',\n options?: string[],\n context?: Record<string, unknown>,\n): Promise<{ prompt_id: string }> {\n const res = await apiCall(creds, 'POST', `/api/v1/executors/${executorId}/tasks/${taskId}/prompt`, {\n type: promptType,\n text: promptText,\n ...(options ? { options } : {}),\n ...(context ? { context } : {}),\n });\n if (!res.ok) throw new Error(`Create prompt failed: ${res.status}`);\n return await res.json() as { prompt_id: string };\n}\n\nexport async function pollPromptResponse(\n creds: CVHubCredentials,\n executorId: string,\n taskId: string,\n promptId: string,\n): Promise<{ response: string | null }> {\n const res = await apiCall(creds, 'GET', `/api/v1/executors/${executorId}/tasks/${taskId}/prompts/${promptId}`);\n if (!res.ok) throw new Error(`Poll prompt failed: ${res.status}`);\n const data = await res.json() as any;\n return { response: data.response ?? null };\n}\n\n// ============================================================================\n// New listing endpoints\n// ============================================================================\n\nexport async function listExecutors(\n creds: CVHubCredentials,\n): Promise<any[]> {\n const res = await apiCall(creds, 'GET', '/api/v1/executors');\n if (!res.ok) throw new Error(`List executors failed: ${res.status}`);\n const data = await res.json() as any;\n return data.executors || [];\n}\n\nexport async function listTasks(\n creds: CVHubCredentials,\n status?: string,\n): Promise<any[]> {\n const qs = status ? `?status=${encodeURIComponent(status)}` : '';\n const res = await apiCall(creds, 'GET', `/api/v1/tasks${qs}`);\n if (!res.ok) throw new Error(`List tasks failed: ${res.status}`);\n const data = await res.json() as any;\n return data.tasks || [];\n}\n\nexport async function getTask(\n creds: CVHubCredentials,\n taskId: string,\n): Promise<any> {\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}`);\n if (!res.ok) throw new Error(`Get task failed: ${res.status}`);\n const data = await res.json() as any;\n return data.task;\n}\n\nexport async function getTaskLogs(\n creds: CVHubCredentials,\n taskId: string,\n): Promise<any[]> {\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}/logs`);\n if (!res.ok) throw new Error(`Get task logs failed: ${res.status}`);\n const data = await res.json() as any;\n return data.logs || [];\n}\n\n// ============================================================================\n// Task events (structured streaming events)\n// ============================================================================\n\nexport async function postTaskEvent(\n creds: CVHubCredentials,\n taskId: string,\n event: {\n event_type: string;\n content: Record<string, unknown> | string;\n needs_response?: boolean;\n },\n): Promise<{ id: string; event_type: string }> {\n const res = await apiCall(creds, 'POST', `/api/v1/tasks/${taskId}/events`, event);\n if (!res.ok) throw new Error(`Post event failed: ${res.status}`);\n return await res.json() as any;\n}\n\nexport async function getEventResponse(\n creds: CVHubCredentials,\n taskId: string,\n eventId: string,\n): Promise<{ response: unknown | null; responded_at: string | null }> {\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}/events?after_id=&limit=200`);\n if (!res.ok) throw new Error(`Get events failed: ${res.status}`);\n const events = await res.json() as any[];\n const event = events.find((e: any) => e.id === eventId);\n return {\n response: event?.response ?? null,\n responded_at: event?.respondedAt ?? event?.responded_at ?? null,\n };\n}\n\nexport async function getRedirects(\n creds: CVHubCredentials,\n taskId: string,\n afterTimestamp?: string,\n): Promise<Array<{ id: string; content: { instruction: string } }>> {\n const qs = afterTimestamp ? `?after_timestamp=${encodeURIComponent(afterTimestamp)}` : '';\n const res = await apiCall(creds, 'GET', `/api/v1/tasks/${taskId}/events${qs}`);\n if (!res.ok) return [];\n const events = await res.json() as any[];\n return events\n .filter((e: any) => (e.eventType ?? e.event_type) === 'redirect')\n .map((e: any) => ({ id: e.id, content: e.content }));\n}\n\n// ============================================================================\n// Repository management\n// ============================================================================\n\nexport async function createRepo(\n creds: CVHubCredentials,\n name: string,\n description?: string,\n): Promise<any> {\n const res = await apiCall(creds, 'POST', '/api/v1/repos', {\n name,\n ...(description ? { description } : {}),\n });\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`Create repo failed: ${res.status} ${err}`);\n }\n return await res.json();\n}\n", "/**\n * Structured Output Parser\n *\n * Parses Claude Code stdout for structured markers emitted by enriched task prompts.\n *\n * Markers:\n * [THINKING] <text> \u2192 event_type: 'thinking'\n * [DECISION] <text> \u2192 event_type: 'decision'\n * [QUESTION] <text> \u2192 event_type: 'question', needs_response: true\n * [PROGRESS] <text> \u2192 event_type: 'progress'\n *\n * Also detects:\n * - File write tool use \u2192 event_type: 'file_change'\n * - Error output \u2192 event_type: 'error'\n */\n\nexport interface ParsedEvent {\n eventType: string;\n content: string | Record<string, unknown>;\n needsResponse: boolean;\n}\n\n/**\n * Parse a single line of Claude Code output for structured markers.\n * Returns null if the line contains no recognized marker.\n */\nexport function parseClaudeCodeOutput(line: string): ParsedEvent | null {\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n // Match [THINKING] ...\n const thinkingMatch = trimmed.match(/^\\[THINKING\\]\\s*(.+)/);\n if (thinkingMatch) {\n return { eventType: 'thinking', content: thinkingMatch[1], needsResponse: false };\n }\n\n // Match [DECISION] ...\n const decisionMatch = trimmed.match(/^\\[DECISION\\]\\s*(.+)/);\n if (decisionMatch) {\n return { eventType: 'decision', content: decisionMatch[1], needsResponse: false };\n }\n\n // Match [QUESTION] ...\n const questionMatch = trimmed.match(/^\\[QUESTION\\]\\s*(.+)/);\n if (questionMatch) {\n return { eventType: 'question', content: questionMatch[1], needsResponse: true };\n }\n\n // Match [PROGRESS] ...\n const progressMatch = trimmed.match(/^\\[PROGRESS\\]\\s*(.+)/);\n if (progressMatch) {\n return { eventType: 'progress', content: progressMatch[1], needsResponse: false };\n }\n\n // Detect file changes from Claude Code tool use output\n // Patterns: \"Created file: ...\", \"Modified: ...\", \"Wrote to ...\", \"Deleted ...\"\n const fileChangeMatch = trimmed.match(\n /(?:Created|Modified|Wrote to|Deleted)\\s+(?:file:\\s*)?(.+)/i,\n );\n if (fileChangeMatch) {\n const action = trimmed.split(/\\s/)[0].toLowerCase();\n return {\n eventType: 'file_change',\n content: { path: fileChangeMatch[1].trim(), action },\n needsResponse: false,\n };\n }\n\n // Detect errors\n const errorMatch = trimmed.match(/^(?:Error|FATAL|FAILED|panic|Traceback)/i);\n if (errorMatch) {\n return { eventType: 'error', content: trimmed, needsResponse: false };\n }\n\n return null;\n}\n", "/**\n * Git state tracking for the cva agent.\n *\n * Captures pre-task and post-task git state so the agent can report\n * structured diffs, commit info, and file change details back to CV-Hub.\n */\n\nimport { execSync } from 'node:child_process';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PreTaskState {\n headSha: string | null;\n branch: string | null;\n remote: string | null;\n workingDir: string;\n}\n\nexport interface PostTaskState {\n headSha: string | null;\n branch: string | null;\n filesAdded: string[];\n filesModified: string[];\n filesDeleted: string[];\n linesAdded: number;\n linesDeleted: number;\n commitMessages: string[];\n pushStatus: 'success' | 'not_pushed' | 'failed' | 'no_remote';\n pushRemote: string | null;\n}\n\nexport interface TaskCompletionPayload {\n summary: string;\n output: string;\n commit: {\n sha: string | null;\n branch: string | null;\n remote: string | null;\n push_status: string;\n messages: string[];\n };\n files: {\n added: string[];\n modified: string[];\n deleted: string[];\n total_changed: number;\n };\n stats: {\n lines_added: number;\n lines_deleted: number;\n duration_seconds: number;\n };\n exit_code: number;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Run a git command, return trimmed stdout or null on failure */\nexport function gitExec(cmd: string, cwd: string): string | null {\n try {\n return execSync(cmd, { cwd, encoding: 'utf-8', timeout: 10000 }).trim();\n } catch {\n return null;\n }\n}\n\n// ============================================================================\n// Pre-task state\n// ============================================================================\n\nexport function capturePreTaskState(cwd: string): PreTaskState {\n return {\n headSha: gitExec('git rev-parse HEAD', cwd),\n branch: gitExec('git rev-parse --abbrev-ref HEAD', cwd),\n remote: gitExec('git remote get-url origin', cwd),\n workingDir: cwd,\n };\n}\n\n// ============================================================================\n// Post-task state\n// ============================================================================\n\nexport function capturePostTaskState(cwd: string, preState: PreTaskState): PostTaskState {\n const headSha = gitExec('git rev-parse HEAD', cwd);\n const branch = gitExec('git rev-parse --abbrev-ref HEAD', cwd);\n\n let filesAdded: string[] = [];\n let filesModified: string[] = [];\n let filesDeleted: string[] = [];\n let linesAdded = 0;\n let linesDeleted = 0;\n let commitMessages: string[] = [];\n\n if (preState.headSha && headSha && preState.headSha !== headSha) {\n const diffOutput = gitExec(\n `git diff --name-status ${preState.headSha}..${headSha}`,\n cwd,\n );\n\n if (diffOutput) {\n for (const line of diffOutput.split('\\n')) {\n const [status, ...pathParts] = line.split('\\t');\n const filepath = pathParts.join('\\t');\n if (!filepath) continue;\n\n if (status === 'A') filesAdded.push(filepath);\n else if (status === 'M') filesModified.push(filepath);\n else if (status === 'D') filesDeleted.push(filepath);\n else if (status?.startsWith('R')) {\n filesDeleted.push(pathParts[0]);\n if (pathParts[1]) filesAdded.push(pathParts[1]);\n }\n }\n }\n\n const statOutput = gitExec(\n `git diff --shortstat ${preState.headSha}..${headSha}`,\n cwd,\n );\n if (statOutput) {\n const addMatch = statOutput.match(/(\\d+) insertion/);\n const delMatch = statOutput.match(/(\\d+) deletion/);\n linesAdded = addMatch ? parseInt(addMatch[1], 10) : 0;\n linesDeleted = delMatch ? parseInt(delMatch[1], 10) : 0;\n }\n\n const logOutput = gitExec(\n `git log --oneline ${preState.headSha}..${headSha}`,\n cwd,\n );\n if (logOutput) {\n commitMessages = logOutput.split('\\n').filter(Boolean);\n }\n } else if (!preState.headSha && headSha) {\n const allFiles = gitExec('git ls-files', cwd);\n if (allFiles) {\n filesAdded = allFiles.split('\\n').filter(Boolean);\n }\n } else {\n const statusOutput = gitExec('git status --porcelain', cwd);\n if (statusOutput) {\n for (const line of statusOutput.split('\\n')) {\n const status = line.substring(0, 2).trim();\n const filepath = line.substring(3);\n if (!filepath) continue;\n\n if (status === '??' || status === 'A') filesAdded.push(filepath);\n else if (status === 'M') filesModified.push(filepath);\n else if (status === 'D') filesDeleted.push(filepath);\n }\n }\n }\n\n let pushStatus: PostTaskState['pushStatus'] = 'not_pushed';\n let pushRemote: string | null = null;\n\n const remote = gitExec('git remote get-url origin', cwd);\n if (!remote) {\n pushStatus = 'no_remote';\n } else {\n pushRemote = remote;\n if (headSha && branch) {\n const remoteRef = gitExec(`git ls-remote origin ${branch}`, cwd);\n if (remoteRef && remoteRef.includes(headSha)) {\n pushStatus = 'success';\n }\n }\n }\n\n return {\n headSha,\n branch,\n filesAdded,\n filesModified,\n filesDeleted,\n linesAdded,\n linesDeleted,\n commitMessages,\n pushStatus,\n pushRemote,\n };\n}\n\n// ============================================================================\n// Structured completion payload\n// ============================================================================\n\nexport function buildCompletionPayload(\n exitCode: number,\n preState: PreTaskState,\n postState: PostTaskState,\n startTime: number,\n output: string = '',\n): TaskCompletionPayload {\n const durationSec = Math.floor((Date.now() - startTime) / 1000);\n const durationStr = durationSec >= 60\n ? `${Math.floor(durationSec / 60)}m ${durationSec % 60}s`\n : `${durationSec}s`;\n\n const totalChanged =\n postState.filesAdded.length +\n postState.filesModified.length +\n postState.filesDeleted.length;\n\n const parts: string[] = [`Completed in ${durationStr}.`];\n\n if (totalChanged > 0) {\n parts.push(\n `${totalChanged} file(s) changed (+${postState.linesAdded}/-${postState.linesDeleted}).`,\n );\n } else {\n parts.push('No file changes detected.');\n }\n\n if (postState.headSha && postState.headSha !== preState.headSha) {\n parts.push(`Commit: ${postState.headSha.substring(0, 8)}`);\n }\n\n if (postState.pushStatus === 'success') {\n parts.push('Pushed to remote.');\n } else if (postState.pushStatus === 'not_pushed') {\n parts.push('Not pushed to remote.');\n }\n\n return {\n summary: parts.join(' '),\n output,\n commit: {\n sha: postState.headSha,\n branch: postState.branch,\n remote: postState.pushRemote,\n push_status: postState.pushStatus,\n messages: postState.commitMessages,\n },\n files: {\n added: postState.filesAdded,\n modified: postState.filesModified,\n deleted: postState.filesDeleted,\n total_changed: totalChanged,\n },\n stats: {\n lines_added: postState.linesAdded,\n lines_deleted: postState.linesDeleted,\n duration_seconds: durationSec,\n },\n exit_code: exitCode,\n };\n}\n\n// ============================================================================\n// Git remote verification\n// ============================================================================\n\nexport function verifyGitRemote(\n cwd: string,\n task: { owner?: string; repo?: string },\n gitHost: string,\n): { remoteName: string; remoteUrl: string } | null {\n if (!task.owner || !task.repo) return null;\n\n const expectedRemote = `https://${gitHost}/${task.owner}/${task.repo}.git`;\n const currentRemote = gitExec('git remote get-url origin', cwd);\n\n if (!currentRemote) {\n try {\n execSync(`git remote add origin ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch { /* remote may already exist without URL */ }\n return { remoteName: 'origin', remoteUrl: expectedRemote };\n }\n\n if (currentRemote === expectedRemote) {\n return { remoteName: 'origin', remoteUrl: expectedRemote };\n }\n\n if (currentRemote.includes(gitHost)) {\n try {\n execSync(`git remote set-url origin ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch {}\n return { remoteName: 'origin', remoteUrl: expectedRemote };\n }\n\n const cvRemote = gitExec('git remote get-url cv-hub', cwd);\n if (!cvRemote) {\n try {\n execSync(`git remote add cv-hub ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch {}\n } else if (cvRemote !== expectedRemote) {\n try {\n execSync(`git remote set-url cv-hub ${expectedRemote}`, { cwd, timeout: 5000 });\n } catch {}\n }\n return { remoteName: 'cv-hub', remoteUrl: expectedRemote };\n}\n", "/**\n * Display helpers for the cva agent.\n */\n\nimport chalk from 'chalk';\n\nexport function formatDuration(ms: number): string {\n const s = Math.floor(ms / 1000);\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n const rem = s % 60;\n if (m < 60) return `${m}m ${rem}s`;\n const h = Math.floor(m / 60);\n return `${h}h ${m % 60}m`;\n}\n\nexport function setTerminalTitle(title: string): void {\n if (process.stdout.isTTY) {\n process.stdout.write(`\\x1b]0;${title}\\x07`);\n }\n}\n\nexport function printBanner(\n status: 'COMPLETED' | 'FAILED' | 'ABORTED',\n elapsed: string,\n changedFiles: string[],\n commitSha: string | null,\n): void {\n const color = status === 'COMPLETED' ? chalk.green : status === 'ABORTED' ? chalk.yellow : chalk.red;\n const icon = status === 'COMPLETED' ? '\u2705' : status === 'ABORTED' ? '\u23F9' : '\u274C';\n\n console.log(color('\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510'));\n console.log(color(`\u2502 ${icon} ${status.padEnd(57)}\u2502`));\n console.log(color(`\u2502 Duration: ${elapsed.padEnd(49)}\u2502`));\n if (changedFiles.length > 0) {\n const shown = changedFiles.slice(0, 3);\n const fileStr = shown.join(', ') + (changedFiles.length > 3 ? ` and ${changedFiles.length - 3} more` : '');\n console.log(color(`\u2502 Files: ${fileStr.substring(0, 51).padEnd(51)}\u2502`));\n }\n if (commitSha) {\n console.log(color(`\u2502 Commit: ${commitSha.substring(0, 8).padEnd(51)}\u2502`));\n }\n console.log(color('\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518'));\n}\n\nexport function updateStatusLine(\n idle: string,\n poll: string,\n completedCount: number,\n failedCount: number,\n): void {\n const line = `\\r${chalk.cyan('\uD83D\uDD04')} Listening... (${idle} idle) | Last poll: ${poll} ago | Completed: ${completedCount} | Failed: ${failedCount}`;\n process.stdout.write(`\\r\\x1b[K${line}`);\n}\n", "/**\n * Retry logic for API calls.\n */\n\nimport chalk from 'chalk';\n\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n label: string,\n maxRetries = 3,\n): Promise<T> {\n for (let i = 0; i < maxRetries; i++) {\n try {\n return await fn();\n } catch (err: any) {\n if (i === maxRetries - 1) throw err;\n const delay = (i + 1) * 5;\n console.log(`\\n${chalk.yellow('\u26A0')} ${label} failed, retrying in ${delay}s... (${err.message})`);\n await new Promise(r => setTimeout(r, delay * 1000));\n }\n }\n throw new Error('unreachable');\n}\n", "/**\n * Agent config at ~/.config/cva/config.json\n */\n\nimport { promises as fs } from 'fs';\nimport { homedir } from 'os';\nimport { join, dirname } from 'path';\n\nexport type ExecutorRole = 'development' | 'production' | 'ci' | 'staging';\nexport type DispatchGuard = 'open' | 'confirm' | 'locked';\n\nexport interface ExecutorIntegration {\n system: string;\n description: string;\n service_port?: number;\n safe_task_types?: string[];\n unsafe_task_types?: string[];\n self_referential?: boolean;\n}\n\nexport interface CvaConfig {\n defaultApiUrl?: string;\n defaultPollInterval?: number;\n autoApprove?: boolean;\n anthropic_api_key?: string;\n\n // Executor identity\n role?: ExecutorRole;\n integration?: ExecutorIntegration;\n tags?: string[];\n owner_project?: string;\n dispatch_guard?: DispatchGuard;\n\n [key: string]: unknown;\n}\n\n/**\n * Load workspace-local agent config from .cva/agent.json (if it exists).\n * This is per-project config, not global.\n */\nexport async function readWorkspaceConfig(workspaceRoot: string): Promise<Partial<CvaConfig>> {\n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(join(workspaceRoot, '.cva', 'agent.json'), 'utf-8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\nexport function getConfigPath(): string {\n return join(homedir(), '.config', 'cva', 'config.json');\n}\n\nexport async function readConfig(): Promise<CvaConfig> {\n try {\n const content = await fs.readFile(getConfigPath(), 'utf-8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\nexport async function writeConfig(config: CvaConfig): Promise<void> {\n const configPath = getConfigPath();\n await fs.mkdir(dirname(configPath), { recursive: true });\n await fs.writeFile(configPath, JSON.stringify(config, null, 2) + '\\n', { mode: 0o600 });\n}\n", "/**\n * Git Safety Net\n *\n * Runs AFTER Claude Code exits, BEFORE task is reported as complete.\n * Ensures all changes are committed and pushed, because Claude Code\n * cannot be trusted to do this reliably.\n *\n * Evidence: ANAX Artifact Registry task (2026-04-03) \u2014 Claude Code wrote\n * an entire module and didn't git-add a single file.\n */\n\nimport { execSync } from 'node:child_process';\n\nexport interface GitSafetyResult {\n hadChanges: boolean;\n filesAdded: number;\n filesModified: number;\n filesDeleted: number;\n commitSha?: string;\n pushed: boolean;\n error?: string;\n}\n\n/**\n * Execute a git command, return stdout or throw.\n */\nfunction git(cmd: string, cwd: string): string {\n return execSync(cmd, { cwd, encoding: 'utf8', timeout: 30_000 }).trim();\n}\n\n/**\n * Ensure all changes are committed and pushed after Claude Code exits.\n *\n * 1. Check for uncommitted changes (untracked, modified, deleted)\n * 2. If any: git add -A, commit with task metadata, push\n * 3. If no local changes but unpushed commits: push them\n * 4. Return structured result for task reporting\n */\nexport function gitSafetyNet(\n workspaceRoot: string,\n taskTitle: string,\n taskId: string,\n branch?: string,\n): GitSafetyResult {\n const targetBranch = branch || 'main';\n\n try {\n // 1. Check for ANY uncommitted changes\n let statusOutput: string;\n try {\n statusOutput = git('git status --porcelain', workspaceRoot);\n } catch {\n return { hadChanges: false, filesAdded: 0, filesModified: 0, filesDeleted: 0, pushed: false, error: 'git status failed' };\n }\n\n const lines = statusOutput.split('\\n').filter(Boolean);\n\n if (lines.length === 0) {\n // No local changes \u2014 check for unpushed commits\n try {\n const unpushed = git(`git log origin/${targetBranch}..HEAD --oneline 2>/dev/null`, workspaceRoot);\n if (unpushed) {\n console.log(` [git-safety] Found unpushed commits \u2014 pushing now`);\n git(`git push origin ${targetBranch}`, workspaceRoot);\n return { hadChanges: false, filesAdded: 0, filesModified: 0, filesDeleted: 0, pushed: true };\n }\n } catch {\n // No remote tracking or push failed \u2014 not critical\n }\n return { hadChanges: false, filesAdded: 0, filesModified: 0, filesDeleted: 0, pushed: false };\n }\n\n // 2. Parse what Claude Code left behind\n let added = 0, modified = 0, deleted = 0;\n for (const line of lines) {\n const code = line.substring(0, 2);\n if (code.includes('?')) added++;\n else if (code.includes('D')) deleted++;\n else if (code.includes('M') || code.includes('A')) modified++;\n else added++; // Treat unknown status as added\n }\n\n console.log(\n ` [git-safety] ${lines.length} uncommitted changes ` +\n `(${added} new, ${modified} modified, ${deleted} deleted) \u2014 committing now`\n );\n\n // 3. Stage everything\n git('git add -A', workspaceRoot);\n\n // 4. Commit with task metadata\n const shortId = taskId.substring(0, 8);\n const commitMsg = `task: ${taskTitle} [${shortId}]\\n\\nAuto-committed by cv-agent git safety net.\\nTask ID: ${taskId}\\nFiles: ${added} added, ${modified} modified, ${deleted} deleted`;\n\n let commitSha: string | undefined;\n try {\n const commitOutput = git(`git commit -m ${JSON.stringify(commitMsg)}`, workspaceRoot);\n const shaMatch = commitOutput.match(/\\[[\\w/]+ ([a-f0-9]+)\\]/);\n commitSha = shaMatch ? shaMatch[1] : undefined;\n } catch (e: any) {\n // Commit may fail if there's nothing to commit after add\n if (!e.message?.includes('nothing to commit')) {\n return {\n hadChanges: true, filesAdded: added, filesModified: modified,\n filesDeleted: deleted, pushed: false, error: `Commit failed: ${e.message}`,\n };\n }\n }\n\n // 5. Push\n try {\n git(`git push origin ${targetBranch}`, workspaceRoot);\n console.log(` [git-safety] Committed and pushed: ${commitSha || 'ok'}`);\n } catch (pushErr: any) {\n console.log(` [git-safety] Push failed: ${pushErr.message}`);\n return {\n hadChanges: true, filesAdded: added, filesModified: modified,\n filesDeleted: deleted, commitSha, pushed: false,\n error: `Push failed: ${pushErr.message}`,\n };\n }\n\n return {\n hadChanges: true, filesAdded: added, filesModified: modified,\n filesDeleted: deleted, commitSha, pushed: true,\n };\n\n } catch (err: any) {\n return {\n hadChanges: false, filesAdded: 0, filesModified: 0,\n filesDeleted: 0, pushed: false, error: err.message,\n };\n }\n}\n", "/**\n * Post-Task Deploy\n *\n * Reads .cva/deploy.json from workspace root and executes:\n * 1. Build steps (cargo build, npm build, etc.)\n * 2. Database migration\n * 3. Service restart (systemd, pm2, manual, docker, or none)\n * 4. Health check + smoke tests\n * 5. Auto-rollback on verification failure\n */\n\nimport { execSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ninterface BuildStep {\n name: string;\n command: string;\n timeout_seconds?: number;\n working_dir?: string;\n}\n\ninterface SmokeTest {\n name: string;\n url: string;\n expected_status: number[];\n description?: string;\n}\n\ninterface ServiceConfig {\n type: 'systemd' | 'pm2' | 'manual' | 'docker' | 'none';\n name?: string;\n restart_command?: string;\n status_command?: string;\n startup_wait_seconds?: number;\n}\n\nexport interface DeployManifest {\n version: number;\n build?: { steps: BuildStep[] };\n migrate?: { check?: string; command: string; env?: Record<string, string> };\n service?: ServiceConfig;\n verify?: { health_url?: string; smoke_tests?: SmokeTest[]; timeout_seconds?: number };\n rollback?: { strategy: 'git_revert' | 'manual'; auto_rollback_on_verify_failure?: boolean };\n}\n\nexport interface DeployResult {\n deployed: boolean;\n steps: DeployStepResult[];\n error?: string;\n rolledBack?: boolean;\n}\n\ninterface DeployStepResult {\n step: string;\n status: 'ok' | 'failed' | 'skipped';\n message?: string;\n durationMs?: number;\n}\n\ntype LogFn = (type: string, message: string) => void;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction exec(cmd: string, cwd: string, timeoutMs = 300_000, env?: Record<string, string>): { ok: boolean; stdout: string; stderr: string } {\n try {\n const stdout = execSync(cmd, {\n cwd,\n encoding: 'utf8',\n timeout: timeoutMs,\n env: env ? { ...process.env, ...env } : undefined,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return { ok: true, stdout, stderr: '' };\n } catch (err: any) {\n return { ok: false, stdout: err.stdout || '', stderr: err.stderr || err.message || '' };\n }\n}\n\nasync function httpStatus(url: string, timeoutMs = 10_000): Promise<number> {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(url, { signal: controller.signal });\n clearTimeout(timer);\n return res.status;\n } catch {\n return 0;\n }\n}\n\nasync function checkHealth(url: string, timeoutSeconds: number): Promise<boolean> {\n const deadline = Date.now() + timeoutSeconds * 1000;\n while (Date.now() < deadline) {\n const status = await httpStatus(url);\n if (status >= 200 && status < 500) return true;\n await new Promise(r => setTimeout(r, 2000));\n }\n return false;\n}\n\nfunction getHeadCommit(cwd: string): string | null {\n try {\n return execSync('git rev-parse HEAD', { cwd, encoding: 'utf8', timeout: 5000 }).trim();\n } catch {\n return null;\n }\n}\n\n// ============================================================================\n// Main\n// ============================================================================\n\nexport function loadDeployManifest(workspaceRoot: string): DeployManifest | null {\n const manifestPath = join(workspaceRoot, '.cva', 'deploy.json');\n if (!existsSync(manifestPath)) return null;\n\n try {\n const raw = readFileSync(manifestPath, 'utf8');\n const manifest = JSON.parse(raw) as DeployManifest;\n if (!manifest.version || manifest.version < 1) {\n console.log(' [deploy] Invalid manifest version');\n return null;\n }\n return manifest;\n } catch (err: any) {\n console.log(` [deploy] Failed to read .cva/deploy.json: ${err.message}`);\n return null;\n }\n}\n\nexport async function postTaskDeploy(\n workspaceRoot: string,\n taskId: string,\n log: LogFn,\n): Promise<DeployResult> {\n const manifest = loadDeployManifest(workspaceRoot);\n if (!manifest) {\n return { deployed: false, steps: [{ step: 'manifest', status: 'skipped', message: 'No .cva/deploy.json' }] };\n }\n\n const steps: DeployStepResult[] = [];\n const preDeployCommit = getHeadCommit(workspaceRoot);\n\n // \u2500\u2500 Build \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (manifest.build?.steps) {\n for (const buildStep of manifest.build.steps) {\n const stepName = `build:${buildStep.name}`;\n console.log(` [deploy] Building: ${buildStep.name}`);\n log('lifecycle', `Building: ${buildStep.name}`);\n\n const start = Date.now();\n const cwd = join(workspaceRoot, buildStep.working_dir || '.');\n const timeoutMs = (buildStep.timeout_seconds || 300) * 1000;\n const result = exec(buildStep.command, cwd, timeoutMs);\n\n if (!result.ok) {\n const msg = `Build failed: ${buildStep.name}\\n${result.stderr.slice(-500)}`;\n steps.push({ step: stepName, status: 'failed', message: msg, durationMs: Date.now() - start });\n log('error', msg);\n return { deployed: false, steps, error: msg };\n }\n\n steps.push({ step: stepName, status: 'ok', durationMs: Date.now() - start });\n }\n }\n\n // \u2500\u2500 Migrate \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (manifest.migrate?.command) {\n console.log(' [deploy] Running migration...');\n log('lifecycle', 'Applying database migration');\n\n const start = Date.now();\n const env = manifest.migrate.env || {};\n const result = exec(manifest.migrate.command, workspaceRoot, 60_000, env);\n\n if (!result.ok) {\n const msg = `Migration failed:\\n${result.stderr.slice(-500)}`;\n steps.push({ step: 'migrate', status: 'failed', message: msg, durationMs: Date.now() - start });\n log('error', msg);\n return { deployed: false, steps, error: msg };\n }\n\n steps.push({ step: 'migrate', status: 'ok', durationMs: Date.now() - start });\n }\n\n // \u2500\u2500 Restart \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (manifest.service && manifest.service.type !== 'none' && manifest.service.restart_command) {\n console.log(` [deploy] Restarting service: ${manifest.service.name || 'default'}`);\n log('lifecycle', `Restarting service: ${manifest.service.name || 'default'}`);\n\n const start = Date.now();\n const result = exec(manifest.service.restart_command, workspaceRoot, 30_000);\n\n if (!result.ok) {\n const msg = `Restart failed:\\n${result.stderr.slice(-300)}`;\n steps.push({ step: 'restart', status: 'failed', message: msg, durationMs: Date.now() - start });\n // Don't abort \u2014 verification will catch if the service is actually down\n } else {\n steps.push({ step: 'restart', status: 'ok', durationMs: Date.now() - start });\n }\n\n // Wait for startup\n const waitMs = (manifest.service.startup_wait_seconds || 5) * 1000;\n await new Promise(r => setTimeout(r, waitMs));\n }\n\n // \u2500\u2500 Verify \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (manifest.verify) {\n console.log(' [deploy] Verifying deployment...');\n log('lifecycle', 'Verifying deployment');\n\n const timeoutSec = manifest.verify.timeout_seconds || 30;\n\n // Health check\n if (manifest.verify.health_url) {\n const healthy = await checkHealth(manifest.verify.health_url, timeoutSec);\n if (!healthy) {\n const msg = `Health check failed: ${manifest.verify.health_url} did not respond within ${timeoutSec}s`;\n steps.push({ step: 'verify:health', status: 'failed', message: msg });\n log('error', msg);\n\n if (manifest.rollback?.auto_rollback_on_verify_failure && preDeployCommit) {\n await rollback(workspaceRoot, preDeployCommit, manifest, log);\n return { deployed: false, steps, error: msg, rolledBack: true };\n }\n return { deployed: false, steps, error: msg };\n }\n steps.push({ step: 'verify:health', status: 'ok' });\n }\n\n // Smoke tests\n for (const test of manifest.verify.smoke_tests || []) {\n const status = await httpStatus(test.url);\n if (!test.expected_status.includes(status)) {\n const msg = `Smoke test \"${test.name}\" failed: got ${status}, expected ${test.expected_status.join('|')}`;\n steps.push({ step: `verify:${test.name}`, status: 'failed', message: msg });\n log('error', msg);\n\n if (manifest.rollback?.auto_rollback_on_verify_failure && preDeployCommit) {\n await rollback(workspaceRoot, preDeployCommit, manifest, log);\n return { deployed: false, steps, error: msg, rolledBack: true };\n }\n return { deployed: false, steps, error: msg };\n }\n steps.push({ step: `verify:${test.name}`, status: 'ok' });\n }\n }\n\n console.log(' [deploy] Deployment verified');\n log('lifecycle', 'Deployment verified successfully');\n return { deployed: true, steps };\n}\n\n// ============================================================================\n// Rollback\n// ============================================================================\n\nasync function rollback(\n workspaceRoot: string,\n targetCommit: string,\n manifest: DeployManifest,\n log: LogFn,\n): Promise<void> {\n console.log(` [deploy] Rolling back to ${targetCommit.substring(0, 8)}`);\n log('lifecycle', `Rolling back to ${targetCommit.substring(0, 8)}`);\n\n try {\n exec(`git checkout ${targetCommit}`, workspaceRoot, 10_000);\n } catch {\n log('error', 'Rollback: git checkout failed');\n return;\n }\n\n // Rebuild\n if (manifest.build?.steps) {\n for (const step of manifest.build.steps) {\n exec(step.command, join(workspaceRoot, step.working_dir || '.'), (step.timeout_seconds || 300) * 1000);\n }\n }\n\n // Restart\n if (manifest.service?.restart_command) {\n exec(manifest.service.restart_command, workspaceRoot, 30_000);\n }\n\n log('lifecycle', 'Rollback complete');\n}\n", "/**\n * cva auth login / cva auth status\n *\n * Manages CV-Hub authentication credentials.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport {\n readCredentials,\n writeCredentialField,\n} from '../utils/credentials.js';\nimport { apiCall } from '../utils/api.js';\nimport { readConfig, writeConfig } from '../utils/config.js';\n\nasync function authLogin(opts: { token?: string; apiUrl?: string }): Promise<void> {\n const token = opts.token || await promptForToken();\n const apiUrl = opts.apiUrl || 'https://api.hub.controlvector.io';\n\n // Validate the token\n console.log(chalk.gray('Validating token...'));\n try {\n const res = await fetch(`${apiUrl}/api/auth/me`, {\n headers: { 'Authorization': `Bearer ${token}` },\n });\n\n if (!res.ok) {\n console.log(chalk.red('Invalid token.') + ` API returned ${res.status}`);\n process.exit(1);\n }\n\n const data = await res.json() as any;\n const username = data.user?.username || data.user?.email || 'unknown';\n\n // Save credentials\n await writeCredentialField('CV_HUB_PAT', token);\n await writeCredentialField('CV_HUB_API', apiUrl);\n\n console.log(chalk.green('Authenticated') + ` as ${chalk.bold(username)}`);\n console.log(chalk.gray(`Token saved to ~/.config/cv-hub/credentials`));\n } catch (err: any) {\n console.log(chalk.red('Connection failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nasync function promptForToken(): Promise<string> {\n // Simple stdin read for token\n const readline = await import('node:readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question('Enter your CV-Hub PAT token: ', (answer: string) => {\n rl.close();\n const token = answer.trim();\n if (!token) {\n console.log(chalk.red('No token provided.'));\n process.exit(1);\n }\n resolve(token);\n });\n });\n}\n\nasync function authStatus(): Promise<void> {\n const creds = await readCredentials();\n\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.yellow('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n return;\n }\n\n const apiUrl = creds.CV_HUB_API || 'https://api.hub.controlvector.io';\n const maskedToken = creds.CV_HUB_PAT.substring(0, 8) + '...' + creds.CV_HUB_PAT.slice(-4);\n\n console.log(`API: ${chalk.cyan(apiUrl)}`);\n console.log(`Token: ${chalk.gray(maskedToken)}`);\n\n // Verify token\n try {\n const res = await fetch(`${apiUrl}/api/auth/me`, {\n headers: { 'Authorization': `Bearer ${creds.CV_HUB_PAT}` },\n });\n\n if (res.ok) {\n const data = await res.json() as any;\n const username = data.user?.username || data.user?.email || 'unknown';\n console.log(`User: ${chalk.green(username)}`);\n console.log(`Status: ${chalk.green('valid')}`);\n } else {\n console.log(`Status: ${chalk.red('invalid')} (${res.status})`);\n }\n } catch (err: any) {\n console.log(`Status: ${chalk.red('unreachable')} (${err.message})`);\n }\n}\n\nasync function authSetApiKey(key: string): Promise<void> {\n if (!key.startsWith('sk-ant-')) {\n console.log(chalk.red('Invalid API key.') + ' Anthropic API keys start with sk-ant-');\n process.exit(1);\n }\n\n const config = await readConfig();\n config.anthropic_api_key = key;\n await writeConfig(config);\n\n const masked = key.substring(0, 10) + '...' + key.slice(-4);\n console.log(chalk.green('API key saved') + ` (${masked})`);\n console.log(chalk.gray('This key will be used as fallback when Claude Code OAuth expires.'));\n}\n\nasync function authRemoveApiKey(): Promise<void> {\n const config = await readConfig();\n if (!config.anthropic_api_key) {\n console.log(chalk.yellow('No API key configured.'));\n return;\n }\n delete config.anthropic_api_key;\n await writeConfig(config);\n console.log(chalk.green('API key removed.'));\n}\n\nexport function authCommand(): Command {\n const cmd = new Command('auth');\n cmd.description('Manage CV-Hub authentication');\n\n cmd\n .command('login')\n .description('Authenticate with CV-Hub using a PAT token')\n .option('--token <token>', 'PAT token (or enter interactively)')\n .option('--api-url <url>', 'CV-Hub API URL', 'https://api.hub.controlvector.io')\n .action(authLogin);\n\n cmd\n .command('status')\n .description('Show current authentication status')\n .action(authStatus);\n\n cmd\n .command('set-api-key')\n .description('Set Anthropic API key as fallback for Claude Code OAuth')\n .argument('<key>', 'Anthropic API key (sk-ant-...)')\n .action(authSetApiKey);\n\n cmd\n .command('remove-api-key')\n .description('Remove stored Anthropic API key')\n .action(authRemoveApiKey);\n\n return cmd;\n}\n", "/**\n * cva remote add / cva remote setup\n *\n * Manages CV-Hub git remotes for the current repository.\n */\n\nimport { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport chalk from 'chalk';\nimport { readCredentials } from '../utils/credentials.js';\nimport { createRepo } from '../utils/api.js';\n\nfunction getGitHost(apiUrl: string): string {\n return apiUrl\n .replace(/^https?:\\/\\//, '')\n .replace(/^api\\./, 'git.');\n}\n\nasync function remoteAdd(ownerRepo: string): Promise<void> {\n const creds = await readCredentials();\n const apiUrl = creds.CV_HUB_API || 'https://api.hub.controlvector.io';\n const gitHost = getGitHost(apiUrl);\n\n const [owner, repo] = ownerRepo.split('/');\n if (!owner || !repo) {\n console.log(chalk.red('Invalid format.') + ' Use: cva remote add <owner>/<repo>');\n process.exit(1);\n }\n\n const remoteUrl = `https://${gitHost}/${owner}/${repo}.git`;\n\n // Check if cvhub remote already exists\n try {\n const existing = execSync('git remote get-url cvhub', { encoding: 'utf-8', timeout: 5000 }).trim();\n if (existing === remoteUrl) {\n console.log(chalk.gray(`Remote 'cvhub' already set to ${remoteUrl}`));\n return;\n }\n // Update it\n execSync(`git remote set-url cvhub ${remoteUrl}`, { timeout: 5000 });\n console.log(chalk.green('Updated') + ` remote 'cvhub' -> ${remoteUrl}`);\n } catch {\n // Add new remote\n try {\n execSync(`git remote add cvhub ${remoteUrl}`, { timeout: 5000 });\n console.log(chalk.green('Added') + ` remote 'cvhub' -> ${remoteUrl}`);\n } catch (err: any) {\n console.log(chalk.red('Failed to add remote:') + ` ${err.message}`);\n process.exit(1);\n }\n }\n}\n\nasync function remoteSetup(ownerRepo: string): Promise<void> {\n const creds = await readCredentials();\n\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n\n if (!creds.CV_HUB_API) {\n creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n }\n\n const [owner, repo] = ownerRepo.split('/');\n if (!owner || !repo) {\n console.log(chalk.red('Invalid format.') + ' Use: cva remote setup <owner>/<repo>');\n process.exit(1);\n }\n\n // Create repo on CV-Hub\n console.log(chalk.gray(`Creating repository ${ownerRepo} on CV-Hub...`));\n try {\n await createRepo(creds, repo);\n console.log(chalk.green('Created') + ` repository ${ownerRepo}`);\n } catch (err: any) {\n if (err.message.includes('409') || err.message.includes('already exists')) {\n console.log(chalk.gray(`Repository ${ownerRepo} already exists.`));\n } else {\n console.log(chalk.red('Failed to create repo:') + ` ${err.message}`);\n process.exit(1);\n }\n }\n\n // Add the remote\n await remoteAdd(ownerRepo);\n}\n\nexport function remoteCommand(): Command {\n const cmd = new Command('remote');\n cmd.description('Manage CV-Hub git remotes');\n\n cmd\n .command('add <owner/repo>')\n .description('Add cvhub remote to current git repo')\n .action(remoteAdd);\n\n cmd\n .command('setup <owner/repo>')\n .description('Create repo on CV-Hub and add cvhub remote')\n .action(remoteSetup);\n\n return cmd;\n}\n", "/**\n * cva task list / cva task logs\n *\n * View tasks and task logs from CV-Hub.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readCredentials } from '../utils/credentials.js';\nimport { listTasks, getTask, getTaskLogs } from '../utils/api.js';\n\nasync function taskList(opts: { status?: string }): Promise<void> {\n const creds = await readCredentials();\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n if (!creds.CV_HUB_API) creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n\n try {\n const tasks = await listTasks(creds, opts.status);\n\n if (tasks.length === 0) {\n console.log(chalk.gray('No tasks found.'));\n return;\n }\n\n // Table output\n const statusColors: Record<string, (s: string) => string> = {\n pending: chalk.yellow,\n assigned: chalk.blue,\n running: chalk.cyan,\n completed: chalk.green,\n failed: chalk.red,\n cancelled: chalk.gray,\n waiting_for_input: chalk.magenta,\n };\n\n for (const t of tasks) {\n const colorFn = statusColors[t.status] || chalk.white;\n const status = colorFn(t.status.padEnd(18));\n const title = (t.title || '').substring(0, 50);\n const id = chalk.gray(t.id.substring(0, 8));\n const age = t.created_at ? chalk.gray(timeSince(new Date(t.created_at))) : '';\n console.log(`${id} ${status} ${title} ${age}`);\n }\n\n console.log(chalk.gray(`\\n${tasks.length} task(s)`));\n } catch (err: any) {\n console.log(chalk.red('Failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nasync function taskLogs(taskId: string): Promise<void> {\n const creds = await readCredentials();\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n if (!creds.CV_HUB_API) creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n\n try {\n const logs = await getTaskLogs(creds, taskId);\n\n if (logs.length === 0) {\n // Fallback: show task detail\n console.log(chalk.gray('No logs found. Showing task detail:'));\n const task = await getTask(creds, taskId);\n console.log(JSON.stringify(task, null, 2));\n return;\n }\n\n const typeColors: Record<string, (s: string) => string> = {\n lifecycle: chalk.blue,\n heartbeat: chalk.gray,\n progress: chalk.cyan,\n git: chalk.green,\n error: chalk.red,\n info: chalk.white,\n };\n\n for (const log of logs) {\n const colorFn = typeColors[log.log_type] || chalk.white;\n const type = colorFn(`[${log.log_type}]`.padEnd(14));\n const time = chalk.gray(new Date(log.created_at).toLocaleTimeString());\n const pct = log.progress_pct !== null && log.progress_pct !== undefined\n ? chalk.yellow(` ${log.progress_pct}%`)\n : '';\n console.log(`${time} ${type} ${log.message}${pct}`);\n }\n } catch (err: any) {\n console.log(chalk.red('Failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nfunction timeSince(date: Date): string {\n const seconds = Math.floor((Date.now() - date.getTime()) / 1000);\n if (seconds < 60) return `${seconds}s ago`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.floor(hours / 24);\n return `${days}d ago`;\n}\n\nexport function taskCommand(): Command {\n const cmd = new Command('task');\n cmd.description('View tasks and task logs');\n\n cmd\n .command('list')\n .description('List tasks')\n .option('--status <status>', 'Filter by status (e.g. running,completed)')\n .action(taskList);\n\n cmd\n .command('logs <taskId>')\n .description('View logs for a task')\n .action(taskLogs);\n\n return cmd;\n}\n", "/**\n * cva status\n *\n * Show registered executors and their current status.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { readCredentials } from '../utils/credentials.js';\nimport { listExecutors } from '../utils/api.js';\n\nasync function showStatus(): Promise<void> {\n const creds = await readCredentials();\n if (!creds.CV_HUB_PAT) {\n console.log(chalk.red('Not authenticated.') + ' Run ' + chalk.cyan('cva auth login') + ' first.');\n process.exit(1);\n }\n if (!creds.CV_HUB_API) creds.CV_HUB_API = 'https://api.hub.controlvector.io';\n\n try {\n const executors = await listExecutors(creds);\n\n if (executors.length === 0) {\n console.log(chalk.gray('No executors registered.'));\n return;\n }\n\n const statusColors: Record<string, (s: string) => string> = {\n online: chalk.green,\n offline: chalk.gray,\n busy: chalk.yellow,\n error: chalk.red,\n };\n\n console.log(chalk.bold('Executors:'));\n console.log();\n\n for (const e of executors) {\n const colorFn = statusColors[e.status] || chalk.white;\n const status = colorFn(e.status.padEnd(10));\n const name = chalk.cyan(e.name || e.machine_name || 'unknown');\n const id = chalk.gray(e.id.substring(0, 8));\n const heartbeat = e.last_heartbeat_at\n ? chalk.gray(`last seen ${timeSince(new Date(e.last_heartbeat_at))}`)\n : chalk.gray('never');\n const workspace = e.workspace_root ? chalk.gray(` | ${e.workspace_root}`) : '';\n\n console.log(` ${id} ${status} ${name} ${heartbeat}${workspace}`);\n }\n\n console.log(chalk.gray(`\\n${executors.length} executor(s)`));\n } catch (err: any) {\n console.log(chalk.red('Failed:') + ` ${err.message}`);\n process.exit(1);\n }\n}\n\nfunction timeSince(date: Date): string {\n const seconds = Math.floor((Date.now() - date.getTime()) / 1000);\n if (seconds < 60) return `${seconds}s ago`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.floor(hours / 24);\n return `${days}d ago`;\n}\n\nexport function statusCommand(): Command {\n const cmd = new Command('status');\n cmd.description('Show registered executors and their status');\n cmd.action(showStatus);\n return cmd;\n}\n", "/**\n * cva \u2014 CV-Hub Agent CLI\n *\n * Standalone agent daemon that bridges Claude Code with CV-Hub task dispatch.\n * Binary: cva\n * Package: @controlvector/cv-agent\n */\n\nimport { Command } from 'commander';\nimport { agentCommand } from './commands/agent.js';\nimport { authCommand } from './commands/auth.js';\nimport { remoteCommand } from './commands/remote.js';\nimport { taskCommand } from './commands/task.js';\nimport { statusCommand } from './commands/status.js';\n\ndeclare const __CVA_VERSION__: string;\n\nconst program = new Command();\n\nprogram\n .name('cva')\n .description('CV-Hub Agent \u2014 bridges Claude Code with CV-Hub task dispatch')\n .version(typeof __CVA_VERSION__ !== 'undefined' ? __CVA_VERSION__ : '1.1.0');\n\nprogram.addCommand(agentCommand());\nprogram.addCommand(authCommand());\nprogram.addCommand(remoteCommand());\nprogram.addCommand(taskCommand());\nprogram.addCommand(statusCommand());\n\nprogram.parse(process.argv);\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,wCAAAA,UAAA;AAGA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;AAAA,MACrB;AAAA,IACF;AAKA,QAAMC,wBAAN,cAAmCD,gBAAe;AAAA;AAAA;AAAA;AAAA;AAAA,MAKhD,YAAY,SAAS;AACnB,cAAM,GAAG,6BAA6B,OAAO;AAE7C,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAAA,MAC/B;AAAA,IACF;AAEA,IAAAD,SAAQ,iBAAiBC;AACzB,IAAAD,SAAQ,uBAAuBE;AAAA;AAAA;;;ACtC/B;AAAA,2CAAAC,UAAA;AAAA,QAAM,EAAE,sBAAAC,sBAAqB,IAAI;AAEjC,QAAMC,YAAN,MAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAUb,YAAY,MAAM,aAAa;AAC7B,aAAK,cAAc,eAAe;AAClC,aAAK,WAAW;AAChB,aAAK,WAAW;AAChB,aAAK,eAAe;AACpB,aAAK,0BAA0B;AAC/B,aAAK,aAAa;AAElB,gBAAQ,KAAK,CAAC,GAAG;AAAA,UACf,KAAK;AACH,iBAAK,WAAW;AAChB,iBAAK,QAAQ,KAAK,MAAM,GAAG,EAAE;AAC7B;AAAA,UACF,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F;AAEA,SAASA,WAAU,MAAoB;AACrC,QAAM,UAAU,KAAK,OAAO,KAAK,IAAI,IAAI,KAAK,QAAQ,KAAK,GAAI;AAC/D,MAAI,UAAU,GAAI,QAAO,GAAG,OAAO;AACnC,QAAM,UAAU,KAAK,MAAM,UAAU,EAAE;AACvC,MAAI,UAAU,GAAI,QAAO,GAAG,OAAO;AACnC,QAAM,QAAQ,KAAK,MAAM,UAAU,EAAE;AACrC,MAAI,QAAQ,GAAI,QAAO,GAAG,KAAK;AAC/B,QAAM,OAAO,KAAK,MAAM,QAAQ,EAAE;AAClC,SAAO,GAAG,IAAI;AAChB;AAEO,SAAS,gBAAyB;AACvC,QAAM,MAAM,IAAI,QAAQ,QAAQ;AAChC,MAAI,YAAY,4CAA4C;AAC5D,MAAI,OAAO,UAAU;AACrB,SAAO;AACT;;;ACxDA,IAAMC,WAAU,IAAI,QAAQ;AAE5BA,SACG,KAAK,KAAK,EACV,YAAY,mEAA8D,EAC1E,QAAQ,OAAyC,UAAkB,OAAO;AAE7EA,SAAQ,WAAW,aAAa,CAAC;AACjCA,SAAQ,WAAW,YAAY,CAAC;AAChCA,SAAQ,WAAW,cAAc,CAAC;AAClCA,SAAQ,WAAW,YAAY,CAAC;AAChCA,SAAQ,WAAW,cAAc,CAAC;AAElCA,SAAQ,MAAM,QAAQ,IAAI;",
|
|
6
|
+
"names": ["exports", "CommanderError", "InvalidArgumentError", "exports", "InvalidArgumentError", "Argument", "exports", "Help", "cmd", "exports", "InvalidArgumentError", "Option", "str", "exports", "exports", "fs", "process", "Argument", "CommanderError", "Help", "Option", "Command", "option", "path", "exports", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "commander", "import_node_child_process", "process", "os", "tty", "styles", "chalk", "styles", "os", "fs", "authStatus", "import_fs", "import_os", "import_path", "fs", "import_node_child_process", "import_node_child_process", "env", "env", "import_node_child_process", "timeSince", "program"]
|
|
7
7
|
}
|