@agiflowai/agent-cli 0.0.9 → 0.0.10
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/CHANGELOG.md +4 -0
- package/dist/{cli-9RY_AMH5.js → cli-Cr-ovvgN.js} +45 -45
- package/dist/cli-Cr-ovvgN.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/package.json +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/dist/cli-9RY_AMH5.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-Cr-ovvgN.js","sources":["../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js","../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js","../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js","../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js","../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js","../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js","../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js","../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs","../../../node_modules/.pnpm/dotenv@17.2.3/node_modules/dotenv/lib/main.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/browser.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js","../../../node_modules/.pnpm/mimic-function@5.0.1/node_modules/mimic-function/index.js","../../../node_modules/.pnpm/onetime@7.0.0/node_modules/onetime/index.js","../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/signals.js","../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/index.js","../../../node_modules/.pnpm/restore-cursor@5.1.0/node_modules/restore-cursor/index.js","../../../node_modules/.pnpm/cli-cursor@5.0.0/node_modules/cli-cursor/index.js","../../../node_modules/.pnpm/cli-spinners@2.9.2/node_modules/cli-spinners/index.js","../../../node_modules/.pnpm/log-symbols@6.0.0/node_modules/log-symbols/browser.js","../../../node_modules/.pnpm/ansi-regex@6.2.2/node_modules/ansi-regex/index.js","../../../node_modules/.pnpm/strip-ansi@7.1.2/node_modules/strip-ansi/index.js","../../../node_modules/.pnpm/get-east-asian-width@1.4.0/node_modules/get-east-asian-width/lookup.js","../../../node_modules/.pnpm/get-east-asian-width@1.4.0/node_modules/get-east-asian-width/index.js","../../../node_modules/.pnpm/emoji-regex@10.6.0/node_modules/emoji-regex/index.mjs","../../../node_modules/.pnpm/string-width@7.2.0/node_modules/string-width/index.js","../../../node_modules/.pnpm/is-interactive@2.0.0/node_modules/is-interactive/index.js","../../../node_modules/.pnpm/is-unicode-supported@2.1.0/node_modules/is-unicode-supported/index.js","../../../node_modules/.pnpm/stdin-discarder@0.2.2/node_modules/stdin-discarder/index.js","../../../node_modules/.pnpm/ora@8.1.1/node_modules/ora/index.js","../src/commands/baseCommand.ts","../../../packages/universal/universal-agent-events/dist/constants/agentSession.mjs","../../../packages/universal/universal-agent-events/dist/constants/daemon.mjs","../../../packages/universal/universal-agent-events/dist/constants/shared.mjs","../../../packages/universal/universal-agent-events/dist/schemas/agentSession.mjs","../../../packages/universal/universal-agent-events/dist/schemas/daemon.mjs","../src/envSchema.ts","../src/config.ts","../src/utils/platform.ts","../src/services/AgentWsService.ts","../src/services/PtyRunnerService.ts","../src/services/RepoSetupService.ts","../src/services/StdinForwarding.ts","../src/services/TerminationService.ts","../src/agents/base.ts","../src/agents/claude.ts","../src/services/DockerRunnerService.ts","../src/agents/baseDocker.ts","../src/agents/claudeDocker.ts","../src/commands/claude.ts","../src/services/AgentProfiles.ts","../src/services/DeviceCodeAuthService.ts","../src/utils/semaphore.ts","../src/agents/gemini.ts","../src/services/GitWorktreeService.ts","../src/workers/agent.ts","../src/services/AgentsManager.ts","../src/services/AgentDetectionService.ts","../src/services/DaemonHttpService.ts","../src/services/DaemonWsService.ts","../src/workers/daemon.ts","../src/commands/connect.ts","../src/commands/logout.ts","../src/commands/router.ts","../src/cli.ts"],"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–Levenshtein_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","const fs = require('fs')\nconst path = require('path')\nconst os = require('os')\nconst crypto = require('crypto')\nconst packageJson = require('../package.json')\n\nconst version = packageJson.version\n\n// Array of tips to display randomly\nconst TIPS = [\n '🔐 encrypt with Dotenvx: https://dotenvx.com',\n '🔐 prevent committing .env to code: https://dotenvx.com/precommit',\n '🔐 prevent building .env in docker: https://dotenvx.com/prebuild',\n '📡 add observability to secrets: https://dotenvx.com/ops',\n '👥 sync secrets across teammates & machines: https://dotenvx.com/ops',\n '🗂️ backup and recover secrets: https://dotenvx.com/ops',\n '✅ audit secrets and track compliance: https://dotenvx.com/ops',\n '🔄 add secrets lifecycle management: https://dotenvx.com/ops',\n '🔑 add access controls to secrets: https://dotenvx.com/ops',\n '🛠️ run anywhere with `dotenvx run -- yourcommand`',\n '⚙️ specify custom .env file path with { path: \\'/custom/path/.env\\' }',\n '⚙️ enable debug logging with { debug: true }',\n '⚙️ override existing env vars with { override: true }',\n '⚙️ suppress all logs with { quiet: true }',\n '⚙️ write to custom object with { processEnv: myObject }',\n '⚙️ load multiple .env files with { path: [\\'.env.local\\', \\'.env\\'] }'\n]\n\n// Get a random tip from the tips array\nfunction _getRandomTip () {\n return TIPS[Math.floor(Math.random() * TIPS.length)]\n}\n\nfunction parseBoolean (value) {\n if (typeof value === 'string') {\n return !['false', '0', 'no', 'off', ''].includes(value.toLowerCase())\n }\n return Boolean(value)\n}\n\nfunction supportsAnsi () {\n return process.stdout.isTTY // && process.env.TERM !== 'dumb'\n}\n\nfunction dim (text) {\n return supportsAnsi() ? `\\x1b[2m${text}\\x1b[0m` : text\n}\n\nconst LINE = /(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg\n\n// Parse src into an Object\nfunction parse (src) {\n const obj = {}\n\n // Convert buffer to string\n let lines = src.toString()\n\n // Convert line breaks to same format\n lines = lines.replace(/\\r\\n?/mg, '\\n')\n\n let match\n while ((match = LINE.exec(lines)) != null) {\n const key = match[1]\n\n // Default undefined or null to empty string\n let value = (match[2] || '')\n\n // Remove whitespace\n value = value.trim()\n\n // Check if double quoted\n const maybeQuote = value[0]\n\n // Remove surrounding quotes\n value = value.replace(/^(['\"`])([\\s\\S]*)\\1$/mg, '$2')\n\n // Expand newlines if double quoted\n if (maybeQuote === '\"') {\n value = value.replace(/\\\\n/g, '\\n')\n value = value.replace(/\\\\r/g, '\\r')\n }\n\n // Add to object\n obj[key] = value\n }\n\n return obj\n}\n\nfunction _parseVault (options) {\n options = options || {}\n\n const vaultPath = _vaultPath(options)\n options.path = vaultPath // parse .env.vault\n const result = DotenvModule.configDotenv(options)\n if (!result.parsed) {\n const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)\n err.code = 'MISSING_DATA'\n throw err\n }\n\n // handle scenario for comma separated keys - for use with key rotation\n // example: DOTENV_KEY=\"dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod\"\n const keys = _dotenvKey(options).split(',')\n const length = keys.length\n\n let decrypted\n for (let i = 0; i < length; i++) {\n try {\n // Get full key\n const key = keys[i].trim()\n\n // Get instructions for decrypt\n const attrs = _instructions(result, key)\n\n // Decrypt\n decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)\n\n break\n } catch (error) {\n // last key\n if (i + 1 >= length) {\n throw error\n }\n // try next key\n }\n }\n\n // Parse decrypted .env string\n return DotenvModule.parse(decrypted)\n}\n\nfunction _warn (message) {\n console.error(`[dotenv@${version}][WARN] ${message}`)\n}\n\nfunction _debug (message) {\n console.log(`[dotenv@${version}][DEBUG] ${message}`)\n}\n\nfunction _log (message) {\n console.log(`[dotenv@${version}] ${message}`)\n}\n\nfunction _dotenvKey (options) {\n // prioritize developer directly setting options.DOTENV_KEY\n if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {\n return options.DOTENV_KEY\n }\n\n // secondary infra already contains a DOTENV_KEY environment variable\n if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {\n return process.env.DOTENV_KEY\n }\n\n // fallback to empty string\n return ''\n}\n\nfunction _instructions (result, dotenvKey) {\n // Parse DOTENV_KEY. Format is a URI\n let uri\n try {\n uri = new URL(dotenvKey)\n } catch (error) {\n if (error.code === 'ERR_INVALID_URL') {\n const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n throw error\n }\n\n // Get decrypt key\n const key = uri.password\n if (!key) {\n const err = new Error('INVALID_DOTENV_KEY: Missing key part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get environment\n const environment = uri.searchParams.get('environment')\n if (!environment) {\n const err = new Error('INVALID_DOTENV_KEY: Missing environment part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get ciphertext payload\n const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`\n const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION\n if (!ciphertext) {\n const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)\n err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'\n throw err\n }\n\n return { ciphertext, key }\n}\n\nfunction _vaultPath (options) {\n let possibleVaultPath = null\n\n if (options && options.path && options.path.length > 0) {\n if (Array.isArray(options.path)) {\n for (const filepath of options.path) {\n if (fs.existsSync(filepath)) {\n possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`\n }\n }\n } else {\n possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`\n }\n } else {\n possibleVaultPath = path.resolve(process.cwd(), '.env.vault')\n }\n\n if (fs.existsSync(possibleVaultPath)) {\n return possibleVaultPath\n }\n\n return null\n}\n\nfunction _resolveHome (envPath) {\n return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath\n}\n\nfunction _configVault (options) {\n const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || (options && options.debug))\n const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || (options && options.quiet))\n\n if (debug || !quiet) {\n _log('Loading env from encrypted .env.vault')\n }\n\n const parsed = DotenvModule._parseVault(options)\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsed, options)\n\n return { parsed }\n}\n\nfunction configDotenv (options) {\n const dotenvPath = path.resolve(process.cwd(), '.env')\n let encoding = 'utf8'\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || (options && options.debug))\n let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || (options && options.quiet))\n\n if (options && options.encoding) {\n encoding = options.encoding\n } else {\n if (debug) {\n _debug('No encoding is specified. UTF-8 is used by default')\n }\n }\n\n let optionPaths = [dotenvPath] // default, look for .env\n if (options && options.path) {\n if (!Array.isArray(options.path)) {\n optionPaths = [_resolveHome(options.path)]\n } else {\n optionPaths = [] // reset default\n for (const filepath of options.path) {\n optionPaths.push(_resolveHome(filepath))\n }\n }\n }\n\n // Build the parsed data in a temporary object (because we need to return it). Once we have the final\n // parsed data, we will combine it with process.env (or options.processEnv if provided).\n let lastError\n const parsedAll = {}\n for (const path of optionPaths) {\n try {\n // Specifying an encoding returns a string instead of a buffer\n const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))\n\n DotenvModule.populate(parsedAll, parsed, options)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${path} ${e.message}`)\n }\n lastError = e\n }\n }\n\n const populated = DotenvModule.populate(processEnv, parsedAll, options)\n\n // handle user settings DOTENV_CONFIG_ options inside .env file(s)\n debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug)\n quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet)\n\n if (debug || !quiet) {\n const keysCount = Object.keys(populated).length\n const shortPaths = []\n for (const filePath of optionPaths) {\n try {\n const relative = path.relative(process.cwd(), filePath)\n shortPaths.push(relative)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${filePath} ${e.message}`)\n }\n lastError = e\n }\n }\n\n _log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`-- tip: ${_getRandomTip()}`)}`)\n }\n\n if (lastError) {\n return { parsed: parsedAll, error: lastError }\n } else {\n return { parsed: parsedAll }\n }\n}\n\n// Populates process.env from .env file\nfunction config (options) {\n // fallback to original dotenv if DOTENV_KEY is not set\n if (_dotenvKey(options).length === 0) {\n return DotenvModule.configDotenv(options)\n }\n\n const vaultPath = _vaultPath(options)\n\n // dotenvKey exists but .env.vault file does not exist\n if (!vaultPath) {\n _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)\n\n return DotenvModule.configDotenv(options)\n }\n\n return DotenvModule._configVault(options)\n}\n\nfunction decrypt (encrypted, keyStr) {\n const key = Buffer.from(keyStr.slice(-64), 'hex')\n let ciphertext = Buffer.from(encrypted, 'base64')\n\n const nonce = ciphertext.subarray(0, 12)\n const authTag = ciphertext.subarray(-16)\n ciphertext = ciphertext.subarray(12, -16)\n\n try {\n const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)\n aesgcm.setAuthTag(authTag)\n return `${aesgcm.update(ciphertext)}${aesgcm.final()}`\n } catch (error) {\n const isRange = error instanceof RangeError\n const invalidKeyLength = error.message === 'Invalid key length'\n const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'\n\n if (isRange || invalidKeyLength) {\n const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n } else if (decryptionFailed) {\n const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')\n err.code = 'DECRYPTION_FAILED'\n throw err\n } else {\n throw error\n }\n }\n}\n\n// Populate process.env with parsed values\nfunction populate (processEnv, parsed, options = {}) {\n const debug = Boolean(options && options.debug)\n const override = Boolean(options && options.override)\n const populated = {}\n\n if (typeof parsed !== 'object') {\n const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')\n err.code = 'OBJECT_REQUIRED'\n throw err\n }\n\n // Set process.env\n for (const key of Object.keys(parsed)) {\n if (Object.prototype.hasOwnProperty.call(processEnv, key)) {\n if (override === true) {\n processEnv[key] = parsed[key]\n populated[key] = parsed[key]\n }\n\n if (debug) {\n if (override === true) {\n _debug(`\"${key}\" is already defined and WAS overwritten`)\n } else {\n _debug(`\"${key}\" is already defined and was NOT overwritten`)\n }\n }\n } else {\n processEnv[key] = parsed[key]\n populated[key] = parsed[key]\n }\n }\n\n return populated\n}\n\nconst DotenvModule = {\n configDotenv,\n _configVault,\n _parseVault,\n config,\n decrypt,\n parse,\n populate\n}\n\nmodule.exports.configDotenv = DotenvModule.configDotenv\nmodule.exports._configVault = DotenvModule._configVault\nmodule.exports._parseVault = DotenvModule._parseVault\nmodule.exports.config = DotenvModule.config\nmodule.exports.decrypt = DotenvModule.decrypt\nmodule.exports.parse = DotenvModule.parse\nmodule.exports.populate = DotenvModule.populate\n\nmodule.exports = DotenvModule\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","/* eslint-env browser */\n\nconst level = (() => {\n\tif (!('navigator' in globalThis)) {\n\t\treturn 0;\n\t}\n\n\tif (globalThis.navigator.userAgentData) {\n\t\tconst brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');\n\t\tif (brand && brand.version > 93) {\n\t\t\treturn 3;\n\t\t}\n\t}\n\n\tif (/\\b(Chrome|Chromium)\\//.test(globalThis.navigator.userAgent)) {\n\t\treturn 1;\n\t}\n\n\treturn 0;\n})();\n\nconst colorSupport = level !== 0 && {\n\tlevel,\n\thasBasic: true,\n\thas256: level >= 2,\n\thas16m: level >= 3,\n};\n\nconst supportsColor = {\n\tstdout: colorSupport,\n\tstderr: colorSupport,\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` → `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","const copyProperty = (to, from, property, ignoreNonConfigurable) => {\n\t// `Function#length` should reflect the parameters of `to` not `from` since we keep its body.\n\t// `Function#prototype` is non-writable and non-configurable so can never be modified.\n\tif (property === 'length' || property === 'prototype') {\n\t\treturn;\n\t}\n\n\t// `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.\n\tif (property === 'arguments' || property === 'caller') {\n\t\treturn;\n\t}\n\n\tconst toDescriptor = Object.getOwnPropertyDescriptor(to, property);\n\tconst fromDescriptor = Object.getOwnPropertyDescriptor(from, property);\n\n\tif (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {\n\t\treturn;\n\t}\n\n\tObject.defineProperty(to, property, fromDescriptor);\n};\n\n// `Object.defineProperty()` throws if the property exists, is not configurable and either:\n// - one its descriptors is changed\n// - it is non-writable and its value is changed\nconst canCopyProperty = function (toDescriptor, fromDescriptor) {\n\treturn toDescriptor === undefined || toDescriptor.configurable || (\n\t\ttoDescriptor.writable === fromDescriptor.writable\n\t\t&& toDescriptor.enumerable === fromDescriptor.enumerable\n\t\t&& toDescriptor.configurable === fromDescriptor.configurable\n\t\t&& (toDescriptor.writable || toDescriptor.value === fromDescriptor.value)\n\t);\n};\n\nconst changePrototype = (to, from) => {\n\tconst fromPrototype = Object.getPrototypeOf(from);\n\tif (fromPrototype === Object.getPrototypeOf(to)) {\n\t\treturn;\n\t}\n\n\tObject.setPrototypeOf(to, fromPrototype);\n};\n\nconst wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\\n${fromBody}`;\n\nconst toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');\nconst toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');\n\n// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.\n// We use `bind()` instead of a closure for the same reason.\n// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.\nconst changeToString = (to, from, name) => {\n\tconst withName = name === '' ? '' : `with ${name.trim()}() `;\n\tconst newToString = wrappedToString.bind(null, withName, from.toString());\n\t// Ensure `to.toString.toString` is non-enumerable and has the same `same`\n\tObject.defineProperty(newToString, 'name', toStringName);\n\tconst {writable, enumerable, configurable} = toStringDescriptor; // We destructue to avoid a potential `get` descriptor.\n\tObject.defineProperty(to, 'toString', {value: newToString, writable, enumerable, configurable});\n};\n\nexport default function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) {\n\tconst {name} = to;\n\n\tfor (const property of Reflect.ownKeys(from)) {\n\t\tcopyProperty(to, from, property, ignoreNonConfigurable);\n\t}\n\n\tchangePrototype(to, from);\n\tchangeToString(to, from, name);\n\n\treturn to;\n}\n","import mimicFunction from 'mimic-function';\n\nconst calledFunctions = new WeakMap();\n\nconst onetime = (function_, options = {}) => {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError('Expected a function');\n\t}\n\n\tlet returnValue;\n\tlet callCount = 0;\n\tconst functionName = function_.displayName || function_.name || '<anonymous>';\n\n\tconst onetime = function (...arguments_) {\n\t\tcalledFunctions.set(onetime, ++callCount);\n\n\t\tif (callCount === 1) {\n\t\t\treturnValue = function_.apply(this, arguments_);\n\t\t\tfunction_ = undefined;\n\t\t} else if (options.throw === true) {\n\t\t\tthrow new Error(`Function \\`${functionName}\\` can only be called once`);\n\t\t}\n\n\t\treturn returnValue;\n\t};\n\n\tmimicFunction(onetime, function_);\n\tcalledFunctions.set(onetime, callCount);\n\n\treturn onetime;\n};\n\nonetime.callCount = function_ => {\n\tif (!calledFunctions.has(function_)) {\n\t\tthrow new Error(`The given function \\`${function_.name}\\` is not wrapped by the \\`onetime\\` package`);\n\t}\n\n\treturn calledFunctions.get(function_);\n};\n\nexport default onetime;\n","/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals = [];\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM');\nif (process.platform !== 'win32') {\n signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n );\n}\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');\n}\n//# sourceMappingURL=signals.js.map","// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js';\nexport { signals };\nconst processOk = (process) => !!process &&\n typeof process === 'object' &&\n typeof process.removeListener === 'function' &&\n typeof process.emit === 'function' &&\n typeof process.reallyExit === 'function' &&\n typeof process.listeners === 'function' &&\n typeof process.kill === 'function' &&\n typeof process.pid === 'number' &&\n typeof process.on === 'function';\nconst kExitEmitter = Symbol.for('signal-exit emitter');\nconst global = globalThis;\nconst ObjectDefineProperty = Object.defineProperty.bind(Object);\n// teeny special purpose ee\nclass Emitter {\n emitted = {\n afterExit: false,\n exit: false,\n };\n listeners = {\n afterExit: [],\n exit: [],\n };\n count = 0;\n id = Math.random();\n constructor() {\n if (global[kExitEmitter]) {\n return global[kExitEmitter];\n }\n ObjectDefineProperty(global, kExitEmitter, {\n value: this,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n }\n on(ev, fn) {\n this.listeners[ev].push(fn);\n }\n removeListener(ev, fn) {\n const list = this.listeners[ev];\n const i = list.indexOf(fn);\n /* c8 ignore start */\n if (i === -1) {\n return;\n }\n /* c8 ignore stop */\n if (i === 0 && list.length === 1) {\n list.length = 0;\n }\n else {\n list.splice(i, 1);\n }\n }\n emit(ev, code, signal) {\n if (this.emitted[ev]) {\n return false;\n }\n this.emitted[ev] = true;\n let ret = false;\n for (const fn of this.listeners[ev]) {\n ret = fn(code, signal) === true || ret;\n }\n if (ev === 'exit') {\n ret = this.emit('afterExit', code, signal) || ret;\n }\n return ret;\n }\n}\nclass SignalExitBase {\n}\nconst signalExitWrap = (handler) => {\n return {\n onExit(cb, opts) {\n return handler.onExit(cb, opts);\n },\n load() {\n return handler.load();\n },\n unload() {\n return handler.unload();\n },\n };\n};\nclass SignalExitFallback extends SignalExitBase {\n onExit() {\n return () => { };\n }\n load() { }\n unload() { }\n}\nclass SignalExit extends SignalExitBase {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n /* c8 ignore start */\n #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP';\n /* c8 ignore stop */\n #emitter = new Emitter();\n #process;\n #originalProcessEmit;\n #originalProcessReallyExit;\n #sigListeners = {};\n #loaded = false;\n constructor(process) {\n super();\n this.#process = process;\n // { <signal>: <listener fn>, ... }\n this.#sigListeners = {};\n for (const sig of signals) {\n this.#sigListeners[sig] = () => {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n const listeners = this.#process.listeners(sig);\n let { count } = this.#emitter;\n // This is a workaround for the fact that signal-exit v3 and signal\n // exit v4 are not aware of each other, and each will attempt to let\n // the other handle it, so neither of them do. To correct this, we\n // detect if we're the only handler *except* for previous versions\n // of signal-exit, and increment by the count of listeners it has\n // created.\n /* c8 ignore start */\n const p = process;\n if (typeof p.__signal_exit_emitter__ === 'object' &&\n typeof p.__signal_exit_emitter__.count === 'number') {\n count += p.__signal_exit_emitter__.count;\n }\n /* c8 ignore stop */\n if (listeners.length === count) {\n this.unload();\n const ret = this.#emitter.emit('exit', null, sig);\n /* c8 ignore start */\n const s = sig === 'SIGHUP' ? this.#hupSig : sig;\n if (!ret)\n process.kill(process.pid, s);\n /* c8 ignore stop */\n }\n };\n }\n this.#originalProcessReallyExit = process.reallyExit;\n this.#originalProcessEmit = process.emit;\n }\n onExit(cb, opts) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return () => { };\n }\n /* c8 ignore stop */\n if (this.#loaded === false) {\n this.load();\n }\n const ev = opts?.alwaysLast ? 'afterExit' : 'exit';\n this.#emitter.on(ev, cb);\n return () => {\n this.#emitter.removeListener(ev, cb);\n if (this.#emitter.listeners['exit'].length === 0 &&\n this.#emitter.listeners['afterExit'].length === 0) {\n this.unload();\n }\n };\n }\n load() {\n if (this.#loaded) {\n return;\n }\n this.#loaded = true;\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n this.#emitter.count += 1;\n for (const sig of signals) {\n try {\n const fn = this.#sigListeners[sig];\n if (fn)\n this.#process.on(sig, fn);\n }\n catch (_) { }\n }\n this.#process.emit = (ev, ...a) => {\n return this.#processEmit(ev, ...a);\n };\n this.#process.reallyExit = (code) => {\n return this.#processReallyExit(code);\n };\n }\n unload() {\n if (!this.#loaded) {\n return;\n }\n this.#loaded = false;\n signals.forEach(sig => {\n const listener = this.#sigListeners[sig];\n /* c8 ignore start */\n if (!listener) {\n throw new Error('Listener not defined for signal: ' + sig);\n }\n /* c8 ignore stop */\n try {\n this.#process.removeListener(sig, listener);\n /* c8 ignore start */\n }\n catch (_) { }\n /* c8 ignore stop */\n });\n this.#process.emit = this.#originalProcessEmit;\n this.#process.reallyExit = this.#originalProcessReallyExit;\n this.#emitter.count -= 1;\n }\n #processReallyExit(code) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return 0;\n }\n this.#process.exitCode = code || 0;\n /* c8 ignore stop */\n this.#emitter.emit('exit', this.#process.exitCode, null);\n return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);\n }\n #processEmit(ev, ...args) {\n const og = this.#originalProcessEmit;\n if (ev === 'exit' && processOk(this.#process)) {\n if (typeof args[0] === 'number') {\n this.#process.exitCode = args[0];\n /* c8 ignore start */\n }\n /* c8 ignore start */\n const ret = og.call(this.#process, ev, ...args);\n /* c8 ignore start */\n this.#emitter.emit('exit', this.#process.exitCode, null);\n /* c8 ignore stop */\n return ret;\n }\n else {\n return og.call(this.#process, ev, ...args);\n }\n }\n}\nconst process = globalThis.process;\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const { \n/**\n * Called when the process is exiting, whether via signal, explicit\n * exit, or running out of stuff to do.\n *\n * If the global process object is not suitable for instrumentation,\n * then this will be a no-op.\n *\n * Returns a function that may be used to unload signal-exit.\n */\nonExit, \n/**\n * Load the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\nload, \n/**\n * Unload the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\nunload, } = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback());\n//# sourceMappingURL=index.js.map","import process from 'node:process';\nimport onetime from 'onetime';\nimport {onExit} from 'signal-exit';\n\nconst terminal = process.stderr.isTTY\n\t? process.stderr\n\t: (process.stdout.isTTY ? process.stdout : undefined);\n\nconst restoreCursor = terminal ? onetime(() => {\n\tonExit(() => {\n\t\tterminal.write('\\u001B[?25h');\n\t}, {alwaysLast: true});\n}) : () => {};\n\nexport default restoreCursor;\n","import process from 'node:process';\nimport restoreCursor from 'restore-cursor';\n\nlet isHidden = false;\n\nconst cliCursor = {};\n\ncliCursor.show = (writableStream = process.stderr) => {\n\tif (!writableStream.isTTY) {\n\t\treturn;\n\t}\n\n\tisHidden = false;\n\twritableStream.write('\\u001B[?25h');\n};\n\ncliCursor.hide = (writableStream = process.stderr) => {\n\tif (!writableStream.isTTY) {\n\t\treturn;\n\t}\n\n\trestoreCursor();\n\tisHidden = true;\n\twritableStream.write('\\u001B[?25l');\n};\n\ncliCursor.toggle = (force, writableStream) => {\n\tif (force !== undefined) {\n\t\tisHidden = force;\n\t}\n\n\tif (isHidden) {\n\t\tcliCursor.show(writableStream);\n\t} else {\n\t\tcliCursor.hide(writableStream);\n\t}\n};\n\nexport default cliCursor;\n","'use strict';\n\nconst spinners = Object.assign({}, require('./spinners.json')); // eslint-disable-line import/extensions\n\nconst spinnersList = Object.keys(spinners);\n\nObject.defineProperty(spinners, 'random', {\n\tget() {\n\t\tconst randomIndex = Math.floor(Math.random() * spinnersList.length);\n\t\tconst spinnerName = spinnersList[randomIndex];\n\t\treturn spinners[spinnerName];\n\t}\n});\n\nmodule.exports = spinners;\n","const logSymbols = {\n\tinfo: 'ℹ️',\n\tsuccess: '✅',\n\twarning: '⚠️',\n\terror: '❌️',\n};\n\nexport default logSymbols;\n","export default function ansiRegex({onlyFirst = false} = {}) {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = '(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)';\n\n\t// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)\n\tconst osc = `(?:\\\\u001B\\\\][\\\\s\\\\S]*?${ST})`;\n\n\t// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte\n\tconst csi = '[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]';\n\n\tconst pattern = `${osc}|${csi}`;\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : 'g');\n}\n","import ansiRegex from 'ansi-regex';\n\nconst regex = ansiRegex();\n\nexport default function stripAnsi(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof string}\\``);\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn string.replace(regex, '');\n}\n","// Generated code.\n\nfunction isAmbiguous(x) {\n\treturn x === 0xA1\n\t\t|| x === 0xA4\n\t\t|| x === 0xA7\n\t\t|| x === 0xA8\n\t\t|| x === 0xAA\n\t\t|| x === 0xAD\n\t\t|| x === 0xAE\n\t\t|| x >= 0xB0 && x <= 0xB4\n\t\t|| x >= 0xB6 && x <= 0xBA\n\t\t|| x >= 0xBC && x <= 0xBF\n\t\t|| x === 0xC6\n\t\t|| x === 0xD0\n\t\t|| x === 0xD7\n\t\t|| x === 0xD8\n\t\t|| x >= 0xDE && x <= 0xE1\n\t\t|| x === 0xE6\n\t\t|| x >= 0xE8 && x <= 0xEA\n\t\t|| x === 0xEC\n\t\t|| x === 0xED\n\t\t|| x === 0xF0\n\t\t|| x === 0xF2\n\t\t|| x === 0xF3\n\t\t|| x >= 0xF7 && x <= 0xFA\n\t\t|| x === 0xFC\n\t\t|| x === 0xFE\n\t\t|| x === 0x101\n\t\t|| x === 0x111\n\t\t|| x === 0x113\n\t\t|| x === 0x11B\n\t\t|| x === 0x126\n\t\t|| x === 0x127\n\t\t|| x === 0x12B\n\t\t|| x >= 0x131 && x <= 0x133\n\t\t|| x === 0x138\n\t\t|| x >= 0x13F && x <= 0x142\n\t\t|| x === 0x144\n\t\t|| x >= 0x148 && x <= 0x14B\n\t\t|| x === 0x14D\n\t\t|| x === 0x152\n\t\t|| x === 0x153\n\t\t|| x === 0x166\n\t\t|| x === 0x167\n\t\t|| x === 0x16B\n\t\t|| x === 0x1CE\n\t\t|| x === 0x1D0\n\t\t|| x === 0x1D2\n\t\t|| x === 0x1D4\n\t\t|| x === 0x1D6\n\t\t|| x === 0x1D8\n\t\t|| x === 0x1DA\n\t\t|| x === 0x1DC\n\t\t|| x === 0x251\n\t\t|| x === 0x261\n\t\t|| x === 0x2C4\n\t\t|| x === 0x2C7\n\t\t|| x >= 0x2C9 && x <= 0x2CB\n\t\t|| x === 0x2CD\n\t\t|| x === 0x2D0\n\t\t|| x >= 0x2D8 && x <= 0x2DB\n\t\t|| x === 0x2DD\n\t\t|| x === 0x2DF\n\t\t|| x >= 0x300 && x <= 0x36F\n\t\t|| x >= 0x391 && x <= 0x3A1\n\t\t|| x >= 0x3A3 && x <= 0x3A9\n\t\t|| x >= 0x3B1 && x <= 0x3C1\n\t\t|| x >= 0x3C3 && x <= 0x3C9\n\t\t|| x === 0x401\n\t\t|| x >= 0x410 && x <= 0x44F\n\t\t|| x === 0x451\n\t\t|| x === 0x2010\n\t\t|| x >= 0x2013 && x <= 0x2016\n\t\t|| x === 0x2018\n\t\t|| x === 0x2019\n\t\t|| x === 0x201C\n\t\t|| x === 0x201D\n\t\t|| x >= 0x2020 && x <= 0x2022\n\t\t|| x >= 0x2024 && x <= 0x2027\n\t\t|| x === 0x2030\n\t\t|| x === 0x2032\n\t\t|| x === 0x2033\n\t\t|| x === 0x2035\n\t\t|| x === 0x203B\n\t\t|| x === 0x203E\n\t\t|| x === 0x2074\n\t\t|| x === 0x207F\n\t\t|| x >= 0x2081 && x <= 0x2084\n\t\t|| x === 0x20AC\n\t\t|| x === 0x2103\n\t\t|| x === 0x2105\n\t\t|| x === 0x2109\n\t\t|| x === 0x2113\n\t\t|| x === 0x2116\n\t\t|| x === 0x2121\n\t\t|| x === 0x2122\n\t\t|| x === 0x2126\n\t\t|| x === 0x212B\n\t\t|| x === 0x2153\n\t\t|| x === 0x2154\n\t\t|| x >= 0x215B && x <= 0x215E\n\t\t|| x >= 0x2160 && x <= 0x216B\n\t\t|| x >= 0x2170 && x <= 0x2179\n\t\t|| x === 0x2189\n\t\t|| x >= 0x2190 && x <= 0x2199\n\t\t|| x === 0x21B8\n\t\t|| x === 0x21B9\n\t\t|| x === 0x21D2\n\t\t|| x === 0x21D4\n\t\t|| x === 0x21E7\n\t\t|| x === 0x2200\n\t\t|| x === 0x2202\n\t\t|| x === 0x2203\n\t\t|| x === 0x2207\n\t\t|| x === 0x2208\n\t\t|| x === 0x220B\n\t\t|| x === 0x220F\n\t\t|| x === 0x2211\n\t\t|| x === 0x2215\n\t\t|| x === 0x221A\n\t\t|| x >= 0x221D && x <= 0x2220\n\t\t|| x === 0x2223\n\t\t|| x === 0x2225\n\t\t|| x >= 0x2227 && x <= 0x222C\n\t\t|| x === 0x222E\n\t\t|| x >= 0x2234 && x <= 0x2237\n\t\t|| x === 0x223C\n\t\t|| x === 0x223D\n\t\t|| x === 0x2248\n\t\t|| x === 0x224C\n\t\t|| x === 0x2252\n\t\t|| x === 0x2260\n\t\t|| x === 0x2261\n\t\t|| x >= 0x2264 && x <= 0x2267\n\t\t|| x === 0x226A\n\t\t|| x === 0x226B\n\t\t|| x === 0x226E\n\t\t|| x === 0x226F\n\t\t|| x === 0x2282\n\t\t|| x === 0x2283\n\t\t|| x === 0x2286\n\t\t|| x === 0x2287\n\t\t|| x === 0x2295\n\t\t|| x === 0x2299\n\t\t|| x === 0x22A5\n\t\t|| x === 0x22BF\n\t\t|| x === 0x2312\n\t\t|| x >= 0x2460 && x <= 0x24E9\n\t\t|| x >= 0x24EB && x <= 0x254B\n\t\t|| x >= 0x2550 && x <= 0x2573\n\t\t|| x >= 0x2580 && x <= 0x258F\n\t\t|| x >= 0x2592 && x <= 0x2595\n\t\t|| x === 0x25A0\n\t\t|| x === 0x25A1\n\t\t|| x >= 0x25A3 && x <= 0x25A9\n\t\t|| x === 0x25B2\n\t\t|| x === 0x25B3\n\t\t|| x === 0x25B6\n\t\t|| x === 0x25B7\n\t\t|| x === 0x25BC\n\t\t|| x === 0x25BD\n\t\t|| x === 0x25C0\n\t\t|| x === 0x25C1\n\t\t|| x >= 0x25C6 && x <= 0x25C8\n\t\t|| x === 0x25CB\n\t\t|| x >= 0x25CE && x <= 0x25D1\n\t\t|| x >= 0x25E2 && x <= 0x25E5\n\t\t|| x === 0x25EF\n\t\t|| x === 0x2605\n\t\t|| x === 0x2606\n\t\t|| x === 0x2609\n\t\t|| x === 0x260E\n\t\t|| x === 0x260F\n\t\t|| x === 0x261C\n\t\t|| x === 0x261E\n\t\t|| x === 0x2640\n\t\t|| x === 0x2642\n\t\t|| x === 0x2660\n\t\t|| x === 0x2661\n\t\t|| x >= 0x2663 && x <= 0x2665\n\t\t|| x >= 0x2667 && x <= 0x266A\n\t\t|| x === 0x266C\n\t\t|| x === 0x266D\n\t\t|| x === 0x266F\n\t\t|| x === 0x269E\n\t\t|| x === 0x269F\n\t\t|| x === 0x26BF\n\t\t|| x >= 0x26C6 && x <= 0x26CD\n\t\t|| x >= 0x26CF && x <= 0x26D3\n\t\t|| x >= 0x26D5 && x <= 0x26E1\n\t\t|| x === 0x26E3\n\t\t|| x === 0x26E8\n\t\t|| x === 0x26E9\n\t\t|| x >= 0x26EB && x <= 0x26F1\n\t\t|| x === 0x26F4\n\t\t|| x >= 0x26F6 && x <= 0x26F9\n\t\t|| x === 0x26FB\n\t\t|| x === 0x26FC\n\t\t|| x === 0x26FE\n\t\t|| x === 0x26FF\n\t\t|| x === 0x273D\n\t\t|| x >= 0x2776 && x <= 0x277F\n\t\t|| x >= 0x2B56 && x <= 0x2B59\n\t\t|| x >= 0x3248 && x <= 0x324F\n\t\t|| x >= 0xE000 && x <= 0xF8FF\n\t\t|| x >= 0xFE00 && x <= 0xFE0F\n\t\t|| x === 0xFFFD\n\t\t|| x >= 0x1F100 && x <= 0x1F10A\n\t\t|| x >= 0x1F110 && x <= 0x1F12D\n\t\t|| x >= 0x1F130 && x <= 0x1F169\n\t\t|| x >= 0x1F170 && x <= 0x1F18D\n\t\t|| x === 0x1F18F\n\t\t|| x === 0x1F190\n\t\t|| x >= 0x1F19B && x <= 0x1F1AC\n\t\t|| x >= 0xE0100 && x <= 0xE01EF\n\t\t|| x >= 0xF0000 && x <= 0xFFFFD\n\t\t|| x >= 0x100000 && x <= 0x10FFFD;\n}\n\nfunction isFullWidth(x) {\n\treturn x === 0x3000\n\t\t|| x >= 0xFF01 && x <= 0xFF60\n\t\t|| x >= 0xFFE0 && x <= 0xFFE6;\n}\n\nfunction isWide(x) {\n\treturn x >= 0x1100 && x <= 0x115F\n\t\t|| x === 0x231A\n\t\t|| x === 0x231B\n\t\t|| x === 0x2329\n\t\t|| x === 0x232A\n\t\t|| x >= 0x23E9 && x <= 0x23EC\n\t\t|| x === 0x23F0\n\t\t|| x === 0x23F3\n\t\t|| x === 0x25FD\n\t\t|| x === 0x25FE\n\t\t|| x === 0x2614\n\t\t|| x === 0x2615\n\t\t|| x >= 0x2630 && x <= 0x2637\n\t\t|| x >= 0x2648 && x <= 0x2653\n\t\t|| x === 0x267F\n\t\t|| x >= 0x268A && x <= 0x268F\n\t\t|| x === 0x2693\n\t\t|| x === 0x26A1\n\t\t|| x === 0x26AA\n\t\t|| x === 0x26AB\n\t\t|| x === 0x26BD\n\t\t|| x === 0x26BE\n\t\t|| x === 0x26C4\n\t\t|| x === 0x26C5\n\t\t|| x === 0x26CE\n\t\t|| x === 0x26D4\n\t\t|| x === 0x26EA\n\t\t|| x === 0x26F2\n\t\t|| x === 0x26F3\n\t\t|| x === 0x26F5\n\t\t|| x === 0x26FA\n\t\t|| x === 0x26FD\n\t\t|| x === 0x2705\n\t\t|| x === 0x270A\n\t\t|| x === 0x270B\n\t\t|| x === 0x2728\n\t\t|| x === 0x274C\n\t\t|| x === 0x274E\n\t\t|| x >= 0x2753 && x <= 0x2755\n\t\t|| x === 0x2757\n\t\t|| x >= 0x2795 && x <= 0x2797\n\t\t|| x === 0x27B0\n\t\t|| x === 0x27BF\n\t\t|| x === 0x2B1B\n\t\t|| x === 0x2B1C\n\t\t|| x === 0x2B50\n\t\t|| x === 0x2B55\n\t\t|| x >= 0x2E80 && x <= 0x2E99\n\t\t|| x >= 0x2E9B && x <= 0x2EF3\n\t\t|| x >= 0x2F00 && x <= 0x2FD5\n\t\t|| x >= 0x2FF0 && x <= 0x2FFF\n\t\t|| x >= 0x3001 && x <= 0x303E\n\t\t|| x >= 0x3041 && x <= 0x3096\n\t\t|| x >= 0x3099 && x <= 0x30FF\n\t\t|| x >= 0x3105 && x <= 0x312F\n\t\t|| x >= 0x3131 && x <= 0x318E\n\t\t|| x >= 0x3190 && x <= 0x31E5\n\t\t|| x >= 0x31EF && x <= 0x321E\n\t\t|| x >= 0x3220 && x <= 0x3247\n\t\t|| x >= 0x3250 && x <= 0xA48C\n\t\t|| x >= 0xA490 && x <= 0xA4C6\n\t\t|| x >= 0xA960 && x <= 0xA97C\n\t\t|| x >= 0xAC00 && x <= 0xD7A3\n\t\t|| x >= 0xF900 && x <= 0xFAFF\n\t\t|| x >= 0xFE10 && x <= 0xFE19\n\t\t|| x >= 0xFE30 && x <= 0xFE52\n\t\t|| x >= 0xFE54 && x <= 0xFE66\n\t\t|| x >= 0xFE68 && x <= 0xFE6B\n\t\t|| x >= 0x16FE0 && x <= 0x16FE4\n\t\t|| x >= 0x16FF0 && x <= 0x16FF6\n\t\t|| x >= 0x17000 && x <= 0x18CD5\n\t\t|| x >= 0x18CFF && x <= 0x18D1E\n\t\t|| x >= 0x18D80 && x <= 0x18DF2\n\t\t|| x >= 0x1AFF0 && x <= 0x1AFF3\n\t\t|| x >= 0x1AFF5 && x <= 0x1AFFB\n\t\t|| x === 0x1AFFD\n\t\t|| x === 0x1AFFE\n\t\t|| x >= 0x1B000 && x <= 0x1B122\n\t\t|| x === 0x1B132\n\t\t|| x >= 0x1B150 && x <= 0x1B152\n\t\t|| x === 0x1B155\n\t\t|| x >= 0x1B164 && x <= 0x1B167\n\t\t|| x >= 0x1B170 && x <= 0x1B2FB\n\t\t|| x >= 0x1D300 && x <= 0x1D356\n\t\t|| x >= 0x1D360 && x <= 0x1D376\n\t\t|| x === 0x1F004\n\t\t|| x === 0x1F0CF\n\t\t|| x === 0x1F18E\n\t\t|| x >= 0x1F191 && x <= 0x1F19A\n\t\t|| x >= 0x1F200 && x <= 0x1F202\n\t\t|| x >= 0x1F210 && x <= 0x1F23B\n\t\t|| x >= 0x1F240 && x <= 0x1F248\n\t\t|| x === 0x1F250\n\t\t|| x === 0x1F251\n\t\t|| x >= 0x1F260 && x <= 0x1F265\n\t\t|| x >= 0x1F300 && x <= 0x1F320\n\t\t|| x >= 0x1F32D && x <= 0x1F335\n\t\t|| x >= 0x1F337 && x <= 0x1F37C\n\t\t|| x >= 0x1F37E && x <= 0x1F393\n\t\t|| x >= 0x1F3A0 && x <= 0x1F3CA\n\t\t|| x >= 0x1F3CF && x <= 0x1F3D3\n\t\t|| x >= 0x1F3E0 && x <= 0x1F3F0\n\t\t|| x === 0x1F3F4\n\t\t|| x >= 0x1F3F8 && x <= 0x1F43E\n\t\t|| x === 0x1F440\n\t\t|| x >= 0x1F442 && x <= 0x1F4FC\n\t\t|| x >= 0x1F4FF && x <= 0x1F53D\n\t\t|| x >= 0x1F54B && x <= 0x1F54E\n\t\t|| x >= 0x1F550 && x <= 0x1F567\n\t\t|| x === 0x1F57A\n\t\t|| x === 0x1F595\n\t\t|| x === 0x1F596\n\t\t|| x === 0x1F5A4\n\t\t|| x >= 0x1F5FB && x <= 0x1F64F\n\t\t|| x >= 0x1F680 && x <= 0x1F6C5\n\t\t|| x === 0x1F6CC\n\t\t|| x >= 0x1F6D0 && x <= 0x1F6D2\n\t\t|| x >= 0x1F6D5 && x <= 0x1F6D8\n\t\t|| x >= 0x1F6DC && x <= 0x1F6DF\n\t\t|| x === 0x1F6EB\n\t\t|| x === 0x1F6EC\n\t\t|| x >= 0x1F6F4 && x <= 0x1F6FC\n\t\t|| x >= 0x1F7E0 && x <= 0x1F7EB\n\t\t|| x === 0x1F7F0\n\t\t|| x >= 0x1F90C && x <= 0x1F93A\n\t\t|| x >= 0x1F93C && x <= 0x1F945\n\t\t|| x >= 0x1F947 && x <= 0x1F9FF\n\t\t|| x >= 0x1FA70 && x <= 0x1FA7C\n\t\t|| x >= 0x1FA80 && x <= 0x1FA8A\n\t\t|| x >= 0x1FA8E && x <= 0x1FAC6\n\t\t|| x === 0x1FAC8\n\t\t|| x >= 0x1FACD && x <= 0x1FADC\n\t\t|| x >= 0x1FADF && x <= 0x1FAEA\n\t\t|| x >= 0x1FAEF && x <= 0x1FAF8\n\t\t|| x >= 0x20000 && x <= 0x2FFFD\n\t\t|| x >= 0x30000 && x <= 0x3FFFD;\n}\n\nfunction getCategory(x) {\n\tif (isAmbiguous(x)) return 'ambiguous';\n\n\tif (isFullWidth(x)) return 'fullwidth';\n\n\tif (\n\t\tx === 0x20A9\n\t\t|| x >= 0xFF61 && x <= 0xFFBE\n\t\t|| x >= 0xFFC2 && x <= 0xFFC7\n\t\t|| x >= 0xFFCA && x <= 0xFFCF\n\t\t|| x >= 0xFFD2 && x <= 0xFFD7\n\t\t|| x >= 0xFFDA && x <= 0xFFDC\n\t\t|| x >= 0xFFE8 && x <= 0xFFEE\n\t) {\n\t\treturn 'halfwidth';\n\t}\n\n\tif (\n\t\tx >= 0x20 && x <= 0x7E\n\t\t|| x === 0xA2\n\t\t|| x === 0xA3\n\t\t|| x === 0xA5\n\t\t|| x === 0xA6\n\t\t|| x === 0xAC\n\t\t|| x === 0xAF\n\t\t|| x >= 0x27E6 && x <= 0x27ED\n\t\t|| x === 0x2985\n\t\t|| x === 0x2986\n\t) {\n\t\treturn 'narrow';\n\t}\n\n\tif (isWide(x)) return 'wide';\n\n\treturn 'neutral';\n}\n\nexport {isAmbiguous, isFullWidth, isWide, getCategory};\n","import {getCategory, isAmbiguous, isFullWidth, isWide} from './lookup.js';\n\nfunction validate(codePoint) {\n\tif (!Number.isSafeInteger(codePoint)) {\n\t\tthrow new TypeError(`Expected a code point, got \\`${typeof codePoint}\\`.`);\n\t}\n}\n\nexport function eastAsianWidthType(codePoint) {\n\tvalidate(codePoint);\n\n\treturn getCategory(codePoint);\n}\n\nexport function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) {\n\tvalidate(codePoint);\n\n\tif (\n\t\tisFullWidth(codePoint)\n\t\t|| isWide(codePoint)\n\t\t|| (ambiguousAsWide && isAmbiguous(codePoint))\n\t) {\n\t\treturn 2;\n\t}\n\n\treturn 1;\n}\n\n// Private exports for https://github.com/sindresorhus/is-fullwidth-code-point\nexport {isFullWidth as _isFullWidth, isWide as _isWide} from './lookup.js';\n","export default () => {\n\t// https://mths.be/emoji\n\treturn /[#*0-9]\\uFE0F?\\u20E3|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26AA\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C8\\u26CF\\u26D1\\u26E9\\u26F0-\\u26F5\\u26F7\\u26F8\\u26FA\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B55\\u3030\\u303D\\u3297\\u3299]\\uFE0F?|[\\u261D\\u270C\\u270D](?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?|[\\u270A\\u270B](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u2693\\u26A1\\u26AB\\u26C5\\u26CE\\u26D4\\u26EA\\u26FD\\u2705\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2795-\\u2797\\u27B0\\u27BF\\u2B50]|\\u26D3\\uFE0F?(?:\\u200D\\uD83D\\uDCA5)?|\\u26F9(?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\u2764\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\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDC68\\uDC69]\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFC-\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFC-\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFD-\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFD\\uDFFF]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFE])|\\uD83E(?:[\\uDD1D\\uDEEF]\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFE]|[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3])))?))?|\\uDC69(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?[\\uDC68\\uDC69]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?|\\uDC69\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?))|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFC-\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFC-\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFD-\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC30\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFD\\uDFFF]|\\uDEEF\\u200D\\uD83D\\uDC69\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFF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[\\uDFFB-\\uDFFF]|\\uDEEF\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDEF1(?:\\uD83C(?:\\uDFFB(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFC-\\uDFFF])?|\\uDFFC(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])?|\\uDFFD(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])?|\\uDFFE(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])?|\\uDFFF(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFE])?))?)/g;\n};\n","import stripAnsi from 'strip-ansi';\nimport {eastAsianWidth} from 'get-east-asian-width';\nimport emojiRegex from 'emoji-regex';\n\nconst segmenter = new Intl.Segmenter();\n\nconst defaultIgnorableCodePointRegex = /^\\p{Default_Ignorable_Code_Point}$/u;\n\nexport default function stringWidth(string, options = {}) {\n\tif (typeof string !== 'string' || string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tconst {\n\t\tambiguousIsNarrow = true,\n\t\tcountAnsiEscapeCodes = false,\n\t} = options;\n\n\tif (!countAnsiEscapeCodes) {\n\t\tstring = stripAnsi(string);\n\t}\n\n\tif (string.length === 0) {\n\t\treturn 0;\n\t}\n\n\tlet width = 0;\n\tconst eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow};\n\n\tfor (const {segment: character} of segmenter.segment(string)) {\n\t\tconst codePoint = character.codePointAt(0);\n\n\t\t// Ignore control characters\n\t\tif (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore zero-width characters\n\t\tif (\n\t\t\t(codePoint >= 0x20_0B && codePoint <= 0x20_0F) // Zero-width space, non-joiner, joiner, left-to-right mark, right-to-left mark\n\t\t\t|| codePoint === 0xFE_FF // Zero-width no-break space\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore combining characters\n\t\tif (\n\t\t\t(codePoint >= 0x3_00 && codePoint <= 0x3_6F) // Combining diacritical marks\n\t\t\t|| (codePoint >= 0x1A_B0 && codePoint <= 0x1A_FF) // Combining diacritical marks extended\n\t\t\t|| (codePoint >= 0x1D_C0 && codePoint <= 0x1D_FF) // Combining diacritical marks supplement\n\t\t\t|| (codePoint >= 0x20_D0 && codePoint <= 0x20_FF) // Combining diacritical marks for symbols\n\t\t\t|| (codePoint >= 0xFE_20 && codePoint <= 0xFE_2F) // Combining half marks\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore surrogate pairs\n\t\tif (codePoint >= 0xD8_00 && codePoint <= 0xDF_FF) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Ignore variation selectors\n\t\tif (codePoint >= 0xFE_00 && codePoint <= 0xFE_0F) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// This covers some of the above cases, but we still keep them for performance reasons.\n\t\tif (defaultIgnorableCodePointRegex.test(character)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// TODO: Use `/\\p{RGI_Emoji}/v` when targeting Node.js 20.\n\t\tif (emojiRegex().test(character)) {\n\t\t\twidth += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\twidth += eastAsianWidth(codePoint, eastAsianWidthOptions);\n\t}\n\n\treturn width;\n}\n","export default function isInteractive({stream = process.stdout} = {}) {\n\treturn Boolean(\n\t\tstream && stream.isTTY &&\n\t\tprocess.env.TERM !== 'dumb' &&\n\t\t!('CI' in process.env)\n\t);\n}\n","import process from 'node:process';\n\nexport default function isUnicodeSupported() {\n\tconst {env} = process;\n\tconst {TERM, TERM_PROGRAM} = env;\n\n\tif (process.platform !== 'win32') {\n\t\treturn TERM !== 'linux'; // Linux console (kernel)\n\t}\n\n\treturn Boolean(env.WT_SESSION) // Windows Terminal\n\t\t|| Boolean(env.TERMINUS_SUBLIME) // Terminus (<0.2.27)\n\t\t|| env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder\n\t\t|| TERM_PROGRAM === 'Terminus-Sublime'\n\t\t|| TERM_PROGRAM === 'vscode'\n\t\t|| TERM === 'xterm-256color'\n\t\t|| TERM === 'alacritty'\n\t\t|| TERM === 'rxvt-unicode'\n\t\t|| TERM === 'rxvt-unicode-256color'\n\t\t|| env.TERMINAL_EMULATOR === 'JetBrains-JediTerm';\n}\n","import process from 'node:process';\n\nconst ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code\n\nclass StdinDiscarder {\n\t#activeCount = 0;\n\n\tstart() {\n\t\tthis.#activeCount++;\n\n\t\tif (this.#activeCount === 1) {\n\t\t\tthis.#realStart();\n\t\t}\n\t}\n\n\tstop() {\n\t\tif (this.#activeCount <= 0) {\n\t\t\tthrow new Error('`stop` called more times than `start`');\n\t\t}\n\n\t\tthis.#activeCount--;\n\n\t\tif (this.#activeCount === 0) {\n\t\t\tthis.#realStop();\n\t\t}\n\t}\n\n\t#realStart() {\n\t\t// No known way to make it work reliably on Windows.\n\t\tif (process.platform === 'win32' || !process.stdin.isTTY) {\n\t\t\treturn;\n\t\t}\n\n\t\tprocess.stdin.setRawMode(true);\n\t\tprocess.stdin.on('data', this.#handleInput);\n\t\tprocess.stdin.resume();\n\t}\n\n\t#realStop() {\n\t\tif (!process.stdin.isTTY) {\n\t\t\treturn;\n\t\t}\n\n\t\tprocess.stdin.off('data', this.#handleInput);\n\t\tprocess.stdin.pause();\n\t\tprocess.stdin.setRawMode(false);\n\t}\n\n\t#handleInput(chunk) {\n\t\t// Allow Ctrl+C to gracefully exit.\n\t\tif (chunk[0] === ASCII_ETX_CODE) {\n\t\t\tprocess.emit('SIGINT');\n\t\t}\n\t}\n}\n\nconst stdinDiscarder = new StdinDiscarder();\n\nexport default stdinDiscarder;\n","import process from 'node:process';\nimport chalk from 'chalk';\nimport cliCursor from 'cli-cursor';\nimport cliSpinners from 'cli-spinners';\nimport logSymbols from 'log-symbols';\nimport stripAnsi from 'strip-ansi';\nimport stringWidth from 'string-width';\nimport isInteractive from 'is-interactive';\nimport isUnicodeSupported from 'is-unicode-supported';\nimport stdinDiscarder from 'stdin-discarder';\n\nclass Ora {\n\t#linesToClear = 0;\n\t#isDiscardingStdin = false;\n\t#lineCount = 0;\n\t#frameIndex = -1;\n\t#lastSpinnerFrameTime = 0;\n\t#options;\n\t#spinner;\n\t#stream;\n\t#id;\n\t#initialInterval;\n\t#isEnabled;\n\t#isSilent;\n\t#indent;\n\t#text;\n\t#prefixText;\n\t#suffixText;\n\tcolor;\n\n\tconstructor(options) {\n\t\tif (typeof options === 'string') {\n\t\t\toptions = {\n\t\t\t\ttext: options,\n\t\t\t};\n\t\t}\n\n\t\tthis.#options = {\n\t\t\tcolor: 'cyan',\n\t\t\tstream: process.stderr,\n\t\t\tdiscardStdin: true,\n\t\t\thideCursor: true,\n\t\t\t...options,\n\t\t};\n\n\t\t// Public\n\t\tthis.color = this.#options.color;\n\n\t\t// It's important that these use the public setters.\n\t\tthis.spinner = this.#options.spinner;\n\n\t\tthis.#initialInterval = this.#options.interval;\n\t\tthis.#stream = this.#options.stream;\n\t\tthis.#isEnabled = typeof this.#options.isEnabled === 'boolean' ? this.#options.isEnabled : isInteractive({stream: this.#stream});\n\t\tthis.#isSilent = typeof this.#options.isSilent === 'boolean' ? this.#options.isSilent : false;\n\n\t\t// Set *after* `this.#stream`.\n\t\t// It's important that these use the public setters.\n\t\tthis.text = this.#options.text;\n\t\tthis.prefixText = this.#options.prefixText;\n\t\tthis.suffixText = this.#options.suffixText;\n\t\tthis.indent = this.#options.indent;\n\n\t\tif (process.env.NODE_ENV === 'test') {\n\t\t\tthis._stream = this.#stream;\n\t\t\tthis._isEnabled = this.#isEnabled;\n\n\t\t\tObject.defineProperty(this, '_linesToClear', {\n\t\t\t\tget() {\n\t\t\t\t\treturn this.#linesToClear;\n\t\t\t\t},\n\t\t\t\tset(newValue) {\n\t\t\t\t\tthis.#linesToClear = newValue;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tObject.defineProperty(this, '_frameIndex', {\n\t\t\t\tget() {\n\t\t\t\t\treturn this.#frameIndex;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tObject.defineProperty(this, '_lineCount', {\n\t\t\t\tget() {\n\t\t\t\t\treturn this.#lineCount;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tget indent() {\n\t\treturn this.#indent;\n\t}\n\n\tset indent(indent = 0) {\n\t\tif (!(indent >= 0 && Number.isInteger(indent))) {\n\t\t\tthrow new Error('The `indent` option must be an integer from 0 and up');\n\t\t}\n\n\t\tthis.#indent = indent;\n\t\tthis.#updateLineCount();\n\t}\n\n\tget interval() {\n\t\treturn this.#initialInterval ?? this.#spinner.interval ?? 100;\n\t}\n\n\tget spinner() {\n\t\treturn this.#spinner;\n\t}\n\n\tset spinner(spinner) {\n\t\tthis.#frameIndex = -1;\n\t\tthis.#initialInterval = undefined;\n\n\t\tif (typeof spinner === 'object') {\n\t\t\tif (spinner.frames === undefined) {\n\t\t\t\tthrow new Error('The given spinner must have a `frames` property');\n\t\t\t}\n\n\t\t\tthis.#spinner = spinner;\n\t\t} else if (!isUnicodeSupported()) {\n\t\t\tthis.#spinner = cliSpinners.line;\n\t\t} else if (spinner === undefined) {\n\t\t\t// Set default spinner\n\t\t\tthis.#spinner = cliSpinners.dots;\n\t\t} else if (spinner !== 'default' && cliSpinners[spinner]) {\n\t\t\tthis.#spinner = cliSpinners[spinner];\n\t\t} else {\n\t\t\tthrow new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);\n\t\t}\n\t}\n\n\tget text() {\n\t\treturn this.#text;\n\t}\n\n\tset text(value = '') {\n\t\tthis.#text = value;\n\t\tthis.#updateLineCount();\n\t}\n\n\tget prefixText() {\n\t\treturn this.#prefixText;\n\t}\n\n\tset prefixText(value = '') {\n\t\tthis.#prefixText = value;\n\t\tthis.#updateLineCount();\n\t}\n\n\tget suffixText() {\n\t\treturn this.#suffixText;\n\t}\n\n\tset suffixText(value = '') {\n\t\tthis.#suffixText = value;\n\t\tthis.#updateLineCount();\n\t}\n\n\tget isSpinning() {\n\t\treturn this.#id !== undefined;\n\t}\n\n\t#getFullPrefixText(prefixText = this.#prefixText, postfix = ' ') {\n\t\tif (typeof prefixText === 'string' && prefixText !== '') {\n\t\t\treturn prefixText + postfix;\n\t\t}\n\n\t\tif (typeof prefixText === 'function') {\n\t\t\treturn prefixText() + postfix;\n\t\t}\n\n\t\treturn '';\n\t}\n\n\t#getFullSuffixText(suffixText = this.#suffixText, prefix = ' ') {\n\t\tif (typeof suffixText === 'string' && suffixText !== '') {\n\t\t\treturn prefix + suffixText;\n\t\t}\n\n\t\tif (typeof suffixText === 'function') {\n\t\t\treturn prefix + suffixText();\n\t\t}\n\n\t\treturn '';\n\t}\n\n\t#updateLineCount() {\n\t\tconst columns = this.#stream.columns ?? 80;\n\t\tconst fullPrefixText = this.#getFullPrefixText(this.#prefixText, '-');\n\t\tconst fullSuffixText = this.#getFullSuffixText(this.#suffixText, '-');\n\t\tconst fullText = ' '.repeat(this.#indent) + fullPrefixText + '--' + this.#text + '--' + fullSuffixText;\n\n\t\tthis.#lineCount = 0;\n\t\tfor (const line of stripAnsi(fullText).split('\\n')) {\n\t\t\tthis.#lineCount += Math.max(1, Math.ceil(stringWidth(line, {countAnsiEscapeCodes: true}) / columns));\n\t\t}\n\t}\n\n\tget isEnabled() {\n\t\treturn this.#isEnabled && !this.#isSilent;\n\t}\n\n\tset isEnabled(value) {\n\t\tif (typeof value !== 'boolean') {\n\t\t\tthrow new TypeError('The `isEnabled` option must be a boolean');\n\t\t}\n\n\t\tthis.#isEnabled = value;\n\t}\n\n\tget isSilent() {\n\t\treturn this.#isSilent;\n\t}\n\n\tset isSilent(value) {\n\t\tif (typeof value !== 'boolean') {\n\t\t\tthrow new TypeError('The `isSilent` option must be a boolean');\n\t\t}\n\n\t\tthis.#isSilent = value;\n\t}\n\n\tframe() {\n\t\t// Ensure we only update the spinner frame at the wanted interval,\n\t\t// even if the render method is called more often.\n\t\tconst now = Date.now();\n\t\tif (this.#frameIndex === -1 || now - this.#lastSpinnerFrameTime >= this.interval) {\n\t\t\tthis.#frameIndex = ++this.#frameIndex % this.#spinner.frames.length;\n\t\t\tthis.#lastSpinnerFrameTime = now;\n\t\t}\n\n\t\tconst {frames} = this.#spinner;\n\t\tlet frame = frames[this.#frameIndex];\n\n\t\tif (this.color) {\n\t\t\tframe = chalk[this.color](frame);\n\t\t}\n\n\t\tconst fullPrefixText = (typeof this.#prefixText === 'string' && this.#prefixText !== '') ? this.#prefixText + ' ' : '';\n\t\tconst fullText = typeof this.text === 'string' ? ' ' + this.text : '';\n\t\tconst fullSuffixText = (typeof this.#suffixText === 'string' && this.#suffixText !== '') ? ' ' + this.#suffixText : '';\n\n\t\treturn fullPrefixText + frame + fullText + fullSuffixText;\n\t}\n\n\tclear() {\n\t\tif (!this.#isEnabled || !this.#stream.isTTY) {\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.#stream.cursorTo(0);\n\n\t\tfor (let index = 0; index < this.#linesToClear; index++) {\n\t\t\tif (index > 0) {\n\t\t\t\tthis.#stream.moveCursor(0, -1);\n\t\t\t}\n\n\t\t\tthis.#stream.clearLine(1);\n\t\t}\n\n\t\tif (this.#indent || this.lastIndent !== this.#indent) {\n\t\t\tthis.#stream.cursorTo(this.#indent);\n\t\t}\n\n\t\tthis.lastIndent = this.#indent;\n\t\tthis.#linesToClear = 0;\n\n\t\treturn this;\n\t}\n\n\trender() {\n\t\tif (this.#isSilent) {\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.clear();\n\t\tthis.#stream.write(this.frame());\n\t\tthis.#linesToClear = this.#lineCount;\n\n\t\treturn this;\n\t}\n\n\tstart(text) {\n\t\tif (text) {\n\t\t\tthis.text = text;\n\t\t}\n\n\t\tif (this.#isSilent) {\n\t\t\treturn this;\n\t\t}\n\n\t\tif (!this.#isEnabled) {\n\t\t\tif (this.text) {\n\t\t\t\tthis.#stream.write(`- ${this.text}\\n`);\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\tif (this.isSpinning) {\n\t\t\treturn this;\n\t\t}\n\n\t\tif (this.#options.hideCursor) {\n\t\t\tcliCursor.hide(this.#stream);\n\t\t}\n\n\t\tif (this.#options.discardStdin && process.stdin.isTTY) {\n\t\t\tthis.#isDiscardingStdin = true;\n\t\t\tstdinDiscarder.start();\n\t\t}\n\n\t\tthis.render();\n\t\tthis.#id = setInterval(this.render.bind(this), this.interval);\n\n\t\treturn this;\n\t}\n\n\tstop() {\n\t\tif (!this.#isEnabled) {\n\t\t\treturn this;\n\t\t}\n\n\t\tclearInterval(this.#id);\n\t\tthis.#id = undefined;\n\t\tthis.#frameIndex = 0;\n\t\tthis.clear();\n\t\tif (this.#options.hideCursor) {\n\t\t\tcliCursor.show(this.#stream);\n\t\t}\n\n\t\tif (this.#options.discardStdin && process.stdin.isTTY && this.#isDiscardingStdin) {\n\t\t\tstdinDiscarder.stop();\n\t\t\tthis.#isDiscardingStdin = false;\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tsucceed(text) {\n\t\treturn this.stopAndPersist({symbol: logSymbols.success, text});\n\t}\n\n\tfail(text) {\n\t\treturn this.stopAndPersist({symbol: logSymbols.error, text});\n\t}\n\n\twarn(text) {\n\t\treturn this.stopAndPersist({symbol: logSymbols.warning, text});\n\t}\n\n\tinfo(text) {\n\t\treturn this.stopAndPersist({symbol: logSymbols.info, text});\n\t}\n\n\tstopAndPersist(options = {}) {\n\t\tif (this.#isSilent) {\n\t\t\treturn this;\n\t\t}\n\n\t\tconst prefixText = options.prefixText ?? this.#prefixText;\n\t\tconst fullPrefixText = this.#getFullPrefixText(prefixText, ' ');\n\n\t\tconst symbolText = options.symbol ?? ' ';\n\n\t\tconst text = options.text ?? this.text;\n\t\tconst separatorText = symbolText ? ' ' : '';\n\t\tconst fullText = (typeof text === 'string') ? separatorText + text : '';\n\n\t\tconst suffixText = options.suffixText ?? this.#suffixText;\n\t\tconst fullSuffixText = this.#getFullSuffixText(suffixText, ' ');\n\n\t\tconst textToWrite = fullPrefixText + symbolText + fullText + fullSuffixText + '\\n';\n\n\t\tthis.stop();\n\t\tthis.#stream.write(textToWrite);\n\n\t\treturn this;\n\t}\n}\n\nexport default function ora(options) {\n\treturn new Ora(options);\n}\n\nexport async function oraPromise(action, options) {\n\tconst actionIsFunction = typeof action === 'function';\n\tconst actionIsPromise = typeof action.then === 'function';\n\n\tif (!actionIsFunction && !actionIsPromise) {\n\t\tthrow new TypeError('Parameter `action` must be a Function or a Promise');\n\t}\n\n\tconst {successText, failText} = typeof options === 'object'\n\t\t? options\n\t\t: {successText: undefined, failText: undefined};\n\n\tconst spinner = ora(options).start();\n\n\ttry {\n\t\tconst promise = actionIsFunction ? action(spinner) : action;\n\t\tconst result = await promise;\n\n\t\tspinner.succeed(\n\t\t\tsuccessText === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (typeof successText === 'string' ? successText : successText(result)),\n\t\t);\n\n\t\treturn result;\n\t} catch (error) {\n\t\tspinner.fail(\n\t\t\tfailText === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (typeof failText === 'string' ? failText : failText(error)),\n\t\t);\n\n\t\tthrow error;\n\t}\n}\n\nexport {default as spinners} from 'cli-spinners';\n","import chalk from 'chalk';\nimport { Command } from 'commander';\nimport ora, { type Ora } from 'ora';\n\nexport abstract class BaseCommand {\n protected spinner?: Ora;\n\n abstract register(program: Command): void;\n\n protected createSpinner(text: string): Ora {\n this.spinner = ora(text);\n return this.spinner;\n }\n\n protected success(message: string): void {\n try {\n if (this.spinner) {\n this.spinner.succeed(chalk.green(message));\n } else {\n console.log(chalk.green('✓'), message);\n }\n } catch (error) {\n // Ultimate fallback\n try {\n process.stdout?.write?.(`✓ ${message}\\n`);\n } catch {\n // Last resort - just exit silently rather than crash\n }\n }\n }\n\n protected error(message: string): void {\n try {\n if (this.spinner) {\n this.spinner.fail(chalk.red(message));\n } else {\n console.error(chalk.red('✗'), message);\n }\n } catch (error) {\n // Ultimate fallback\n try {\n process.stderr?.write?.(`✗ ${message}\\n`);\n } catch {\n // Last resort - just exit silently rather than crash\n }\n }\n }\n\n protected info(message: string): void {\n try {\n if (this.spinner) {\n this.spinner.info(chalk.blue(message));\n } else {\n console.log(chalk.blue('ℹ'), message);\n }\n } catch (error) {\n // Ultimate fallback\n try {\n process.stdout?.write?.(`ℹ ${message}\\n`);\n } catch {\n // Last resort - just exit silently rather than crash\n }\n }\n }\n\n protected warn(message: string): void {\n try {\n if (this.spinner) {\n this.spinner.warn(chalk.yellow(message));\n } else {\n console.warn(chalk.yellow('⚠'), message);\n }\n } catch (error) {\n // Ultimate fallback\n try {\n process.stderr?.write?.(`⚠ ${message}\\n`);\n } catch {\n // Last resort - just exit silently rather than crash\n }\n }\n }\n\n protected handleError(error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n this.error(message);\n\n if (process.env.DEBUG && error instanceof Error) {\n console.error(chalk.gray('Stack trace:'));\n console.error(chalk.gray(error.stack));\n }\n\n process.exit(1);\n }\n}\n","//#region src/constants/agentSession.ts\n/**\n* @agimonai/universal-agent-events\n*\n* Agent Session Constants\n*\n* Shared constants for agent session management and communication.\n* These constants are extracted from the agent message schemas to ensure\n* consistency across frontend, backend, and CLI applications.\n*\n* DESIGN PATTERNS:\n* - Centralized Constants: Single source of truth for agent-related enums\n* - Type Safety: Const assertions for literal type inference\n* - Consistency: Matches backend message schema definitions\n* - Reusability: Shared across all agent communication layers\n*/\nconst AGENT_EVENT_TYPES = {\n\tSTATUS: \"agent-status\",\n\tRESIZE: \"agent-pty-resize\",\n\tDIRECT_CONTROL: \"agent-direct-control\",\n\tMESSAGE_INPUT: \"agent-message-input\",\n\tMESSAGE_OUTPUT: \"agent-message-output\",\n\tMESSAGE_OUTPUT_STARTED: \"agent-message-output-started\",\n\tMESSAGE_OUTPUT_ENDED: \"agent-message-output-ended\",\n\tMESSAGE_OUTPUT_PERMISSION_REQUESTED: \"agent-message-output-permission-requested\",\n\tMESSAGE_DELETED: \"agent-message-deleted\",\n\tMESSAGE_STDOUT: \"agent-message-stdout\",\n\tMESSAGE_STDIN: \"agent-message-stdin\",\n\tERROR: \"agent-error\"\n};\nconst AGENT_TYPES = {\n\tCLAUDE_CODE: \"claude-code\",\n\tGEMINI_CLI: \"gemini-cli\"\n};\nconst AGENT_STATUS = {\n\tSTARTING: \"starting\",\n\tIDLE: \"idle\",\n\tPAUSED: \"paused\",\n\tSTOPPED: \"stopped\",\n\tERROR: \"error\"\n};\nconst OUTPUT_STREAMS = {\n\tSTDOUT: \"stdout\",\n\tSTDERR: \"stderr\"\n};\n\n//#endregion\nexport { AGENT_EVENT_TYPES, AGENT_STATUS, AGENT_TYPES, OUTPUT_STREAMS };\n//# sourceMappingURL=agentSession.mjs.map","//#region src/constants/daemon.ts\n/**\n* Daemon Event Constants\n*\n* Standardized constants for daemon-related events.\n* These define event types, status values, and command actions.\n*/\nconst DAEMON_EVENT_TYPES = {\n\tSTATUS: \"daemon-status\",\n\tERROR: \"daemon-error\",\n\tTERMINATE: \"daemon-terminate\",\n\tLIST: \"daemon-list-agent-sessions\",\n\tSTART_AGENT: \"daemon-start-agent\",\n\tSTOP_AGENT: \"daemon-stop-agent\"\n};\nconst DAEMON_STATUS = {\n\tSTARTING: \"starting\",\n\tIDLE: \"idle\",\n\tBUSY: \"busy\",\n\tOFFLINE: \"offline\"\n};\nconst SESSION_LIST_DATA = \"Session list\";\n\n//#endregion\nexport { DAEMON_EVENT_TYPES, DAEMON_STATUS, SESSION_LIST_DATA };\n//# sourceMappingURL=daemon.mjs.map","//#region src/constants/shared.ts\n/**\n* Shared Event Constants\n*\n* Standardized constants for shared event communication patterns.\n* These define command types for request/response interactions.\n*/\nconst COMMANDS = {\n\tREQUEST: \"request\",\n\tRESPONSE: \"response\",\n\tACK: \"ack\"\n};\n\n//#endregion\nexport { COMMANDS };\n//# sourceMappingURL=shared.mjs.map","import { AGENT_EVENT_TYPES, AGENT_STATUS, AGENT_TYPES, OUTPUT_STREAMS } from \"../constants/agentSession.mjs\";\nimport { COMMANDS } from \"../constants/shared.mjs\";\nimport { z } from \"zod\";\n\n//#region src/schemas/agentSession.ts\n/**\n* Agent Session Event Schemas\n*\n* Standardized Zod schemas for agent session-related events.\n* These handle agent status updates, message input/output, and error handling.\n*/\nconst BaseAgentSessionEventSchema = z.object({\n\teventType: z.string(),\n\tcommand: z.string(),\n\tpayload: z.object({\n\t\tsessionId: z.string(),\n\t\ttimestamp: z.number().default(() => Date.now())\n\t})\n});\nconst AgentStatusSchema = z.enum([\n\tAGENT_STATUS.STARTING,\n\tAGENT_STATUS.IDLE,\n\tAGENT_STATUS.PAUSED,\n\tAGENT_STATUS.STOPPED,\n\tAGENT_STATUS.ERROR\n]);\nconst AgentTypeSchema = z.enum([AGENT_TYPES.CLAUDE_CODE, AGENT_TYPES.GEMINI_CLI]);\nconst OutputStreamSchema = z.enum([OUTPUT_STREAMS.STDOUT, OUTPUT_STREAMS.STDERR]);\nconst AgentSessionStatusRequestEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.STATUS).default(AGENT_EVENT_TYPES.STATUS),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tfullscreen: z.boolean().default(false).optional()\n\t})\n});\nconst AgentSessionResizeRequestEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.RESIZE).default(AGENT_EVENT_TYPES.RESIZE),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tcols: z.coerce.number(),\n\t\trows: z.coerce.number()\n\t})\n});\nconst AgentSessionDirectControlRequestEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.DIRECT_CONTROL).default(AGENT_EVENT_TYPES.DIRECT_CONTROL),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string(),\n\t\tcontrolType: z.enum([\n\t\t\t\"interrupt\",\n\t\t\t\"cancel\",\n\t\t\t\"eof\",\n\t\t\t\"signal\"\n\t\t]).default(\"interrupt\"),\n\t\tmetadata: z.record(z.string(), z.any()).optional()\n\t})\n});\nconst AgentSessionStatusResponseEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.STATUS).default(AGENT_EVENT_TYPES.STATUS),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tstatus: AgentStatusSchema.default(AGENT_STATUS.IDLE),\n\t\tagentType: AgentTypeSchema.optional(),\n\t\tpid: z.number().optional(),\n\t\tversion: z.string().optional(),\n\t\tcapabilities: z.string().array().optional(),\n\t\tmessage: z.string().optional()\n\t})\n});\nconst AgentSessionMessageInputRequestEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_INPUT).default(AGENT_EVENT_TYPES.MESSAGE_INPUT),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.coerce.string(),\n\t\tmessageId: z.string(),\n\t\tcontent: z.coerce.string(),\n\t\tpreCommands: z.array(z.string()).optional(),\n\t\tmetadata: z.record(z.string(), z.any()).optional()\n\t})\n});\nconst AgentSessionMessageInputResponseEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_INPUT).default(AGENT_EVENT_TYPES.MESSAGE_INPUT),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tid: z.string(),\n\t\tsessionId: z.string(),\n\t\tmemberId: z.string().nullable().optional(),\n\t\tmessageType: z.enum([\n\t\t\t\"input\",\n\t\t\t\"output\",\n\t\t\t\"error\",\n\t\t\t\"system\"\n\t\t]),\n\t\tcontent: z.string(),\n\t\tcontentSize: z.number().nullable(),\n\t\tmessageTimestamp: z.string(),\n\t\tmetadata: z.any().nullable(),\n\t\tcreatedAt: z.string(),\n\t\tupdatedAt: z.string()\n\t})\n});\nconst AgentSessionMessageOutputRequestEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_OUTPUT).default(AGENT_EVENT_TYPES.MESSAGE_OUTPUT),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({ data: z.string().default(\"\") })\n});\nconst AgentSessionMessageOutputResponseEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_OUTPUT).default(AGENT_EVENT_TYPES.MESSAGE_OUTPUT),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tid: z.string(),\n\t\tmessageId: z.string(),\n\t\tmemberId: z.string().nullable().optional(),\n\t\tmessageType: z.enum([\n\t\t\t\"input\",\n\t\t\t\"output\",\n\t\t\t\"error\",\n\t\t\t\"system\"\n\t\t]),\n\t\tparts: z.array(z.unknown()).default([]),\n\t\tcontentSize: z.number().nullable(),\n\t\tmessageTimestamp: z.string(),\n\t\tstream: OutputStreamSchema.optional(),\n\t\tisComplete: z.boolean().optional().default(false),\n\t\tmetadata: z.any().nullable(),\n\t\tcreatedAt: z.string(),\n\t\tupdatedAt: z.string()\n\t})\n});\nconst AgentSessionMessageOutputPermissionRequestedEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_OUTPUT_PERMISSION_REQUESTED).default(AGENT_EVENT_TYPES.MESSAGE_OUTPUT_PERMISSION_REQUESTED),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tmessageId: z.string(),\n\t\ttoolName: z.string(),\n\t\tdescription: z.string(),\n\t\tmetadata: z.record(z.string(), z.any()).optional()\n\t})\n});\nconst AgentSessionMessageStdinRequestEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_STDIN).default(AGENT_EVENT_TYPES.MESSAGE_STDIN),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({ data: z.string().default(\"\") })\n});\nconst AgentSessionMessageStdoutResponseEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_STDOUT).default(AGENT_EVENT_TYPES.MESSAGE_STDOUT),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({ data: z.string().default(\"\") })\n});\nconst AgentSessionMessageOutputStartedEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_OUTPUT_STARTED).default(AGENT_EVENT_TYPES.MESSAGE_OUTPUT_STARTED),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tid: z.string(),\n\t\tmessageId: z.string(),\n\t\tmemberId: z.string().nullable().optional(),\n\t\tmessageType: z.enum([\n\t\t\t\"input\",\n\t\t\t\"output\",\n\t\t\t\"error\",\n\t\t\t\"system\"\n\t\t]),\n\t\tparts: z.array(z.unknown()).default([]),\n\t\tcontentSize: z.number().nullable(),\n\t\tmessageTimestamp: z.string(),\n\t\tmetadata: z.any().nullable(),\n\t\tcreatedAt: z.string(),\n\t\tupdatedAt: z.string()\n\t})\n});\nconst AgentSessionMessageOutputEndedEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_OUTPUT_ENDED).default(AGENT_EVENT_TYPES.MESSAGE_OUTPUT_ENDED),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tid: z.string(),\n\t\tmessageId: z.string(),\n\t\tmemberId: z.string().nullable().optional(),\n\t\tmessageType: z.enum([\n\t\t\t\"input\",\n\t\t\t\"output\",\n\t\t\t\"error\",\n\t\t\t\"system\"\n\t\t]),\n\t\tparts: z.array(z.unknown()),\n\t\tcontentSize: z.number().nullable(),\n\t\tmessageTimestamp: z.string(),\n\t\ttotalTokens: z.number().optional(),\n\t\tcompletionTime: z.number().optional(),\n\t\tmetadata: z.any().nullable(),\n\t\tcreatedAt: z.string(),\n\t\tupdatedAt: z.string()\n\t})\n});\nconst AgentSessionMessageDeletedEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_DELETED).default(AGENT_EVENT_TYPES.MESSAGE_DELETED),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tid: z.string()\n\t})\n});\nconst AgentSessionErrorRequestEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.ERROR).default(AGENT_EVENT_TYPES.ERROR),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({ data: z.string().default(\"\") })\n});\nconst AgentSessionErrorResponseEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.ERROR).default(AGENT_EVENT_TYPES.ERROR),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\terror: z.object({\n\t\t\tcode: z.string().default(\"UNKNOWN_ERROR\"),\n\t\t\tmessage: z.string().default(\"An unknown error occurred\"),\n\t\t\tdetails: z.any().optional(),\n\t\t\tstack: z.string().optional()\n\t\t})\n\t})\n});\nconst AgentSessionStatusAckEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.STATUS).default(AGENT_EVENT_TYPES.STATUS),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tagentSessionsSent: z.number().default(0)\n\t})\n});\nconst AgentSessionMessageInputAckEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_INPUT).default(AGENT_EVENT_TYPES.MESSAGE_INPUT),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tmessageId: z.string(),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tagentSessionsSent: z.number().default(0)\n\t})\n});\nconst AgentSessionMessageOutputAckEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_OUTPUT).default(AGENT_EVENT_TYPES.MESSAGE_OUTPUT),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tmessageId: z.string(),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tagentSessionsSent: z.number().default(0)\n\t})\n});\nconst AgentSessionMessageDeletedAckEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.MESSAGE_DELETED).default(AGENT_EVENT_TYPES.MESSAGE_DELETED),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tid: z.string(),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tagentSessionsSent: z.number().default(0)\n\t})\n});\nconst AgentSessionErrorAckEventSchema = BaseAgentSessionEventSchema.extend({\n\teventType: z.literal(AGENT_EVENT_TYPES.ERROR).default(AGENT_EVENT_TYPES.ERROR),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseAgentSessionEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tagentSessionsSent: z.number().default(0)\n\t})\n});\nconst AgentSessionEventSchema = z.union([\n\tAgentSessionStatusRequestEventSchema,\n\tAgentSessionResizeRequestEventSchema,\n\tAgentSessionDirectControlRequestEventSchema,\n\tAgentSessionStatusResponseEventSchema,\n\tAgentSessionMessageInputRequestEventSchema,\n\tAgentSessionMessageInputResponseEventSchema,\n\tAgentSessionMessageOutputRequestEventSchema,\n\tAgentSessionMessageOutputResponseEventSchema,\n\tAgentSessionMessageOutputPermissionRequestedEventSchema,\n\tAgentSessionMessageStdinRequestEventSchema,\n\tAgentSessionMessageStdoutResponseEventSchema,\n\tAgentSessionMessageOutputStartedEventSchema,\n\tAgentSessionMessageOutputEndedEventSchema,\n\tAgentSessionMessageDeletedEventSchema,\n\tAgentSessionErrorRequestEventSchema,\n\tAgentSessionErrorResponseEventSchema,\n\tAgentSessionStatusAckEventSchema,\n\tAgentSessionMessageInputAckEventSchema,\n\tAgentSessionMessageOutputAckEventSchema,\n\tAgentSessionMessageDeletedAckEventSchema,\n\tAgentSessionErrorAckEventSchema\n]);\n\n//#endregion\nexport { AgentSessionDirectControlRequestEventSchema, AgentSessionErrorAckEventSchema, AgentSessionErrorRequestEventSchema, AgentSessionErrorResponseEventSchema, AgentSessionEventSchema, AgentSessionMessageDeletedAckEventSchema, AgentSessionMessageDeletedEventSchema, AgentSessionMessageInputAckEventSchema, AgentSessionMessageInputRequestEventSchema, AgentSessionMessageInputResponseEventSchema, AgentSessionMessageOutputAckEventSchema, AgentSessionMessageOutputEndedEventSchema, AgentSessionMessageOutputPermissionRequestedEventSchema, AgentSessionMessageOutputRequestEventSchema, AgentSessionMessageOutputResponseEventSchema, AgentSessionMessageOutputStartedEventSchema, AgentSessionMessageStdinRequestEventSchema, AgentSessionMessageStdoutResponseEventSchema, AgentSessionResizeRequestEventSchema, AgentSessionStatusAckEventSchema, AgentSessionStatusRequestEventSchema, AgentSessionStatusResponseEventSchema, AgentStatusSchema, AgentTypeSchema, BaseAgentSessionEventSchema, OutputStreamSchema };\n//# sourceMappingURL=agentSession.mjs.map","import { DAEMON_EVENT_TYPES, DAEMON_STATUS } from \"../constants/daemon.mjs\";\nimport { COMMANDS } from \"../constants/shared.mjs\";\nimport { z } from \"zod\";\n\n//#region src/schemas/daemon.ts\n/**\n* Daemon Event Schemas\n*\n* Standardized Zod schemas for daemon-related events.\n* These handle daemon registration, status updates, and core daemon functionality.\n*/\nconst BaseDaemonEventSchema = z.object({\n\teventType: z.string(),\n\tcommand: z.string(),\n\tpayload: z.object({\n\t\tsessionId: z.string(),\n\t\ttimestamp: z.number().default(() => Date.now())\n\t})\n});\nconst DaemonStatusSchema = z.enum([\n\tDAEMON_STATUS.IDLE,\n\tDAEMON_STATUS.BUSY,\n\tDAEMON_STATUS.OFFLINE,\n\tDAEMON_STATUS.STARTING\n]);\nconst DaemonStatusRequestEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.STATUS).default(DAEMON_EVENT_TYPES.STATUS),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({ data: z.string().default(\"\") })\n});\nconst DaemonStatusResponseEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.STATUS).default(DAEMON_EVENT_TYPES.STATUS),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tstatus: DaemonStatusSchema.default(DAEMON_STATUS.IDLE)\n\t})\n});\nconst DaemonErrorRequestEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.ERROR).default(DAEMON_EVENT_TYPES.ERROR),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({ data: z.string().default(\"\") })\n});\nconst DaemonErrorResponseEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.ERROR).default(DAEMON_EVENT_TYPES.ERROR),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\terror: z.object({\n\t\t\tcode: z.string().default(\"UNKNOWN_ERROR\"),\n\t\t\tmessage: z.string().default(\"An unknown error occurred\"),\n\t\t\tdetails: z.any().optional()\n\t\t})\n\t})\n});\nconst DaemonTerminateRequestEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.TERMINATE).default(DAEMON_EVENT_TYPES.TERMINATE),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({ data: z.string().optional().default(\"\") })\n});\nconst DaemonTerminateResponseEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.TERMINATE).default(DAEMON_EVENT_TYPES.TERMINATE),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({ data: z.string().optional().default(\"\") })\n});\nconst DaemonListAgentSessionsRequestEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.LIST).default(DAEMON_EVENT_TYPES.LIST),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({ data: z.string().optional().default(\"\") })\n});\nconst DaemonListAgentSessionsResponseEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.LIST).default(DAEMON_EVENT_TYPES.LIST),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({ data: z.string().optional().default(\"\") })\n});\nconst DaemonStartAgentRequestEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.START_AGENT).default(DAEMON_EVENT_TYPES.START_AGENT),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tagentType: z.string(),\n\t\tagentSessionId: z.string(),\n\t\tagentConfig: z.object({\n\t\t\tconversationSessionId: z.string().optional(),\n\t\t\tworkingDirectory: z.string().nullable(),\n\t\t\tenvironment: z.record(z.string(), z.string()).optional(),\n\t\t\targs: z.string().array().optional(),\n\t\t\tcommands: z.string().array().optional(),\n\t\t\tmcps: z.any().optional(),\n\t\t\thooks: z.any().optional(),\n\t\t\txterm: z.boolean().optional().default(false),\n\t\t\tdocker: z.boolean().optional().default(false),\n\t\t\tdockerImage: z.string().optional(),\n\t\t\tautonomous: z.boolean().optional().default(false),\n\t\t\tworktree: z.union([z.boolean(), z.object({\n\t\t\t\tbranch: z.string().optional(),\n\t\t\t\tname: z.string().optional()\n\t\t\t})]).optional().default(false),\n\t\t\tsessionAlias: z.string().optional(),\n\t\t\tllmConfig: z.object({\n\t\t\t\tprovider: z.string(),\n\t\t\t\tmodel: z.string().optional(),\n\t\t\t\tapiKey: z.string().optional(),\n\t\t\t\tendpoint: z.string().optional()\n\t\t\t}).optional()\n\t\t}).optional()\n\t})\n});\nconst DaemonStartAgentResponseEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.START_AGENT).default(DAEMON_EVENT_TYPES.START_AGENT),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tagentSessionId: z.string(),\n\t\tagentType: z.string(),\n\t\tstatus: z.enum([\"started\", \"failed\"]).default(\"started\"),\n\t\tmessage: z.string().optional()\n\t})\n});\nconst DaemonStartAgentAckEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.START_AGENT).default(DAEMON_EVENT_TYPES.START_AGENT),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tagentType: z.string(),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tdaemonsSent: z.number().default(0)\n\t})\n});\nconst DaemonStopAgentRequestEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.STOP_AGENT).default(DAEMON_EVENT_TYPES.STOP_AGENT),\n\tcommand: z.literal(COMMANDS.REQUEST).default(COMMANDS.REQUEST),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tagentSessionId: z.string()\n\t})\n});\nconst DaemonStopAgentResponseEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.STOP_AGENT).default(DAEMON_EVENT_TYPES.STOP_AGENT),\n\tcommand: z.literal(COMMANDS.RESPONSE).default(COMMANDS.RESPONSE),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tagentSessionId: z.string(),\n\t\tstatus: z.enum([\n\t\t\t\"stopped\",\n\t\t\t\"not_found\",\n\t\t\t\"failed\"\n\t\t]).default(\"stopped\"),\n\t\tmessage: z.string().optional()\n\t})\n});\nconst DaemonStopAgentAckEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.STOP_AGENT).default(DAEMON_EVENT_TYPES.STOP_AGENT),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tdaemonsSent: z.number().default(0)\n\t})\n});\nconst DaemonTerminateAckEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.TERMINATE).default(DAEMON_EVENT_TYPES.TERMINATE),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tdaemonsSent: z.number().default(0)\n\t})\n});\nconst DaemonListAgentSessionsAckEventSchema = BaseDaemonEventSchema.extend({\n\teventType: z.literal(DAEMON_EVENT_TYPES.LIST).default(DAEMON_EVENT_TYPES.LIST),\n\tcommand: z.literal(COMMANDS.ACK).default(COMMANDS.ACK),\n\tpayload: BaseDaemonEventSchema.shape.payload.extend({\n\t\tdata: z.string().default(\"\"),\n\t\tstatus: z.enum([\"forwarded\", \"failed\"]).default(\"forwarded\"),\n\t\tmessage: z.string(),\n\t\tdaemonsSent: z.number().default(0)\n\t})\n});\nconst DaemonEventSchema = z.union([\n\tDaemonStatusRequestEventSchema,\n\tDaemonStatusResponseEventSchema,\n\tDaemonErrorRequestEventSchema,\n\tDaemonErrorResponseEventSchema,\n\tDaemonTerminateRequestEventSchema,\n\tDaemonTerminateResponseEventSchema,\n\tDaemonListAgentSessionsRequestEventSchema,\n\tDaemonListAgentSessionsResponseEventSchema,\n\tDaemonStartAgentRequestEventSchema,\n\tDaemonStartAgentResponseEventSchema,\n\tDaemonStartAgentAckEventSchema,\n\tDaemonStopAgentRequestEventSchema,\n\tDaemonStopAgentResponseEventSchema,\n\tDaemonStopAgentAckEventSchema,\n\tDaemonTerminateAckEventSchema,\n\tDaemonListAgentSessionsAckEventSchema\n]);\n\n//#endregion\nexport { BaseDaemonEventSchema, DaemonErrorRequestEventSchema, DaemonErrorResponseEventSchema, DaemonEventSchema, DaemonListAgentSessionsAckEventSchema, DaemonListAgentSessionsRequestEventSchema, DaemonListAgentSessionsResponseEventSchema, DaemonStartAgentAckEventSchema, DaemonStartAgentRequestEventSchema, DaemonStartAgentResponseEventSchema, DaemonStatusRequestEventSchema, DaemonStatusResponseEventSchema, DaemonStatusSchema, DaemonStopAgentAckEventSchema, DaemonStopAgentRequestEventSchema, DaemonStopAgentResponseEventSchema, DaemonTerminateAckEventSchema, DaemonTerminateRequestEventSchema, DaemonTerminateResponseEventSchema };\n//# sourceMappingURL=daemon.mjs.map","import z from 'zod';\n\n/**\n * Environment configuration schema for agent-cli\n *\n * This schema defines the environment variables used by the agent CLI.\n * All variables are optional with sensible defaults provided in the code.\n */\nconst ConfigSchema = z.object({\n VITE_INJECT_AGIFLOW_APP_ENDPOINT: z\n .string()\n .default('')\n .transform((val) => val.trim() || undefined)\n .pipe(z.string().url().optional())\n .describe(\n 'Server base URL for both HTTP API and WebSocket connections (optional - leave empty for standalone mode)',\n ),\n VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT: z\n .string()\n .default('')\n .transform((val) => val.trim() || undefined)\n .pipe(z.string().url().optional())\n .describe('Server base URL when running inside Docker containers (optional)'),\n VITE_AGENT_CLI_DOCKER_IMAGE: z\n .string()\n .default('')\n .describe('Docker image name for containerized Claude Code agents'),\n VITE_AGENT_CLI_DOCKER_NETWORK: z.string().default('').describe('Docker network mode for containerized agents'),\n VITE_SAVE_RAW: z\n .preprocess((val) => {\n if (val === 'false' || val === '' || val === null || val === undefined) return false;\n if (val === 'true') return true;\n return val;\n }, z.boolean().optional())\n .default(false),\n});\n\nexport { ConfigSchema };\n","import dotenv from 'dotenv';\nimport z from 'zod';\nimport { ConfigSchema } from './envSchema';\n\n// Load environment variables from .env file\ndotenv.config({ override: false, debug: false });\n\nexport { ConfigSchema };\nexport type Env = z.infer<typeof ConfigSchema>;\nexport type EnvKey = keyof Env;\n\n// Parse and export the configuration\nexport const config = ConfigSchema.parse({\n VITE_INJECT_AGIFLOW_APP_ENDPOINT: process.env.VITE_INJECT_AGIFLOW_APP_ENDPOINT,\n VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT: process.env.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT,\n VITE_AGENT_CLI_DOCKER_IMAGE: process.env.VITE_AGENT_CLI_DOCKER_IMAGE,\n VITE_AGENT_CLI_DOCKER_NETWORK: process.env.VITE_AGENT_CLI_DOCKER_NETWORK,\n});\n\n/**\n * Get the appropriate server URL based on the environment\n * @param forceDocker - Force Docker URL regardless of environment\n * @returns Server base URL (http/https) or undefined if not configured\n */\nexport function getServerUrl(forceDocker = false): string | undefined {\n const isInDocker = process.env.AGENT_CONTAINER_MODE === 'true' || forceDocker;\n return isInDocker ? config.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT : config.VITE_INJECT_AGIFLOW_APP_ENDPOINT;\n}\n\n/**\n * Get WebSocket URL from HTTP URL\n * @param httpUrl - HTTP base URL\n * @returns WebSocket URL (ws/wss)\n */\nexport function getWebSocketUrl(httpUrl: string): string {\n const url = new URL(httpUrl);\n url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';\n return url.toString();\n}\n","import * as crypto from 'node:crypto';\nimport * as os from 'node:os';\n\n/**\n * Platform utilities for device identification and system information\n */\n\n/**\n * Generate a device ID for daemon identification\n * @param stable - Whether to generate a stable device ID (default: true)\n * @param workDir - Working directory to use for stable ID generation (default: process.cwd())\n * @returns Device ID string\n */\nexport function generateDeviceId(stable = true, workDir?: string): string {\n const hostname = os.hostname();\n const safeHost = hostname.replace(/[^a-zA-Z0-9-]/g, '-');\n\n if (stable) {\n const dir = workDir || process.cwd();\n // Create a stable hash from the working directory\n const hash = crypto\n .createHash('sha256')\n .update(dir)\n .digest('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '')\n .slice(0, 8);\n\n return `claude-daemon-${safeHost}-${hash}`;\n }\n\n // Non-stable ID includes timestamp\n return `claude-daemon-${safeHost}-${Date.now()}`;\n}\n\n/**\n * Get system information for daemon registration\n */\nexport function getSystemInfo() {\n return {\n hostname: os.hostname(),\n platform: os.platform(),\n arch: os.arch(),\n release: os.release(),\n cpus: os.cpus().length,\n totalMemory: os.totalmem(),\n type: os.type(),\n };\n}\n\n/**\n * Format WebSocket URL from HTTP URL\n * @param httpUrl - HTTP URL to convert\n * @returns WebSocket URL\n */\nexport function httpToWebSocket(httpUrl: string): string {\n return httpUrl.replace(/^http/, 'ws');\n}\n\n/**\n * Format HTTP URL from WebSocket URL\n * @param wsUrl - WebSocket URL to convert\n * @param defaultPort - Default port if not specified (default: 3000)\n * @returns HTTP URL\n */\nexport function webSocketToHttp(wsUrl: string, defaultPort = 3000): string {\n return wsUrl.replace(/^ws/, 'http').replace(/:\\d+$/, `:${defaultPort}`);\n}\n\n/**\n * Create a heartbeat interval\n * @param callback - Callback function to execute on each heartbeat\n * @param interval - Interval in milliseconds (default: 5 minutes)\n * @param logger - Optional logger for error messages\n * @returns Object with start and stop methods\n */\nexport function createHeartbeat(\n callback: () => Promise<void>,\n interval = 300000,\n logger?: any,\n): { start: () => void; stop: () => void } {\n let timer: NodeJS.Timeout | null = null;\n const log = logger || console;\n\n const start = () => {\n stop(); // Clear any existing timer\n\n // Execute immediately\n callback().catch((e) => {\n log.warn?.('Heartbeat failed:', e) || console.warn('Heartbeat failed:', e);\n });\n\n // Then set up interval\n timer = setInterval(async () => {\n try {\n await callback();\n } catch (e) {\n log.warn?.('Heartbeat failed:', e) || console.warn('Heartbeat failed:', e);\n }\n }, interval);\n };\n\n const stop = () => {\n if (timer) {\n clearInterval(timer);\n timer = null;\n }\n };\n\n return { start, stop };\n}\n","/**\n * Agent WebSocket Service\n *\n * Manages WebSocket connections for agent sessions, handling:\n * - Connection establishment and authentication\n * - Message routing and validation\n * - Automatic reconnection\n * - Event callbacks\n */\n\nimport {\n AGENT_EVENT_TYPES,\n AGENT_STATUS,\n type AgentSessionDirectControlRequestEvent,\n AgentSessionDirectControlRequestEventSchema,\n type AgentSessionErrorResponseEvent,\n AgentSessionErrorResponseEventSchema,\n type AgentSessionMessageInputRequestEvent,\n AgentSessionMessageInputRequestEventSchema,\n type AgentSessionMessageOutputResponseEvent,\n AgentSessionMessageOutputResponseEventSchema,\n type AgentSessionMessageStdinRequestEvent,\n AgentSessionMessageStdinRequestEventSchema,\n type AgentSessionMessageStdoutResponseEvent,\n AgentSessionMessageStdoutResponseEventSchema,\n type AgentSessionResizeRequestEvent,\n AgentSessionResizeRequestEventSchema,\n type AgentSessionStatusRequestEvent,\n AgentSessionStatusRequestEventSchema,\n type AgentSessionStatusResponseEvent,\n AgentSessionStatusResponseEventSchema,\n COMMANDS,\n OUTPUT_STREAMS,\n} from '@agimonai/universal-agent-events';\nimport WebSocket from 'ws';\nimport { SubEnvManager } from '../config/subenv';\nimport { Logger } from '../utils/logger';\nimport { CredentialsService } from './CredentialsService';\n\nexport interface AgentWsOptions {\n serverUrl: string;\n apiKey?: string;\n verbose?: boolean;\n deviceGuid?: string;\n organizationId?: string;\n reconnectInterval?: number;\n credentialsService?: CredentialsService;\n logger?: Logger;\n}\n\nexport interface AgentWsCallbacks {\n onStatusRequest?: (message: AgentSessionStatusRequestEvent) => Promise<void>;\n onMessageInput?: (message: AgentSessionMessageInputRequestEvent) => Promise<void>;\n onStdinInput?: (message: AgentSessionMessageStdinRequestEvent) => Promise<void>;\n onResizeRequest?: (message: AgentSessionResizeRequestEvent) => Promise<void>;\n onDirectControl?: (message: AgentSessionDirectControlRequestEvent) => Promise<void>;\n onConnect?: () => void;\n onDisconnect?: (code: number, reason: string) => void;\n onError?: (error: Error) => void;\n onMessage?: (message: any) => Promise<void>;\n}\n\nexport class AgentWsService {\n private ws: WebSocket | null = null;\n private options: AgentWsOptions;\n private callbacks: AgentWsCallbacks;\n private isConnected = false;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private shouldReconnect = true;\n private currentSessionId: string | null = null;\n private credentialsService: CredentialsService;\n private logger: Logger;\n\n // Connection health monitoring\n private pingInterval: NodeJS.Timeout | null = null;\n private connectionAttempts = 0;\n private maxReconnectAttempts = 10; // Increased for Docker reliability\n\n // Agent session heartbeat\n private heartbeatInterval: NodeJS.Timeout | null = null;\n\n constructor(options: AgentWsOptions, callbacks: AgentWsCallbacks = {}) {\n // Use shorter reconnect interval for Docker environments to handle connectivity issues\n const defaultReconnectInterval = SubEnvManager.isContainerMode ? 2000 : 5000; // 2s for Docker, 5s for host\n\n this.options = { reconnectInterval: defaultReconnectInterval, ...options };\n this.callbacks = callbacks;\n this.credentialsService = options.credentialsService ?? new CredentialsService();\n this.logger = options.logger ?? new Logger({ verbose: options.verbose ?? false });\n\n if (SubEnvManager.isContainerMode) {\n this.logger.debug('🐳 Docker WebSocket service initialized with enhanced connectivity handling');\n }\n }\n\n /**\n * Connect to agent session WebSocket\n */\n async connect(sessionId: string): Promise<void> {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n return;\n }\n\n this.currentSessionId = sessionId;\n const wsUrl = await this.buildWebSocketUrl(sessionId);\n\n // Enhanced logging for Docker environments\n if (SubEnvManager.isContainerMode) {\n this.logger.info(`🐳 Docker WebSocket connecting to: ${wsUrl}`);\n this.logger.debug('Docker network environment:', {\n hostname: SubEnvManager.hostname,\n containerMode: SubEnvManager.isContainerMode,\n serverUrl: this.options.serverUrl,\n });\n }\n\n return new Promise((resolve, reject) => {\n const headers: Record<string, string> = {};\n\n // Add API key header for authentication\n if (this.options.apiKey) {\n headers['x-api-key'] = this.options.apiKey;\n }\n\n this.ws = new WebSocket(wsUrl, { headers });\n\n this.ws.on('open', () => {\n this.isConnected = true;\n this.connectionAttempts = 0; // Reset attempts on successful connection\n\n // Use local logger reference to avoid scope issues\n const logger = this.logger;\n if (logger) {\n if (SubEnvManager.isContainerMode) {\n logger.info(`🐳 Docker WebSocket connected successfully to ${wsUrl}`);\n } else {\n logger.info(`🔌 WebSocket connected to ${wsUrl}`);\n }\n }\n\n // Start connection health monitoring for Docker environments\n if (SubEnvManager.isContainerMode) {\n this.startHealthMonitoring();\n }\n\n // Start agent session heartbeat\n this.startAgentHeartbeat();\n\n // Call onConnect callback\n if (this.callbacks.onConnect) {\n this.callbacks.onConnect();\n }\n\n resolve();\n });\n\n this.ws.on('message', (data) => {\n try {\n const rawMessage = JSON.parse(data.toString());\n this.handleMessage(rawMessage);\n } catch (error) {\n this.log(`Error parsing message: ${error}`);\n }\n });\n\n this.ws.on('close', (code, reason) => {\n this.isConnected = false;\n this.currentSessionId = null;\n\n // Call onDisconnect callback\n if (this.callbacks.onDisconnect) {\n this.callbacks.onDisconnect(code, reason.toString());\n }\n\n if (this.shouldReconnect) {\n this.scheduleReconnect(sessionId);\n }\n });\n\n this.ws.on('error', (error) => {\n // Enhanced error logging for Docker environments\n if (SubEnvManager.isContainerMode) {\n this.logger.error(\n '🐳 Docker WebSocket connection error:',\n new Error(\n `Docker WebSocket error: ${error.message}. URL: ${wsUrl}, Hostname: ${SubEnvManager.hostname}, Server: ${this.options.serverUrl}`,\n ),\n );\n }\n\n // Check if it's an authentication error\n if (error.message.includes('401')) {\n if (this.options.apiKey) {\n this.log(`API key first 8 chars: ${this.options.apiKey.substring(0, 8)}...`);\n }\n }\n\n // Check for common Docker networking errors\n if (error.message.includes('ECONNREFUSED') || error.message.includes('ENOTFOUND')) {\n this.logger.error('🐳 Docker networking issue - check if server is accessible from container');\n }\n\n // Call onError callback\n if (this.callbacks.onError) {\n this.callbacks.onError(error);\n }\n\n if (!this.isConnected) {\n reject(error);\n }\n });\n\n // Connection timeout\n setTimeout(() => {\n if (!this.isConnected) {\n reject(new Error('WebSocket connection timeout'));\n }\n }, 10000);\n });\n }\n\n /**\n * Disconnect from WebSocket\n */\n disconnect(): void {\n this.shouldReconnect = false;\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n // Stop health monitoring\n this.stopHealthMonitoring();\n\n // Stop agent heartbeat\n this.stopAgentHeartbeat();\n\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n\n this.isConnected = false;\n }\n\n /**\n * Check if WebSocket is connected\n */\n isWebSocketConnected(): boolean {\n return this.isConnected;\n }\n\n /**\n * Get current session ID\n */\n getCurrentSessionId(): string {\n if (!this.currentSessionId) {\n throw new Error('No active session ID');\n }\n return this.currentSessionId;\n }\n\n /**\n * Set current session ID\n */\n setCurrentSessionId(sessionId: string): void {\n this.currentSessionId = sessionId;\n }\n\n /**\n * Send agent status message\n */\n sendAgentStatus(payload: {\n agentType?: any;\n status?: (typeof AGENT_STATUS)[keyof typeof AGENT_STATUS];\n pid?: number;\n version?: string;\n capabilities?: string[];\n message?: string;\n }): void {\n const message: AgentSessionStatusResponseEvent = {\n eventType: AGENT_EVENT_TYPES.STATUS,\n command: COMMANDS.RESPONSE,\n payload: {\n sessionId: this.getCurrentSessionId(),\n timestamp: Date.now(),\n data: '',\n status: payload.status || AGENT_STATUS.IDLE,\n agentType: payload.agentType,\n pid: payload.pid,\n version: payload.version,\n capabilities: payload.capabilities,\n message: payload.message,\n },\n };\n\n this.sendMessage(AgentSessionStatusResponseEventSchema.parse(message));\n }\n\n /**\n * Send agent output message\n */\n sendAgentOutput(payload: {\n messageId: string;\n content: string;\n stream?: (typeof OUTPUT_STREAMS)[keyof typeof OUTPUT_STREAMS];\n isComplete?: boolean;\n metadata?: Record<string, any>;\n }): void {\n const now = new Date().toISOString();\n const message: AgentSessionMessageOutputResponseEvent = {\n eventType: AGENT_EVENT_TYPES.MESSAGE_OUTPUT,\n command: COMMANDS.RESPONSE,\n payload: {\n sessionId: this.getCurrentSessionId(),\n timestamp: Date.now(),\n data: payload.content,\n id: payload.messageId, // Database ID (same as messageId for consistency)\n messageId: payload.messageId,\n messageType: 'output' as const,\n parts: [],\n contentSize: payload.content.length,\n messageTimestamp: now,\n stream: payload.stream,\n isComplete: payload.isComplete || false,\n metadata: payload.metadata,\n createdAt: now,\n updatedAt: now,\n },\n };\n\n this.sendMessage(AgentSessionMessageOutputResponseEventSchema.parse(message));\n }\n\n /**\n * Send agent error message\n */\n sendAgentError(payload: { code: string; message: string; details?: any; stack?: string }): void {\n const message: AgentSessionErrorResponseEvent = {\n eventType: AGENT_EVENT_TYPES.ERROR,\n command: COMMANDS.RESPONSE,\n payload: {\n sessionId: this.getCurrentSessionId(),\n timestamp: Date.now(),\n data: '',\n error: {\n code: payload.code,\n message: payload.message,\n details: payload.details,\n stack: payload.stack,\n },\n },\n };\n\n this.sendMessage(AgentSessionErrorResponseEventSchema.parse(message));\n }\n\n /**\n * Send stdout message (for terminal output)\n */\n sendStdoutMessage(data: string): void {\n const message: AgentSessionMessageStdoutResponseEvent = {\n eventType: AGENT_EVENT_TYPES.MESSAGE_STDOUT,\n command: COMMANDS.RESPONSE,\n payload: {\n sessionId: this.getCurrentSessionId(),\n timestamp: Date.now(),\n data,\n },\n };\n\n this.sendMessage(AgentSessionMessageStdoutResponseEventSchema.parse(message));\n }\n\n /**\n * Send message through WebSocket\n */\n private sendMessage(message: any): void {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n try {\n this.ws.send(JSON.stringify(message));\n } catch (error) {\n if (SubEnvManager.isContainerMode) {\n this.logger.error('🐳 Docker WebSocket send error:', error as Error);\n this.logger.debug('🐳 Message that failed to send:', message);\n } else {\n this.logger.error('WebSocket send error:', error as Error);\n }\n\n // Try to reconnect if sending fails\n if (this.currentSessionId) {\n this.scheduleReconnect(this.currentSessionId);\n }\n }\n } else {\n const wsState = this.ws ? this.ws.readyState : 'no socket';\n if (SubEnvManager.isContainerMode) {\n this.logger.warn(`🐳 Docker WebSocket not ready to send message. State: ${wsState}`);\n } else {\n this.logger.warn(`WebSocket not ready to send message. State: ${wsState}`);\n }\n }\n }\n\n /**\n * Handle incoming messages from WebSocket\n */\n private handleMessage(rawMessage: any): void {\n try {\n switch (rawMessage.eventType) {\n case AGENT_EVENT_TYPES.STATUS:\n if (rawMessage.command === COMMANDS.REQUEST) {\n const message = AgentSessionStatusRequestEventSchema.parse(rawMessage);\n if (this.callbacks.onStatusRequest) {\n this.callbacks.onStatusRequest(message);\n }\n }\n break;\n case AGENT_EVENT_TYPES.MESSAGE_INPUT:\n if (rawMessage.command === COMMANDS.REQUEST) {\n const message = AgentSessionMessageInputRequestEventSchema.parse(rawMessage);\n if (this.callbacks.onMessageInput) {\n this.callbacks.onMessageInput(message);\n }\n }\n break;\n case AGENT_EVENT_TYPES.MESSAGE_STDIN:\n if (rawMessage.command === COMMANDS.REQUEST) {\n const message = AgentSessionMessageStdinRequestEventSchema.parse(rawMessage);\n if (this.callbacks.onStdinInput) {\n this.callbacks.onStdinInput(message);\n }\n }\n break;\n case AGENT_EVENT_TYPES.RESIZE:\n if (rawMessage.command === COMMANDS.REQUEST) {\n const message = AgentSessionResizeRequestEventSchema.parse(rawMessage);\n // Use local logger reference to avoid scope issues\n const logger = this.logger;\n if (logger) {\n logger.info(`📐 Received resize event: ${message.payload.cols}x${message.payload.rows}`);\n }\n if (this.callbacks.onResizeRequest) {\n this.callbacks.onResizeRequest(message);\n } else if (logger) {\n logger.warn('📐 No onResizeRequest callback registered, ignoring resize event');\n }\n }\n break;\n case AGENT_EVENT_TYPES.DIRECT_CONTROL:\n if (rawMessage.command === COMMANDS.REQUEST) {\n const message = AgentSessionDirectControlRequestEventSchema.parse(rawMessage);\n // Use local logger reference to avoid scope issues\n const logger = this.logger;\n if (logger) {\n logger.info(\n `🎮 Received direct control event: ${message.payload.controlType} - data: ${JSON.stringify(message.payload.data)}`,\n );\n }\n if (this.callbacks.onDirectControl) {\n this.callbacks.onDirectControl(message);\n } else if (logger) {\n logger.warn('🎮 No onDirectControl callback registered, ignoring direct control event');\n }\n }\n break;\n default:\n // Call custom message callback if provided\n if (this.callbacks.onMessage) {\n this.callbacks.onMessage(rawMessage);\n }\n }\n } catch (error) {\n this.log(`Error validating message: ${error}`);\n }\n }\n\n /**\n * Schedule reconnection attempt\n */\n private scheduleReconnect(sessionId: string): void {\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n }\n\n // Increment connection attempts\n this.connectionAttempts++;\n\n // Check if we've exceeded max attempts\n if (this.connectionAttempts > this.maxReconnectAttempts) {\n if (SubEnvManager.isContainerMode) {\n this.logger.error(\n `🐳 Docker WebSocket max reconnection attempts (${this.maxReconnectAttempts}) exceeded. Giving up.`,\n );\n } else {\n this.logger.error(`WebSocket max reconnection attempts (${this.maxReconnectAttempts}) exceeded. Giving up.`);\n }\n return;\n }\n\n // Use exponential backoff for Docker environments\n const baseInterval = this.options.reconnectInterval || 2000;\n const backoffMultiplier = SubEnvManager.isContainerMode ? Math.min(this.connectionAttempts, 5) : 1;\n const reconnectDelay = baseInterval * backoffMultiplier;\n\n if (SubEnvManager.isContainerMode) {\n this.logger.info(\n `🐳 Docker WebSocket reconnection attempt ${this.connectionAttempts}/${this.maxReconnectAttempts} in ${reconnectDelay}ms`,\n );\n }\n\n this.reconnectTimer = setTimeout(async () => {\n try {\n await this.connect(sessionId);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (SubEnvManager.isContainerMode) {\n this.logger.error(`🐳 Docker WebSocket reconnection failed: ${errorMessage}`);\n } else {\n this.log(`Reconnection failed: ${errorMessage}`);\n }\n this.scheduleReconnect(sessionId);\n }\n }, reconnectDelay);\n }\n\n /**\n * Build WebSocket URL for agent session\n */\n private async buildWebSocketUrl(sessionId: string): Promise<string> {\n const url = new URL(this.options.serverUrl);\n\n // Convert HTTP to WebSocket protocol\n if (url.protocol === 'http:') {\n url.protocol = 'ws:';\n } else if (url.protocol === 'https:') {\n url.protocol = 'wss:';\n }\n\n // Build agent session WebSocket path\n url.pathname = `/api/v1/organizations/${this.options.organizationId}/agent-sessions/${sessionId}/ws`;\n url.searchParams.set('clientType', 'agent');\n\n // Use deviceId from credentials service (stored device.id from database)\n const deviceId = await this.credentialsService.getDeviceId();\n url.searchParams.set('deviceId', deviceId || 'unknown');\n\n return url.toString();\n }\n\n /**\n * Start connection health monitoring for Docker environments\n */\n private startHealthMonitoring(): void {\n // Clear existing ping interval\n if (this.pingInterval) {\n clearInterval(this.pingInterval);\n }\n\n // Ping every 30 seconds to detect connection issues early\n this.pingInterval = setInterval(() => {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n // Send a simple ping to keep connection alive\n try {\n // WebSocket ping is usually handled automatically by the protocol\n // but we can send a status request as a keep-alive\n } catch (error) {\n this.logger.warn('🐳 Docker WebSocket ping failed:', error);\n }\n } else {\n this.logger.warn('🐳 Docker WebSocket connection lost during health check');\n this.stopHealthMonitoring();\n if (this.currentSessionId) {\n this.scheduleReconnect(this.currentSessionId);\n }\n }\n }, 30000); // 30 seconds\n }\n\n /**\n * Stop connection health monitoring\n */\n private stopHealthMonitoring(): void {\n if (this.pingInterval) {\n clearInterval(this.pingInterval);\n this.pingInterval = null;\n }\n }\n\n /**\n * Start agent session heartbeat to update lastHeartbeat field\n */\n private startAgentHeartbeat(): void {\n // Clear existing heartbeat interval\n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n }\n\n // Send initial heartbeat immediately\n this.sendHeartbeat();\n\n // Send heartbeat every 30 seconds\n // This is much more frequent than the 3-minute timeout to ensure sessions stay active\n // and aligns with frontend's 30-second stale time\n this.heartbeatInterval = setInterval(() => {\n this.sendHeartbeat();\n }, 30000); // 30 seconds\n }\n\n /**\n * Stop agent session heartbeat\n */\n private stopAgentHeartbeat(): void {\n if (this.heartbeatInterval) {\n clearInterval(this.heartbeatInterval);\n this.heartbeatInterval = null;\n }\n }\n\n /**\n * Send heartbeat status update\n */\n private sendHeartbeat(): void {\n if (this.isConnected && this.currentSessionId) {\n try {\n // Create a proper status response event according to the schema\n const statusEvent: AgentSessionStatusResponseEvent = {\n eventType: AGENT_EVENT_TYPES.STATUS,\n command: COMMANDS.RESPONSE,\n payload: {\n sessionId: this.currentSessionId,\n timestamp: Date.now(),\n data: '',\n status: AGENT_STATUS.IDLE,\n message: 'Heartbeat',\n },\n };\n\n // Validate the event against the schema before sending\n const validatedEvent = AgentSessionStatusResponseEventSchema.parse(statusEvent);\n this.sendMessage(validatedEvent);\n\n this.logger.debug('Agent session heartbeat sent');\n } catch (error) {\n this.logger.warn('Failed to send agent session heartbeat:', error);\n }\n }\n }\n\n /**\n * Logging utility\n */\n private log(message: string): void {\n if (this.options.verbose) {\n console.log(`[AGENT-WS] ${message}`);\n }\n }\n}\n","/**\n * PTY Runner Service\n *\n * Centralized service for managing PTY (pseudo-terminal) processes.\n * Handles spawning, I/O, resizing, and cleanup for interactive CLI tools\n * like Claude Code, Gemini, and other terminal-based agents.\n */\n\nimport * as fs from 'fs';\nimport * as pty from 'node-pty';\nimport { ulid } from 'ulidx';\nimport { ENV_KEYS } from '../config/subenv';\nimport { Logger } from '../utils/logger';\n\nexport interface PtyOptions {\n command: string;\n args?: string[];\n workingDir?: string;\n env?: Record<string, string>;\n cols?: number;\n rows?: number;\n agentSessionId?: string;\n logStream?: fs.WriteStream;\n logger?: Logger;\n // Agent-specific environment variables\n agentApiKey?: string;\n agentOrganizationId?: string;\n agentDeviceGuid?: string;\n agentServerUrl?: string;\n agentType?: string;\n}\n\nexport interface PtyCallbacks {\n onData?: (data: string, cleanContent: string) => void;\n onExit?: (exitCode: number, signal?: number) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface PtySession {\n id: string;\n ptyProcess: pty.IPty;\n command: string;\n workingDir: string;\n status: 'running' | 'stopped' | 'error';\n createdAt: Date;\n lastActivity: Date;\n logStream?: fs.WriteStream;\n metadata?: Record<string, any>;\n}\n\nexport class PtyRunnerService {\n private session!: PtySession;\n private logger: Logger;\n\n constructor(logger?: Logger) {\n this.logger = logger ?? new Logger({ verbose: false });\n }\n\n /**\n * Spawn a new PTY process\n */\n spawn(options: PtyOptions, callbacks?: PtyCallbacks): PtySession {\n const agentSessionId = options.agentSessionId || ulid();\n const workingDir = options.workingDir || process.cwd();\n\n // Build environment with agent-specific variables\n const agentEnv: Record<string, string> = {};\n if (options.agentApiKey) {\n agentEnv[ENV_KEYS.AGENT_API_KEY] = options.agentApiKey;\n }\n if (options.agentOrganizationId) {\n agentEnv[ENV_KEYS.AGENT_ORGANIZATION_ID] = options.agentOrganizationId;\n }\n if (options.agentDeviceGuid) {\n agentEnv[ENV_KEYS.AGENT_DEVICE_GUID] = options.agentDeviceGuid;\n }\n if (options.agentServerUrl) {\n agentEnv[ENV_KEYS.AGENT_SERVER_URL] = options.agentServerUrl;\n }\n if (options.agentType) {\n agentEnv[ENV_KEYS.AGENT_TYPE] = options.agentType;\n }\n // Also set session ID for network logging\n agentEnv[ENV_KEYS.AGENT_SESSION_ID] = agentSessionId;\n\n // Log environment variables being passed to PTY for debugging\n this.logger.debug('PTY Environment Variables:', {\n ...process.env,\n ...agentEnv,\n ...options.env,\n TERM: 'xterm-256color',\n COLORTERM: 'truecolor',\n });\n\n // Spawn the PTY process\n const ptyProcess = pty.spawn(options.command, options.args || [], {\n name: 'xterm-256color',\n cwd: workingDir,\n env: {\n ...process.env,\n ...agentEnv,\n ...options.env,\n TERM: 'xterm-256color',\n COLORTERM: 'truecolor',\n },\n });\n\n // Create session object\n const session: PtySession = {\n id: agentSessionId,\n ptyProcess,\n command: options.command,\n workingDir,\n status: 'running',\n createdAt: new Date(),\n lastActivity: new Date(),\n logStream: options.logStream,\n };\n\n // Handle PTY data\n ptyProcess.onData((data) => {\n session.lastActivity = new Date();\n\n // Log raw data to file if stream provided\n if (session.logStream) {\n session.logStream.write(data);\n }\n\n // Only write to stdout if we're in a terminal (not running as daemon)\n if (process.stdout.isTTY) {\n process.stdout.write(data);\n }\n\n // Always invoke callback with raw data - let the consumer handle deduplication if needed\n if (callbacks?.onData) {\n callbacks.onData(data, data);\n }\n });\n\n // Handle PTY exit\n ptyProcess.onExit((exitInfo) => {\n const exitCode = exitInfo.exitCode;\n const signal = exitInfo.signal;\n\n session.status = exitCode === 0 ? 'stopped' : 'error';\n session.lastActivity = new Date();\n\n this.logger.info(\n `PTY process ${agentSessionId} exited with code ${exitCode}${signal ? ` (signal: ${signal})` : ''}`,\n );\n\n // Close log stream\n if (session.logStream) {\n session.logStream.end();\n }\n\n // Invoke exit callback\n if (callbacks?.onExit) {\n callbacks.onExit(exitCode, signal);\n }\n });\n\n this.session = session;\n\n return session;\n }\n\n /**\n * Send input to a PTY session or Docker container\n */\n sendInput(input: string): boolean {\n if (this.session?.ptyProcess) {\n this.session.ptyProcess.write(input);\n this.session.lastActivity = new Date();\n return true;\n } else {\n this.logger.warn('No active process to send input to');\n return false;\n }\n }\n\n /**\n * Resize a PTY session (Docker containers don't support resize)\n */\n resize(cols: number, rows: number): boolean {\n if (this.session?.ptyProcess) {\n this.session.ptyProcess.resize(cols, rows);\n this.session.lastActivity = new Date();\n return true;\n }\n\n return false;\n }\n\n /**\n * Kill a PTY session\n */\n kill(signal?: NodeJS.Signals): boolean {\n if (!this.session?.ptyProcess) {\n this.logger.warn('No PTY session to kill');\n return false;\n }\n\n try {\n this.session.ptyProcess.kill(signal);\n this.session.status = 'stopped';\n return true;\n } catch (error) {\n this.logger.error(`Failed to kill PTY session : ${error}`);\n return false;\n }\n }\n\n /**\n * Get a PTY session by ID\n */\n getSession(): PtySession | undefined {\n return this.session;\n }\n\n /**\n * Check if a session exists and is running\n */\n isSessionRunning(): boolean {\n return this.session?.status === 'running';\n }\n}\n","import { execSync } from 'child_process';\nimport { existsSync } from 'fs';\nimport { copyFile, mkdir, readdir } from 'fs/promises';\nimport { dirname, join, relative, resolve } from 'path';\nimport { Logger } from '../utils/logger';\n\nexport interface RepoSetupOptions {\n targetDirectory: string;\n originalDirectory?: string;\n logger?: Logger;\n}\n\nexport interface EnvFileInfo {\n originalPath: string;\n targetPath: string;\n relativePath: string;\n copied: boolean;\n}\n\nexport interface SetupResult {\n envFilesCopied: EnvFileInfo[];\n errors: string[];\n}\n\nexport class RepoSetupService {\n private logger: Logger;\n private targetDirectory: string;\n private originalDirectory?: string;\n private envFilePatterns = ['.env', '.env.development', '.dev.vars', '.env.test'];\n\n constructor(options: RepoSetupOptions) {\n this.targetDirectory = resolve(options.targetDirectory);\n this.originalDirectory = options.originalDirectory ? resolve(options.originalDirectory) : undefined;\n this.logger = options.logger ?? new Logger({ verbose: false });\n\n // Validate target directory exists\n if (!existsSync(this.targetDirectory)) {\n throw new Error(`Target directory does not exist: ${this.targetDirectory}`);\n }\n\n // Validate original directory if provided\n if (this.originalDirectory && !existsSync(this.originalDirectory)) {\n throw new Error(`Original directory does not exist: ${this.originalDirectory}`);\n }\n }\n\n /**\n * Setup the repository with environment files only\n */\n async setup(): Promise<SetupResult> {\n const result: SetupResult = {\n envFilesCopied: [],\n errors: [],\n };\n\n try {\n // Copy environment files if original directory is provided\n if (this.originalDirectory) {\n this.logger.info('Copying environment files...');\n result.envFilesCopied = await this.copyEnvironmentFiles();\n this.logger.success(`Copied ${result.envFilesCopied.filter((f) => f.copied).length} environment files`);\n }\n } catch (error: any) {\n const errorMessage = `Setup failed: ${error.message}`;\n result.errors.push(errorMessage);\n this.logger.error(errorMessage);\n }\n\n return result;\n }\n\n /**\n * Recursively find and copy environment files from original to target directory\n */\n async copyEnvironmentFiles(): Promise<EnvFileInfo[]> {\n if (!this.originalDirectory) {\n return [];\n }\n\n const envFiles: EnvFileInfo[] = [];\n const foundFiles = await this.findEnvironmentFiles(this.originalDirectory);\n\n for (const originalPath of foundFiles) {\n try {\n const relativePath = relative(this.originalDirectory, originalPath);\n const targetPath = join(this.targetDirectory, relativePath);\n const targetDir = dirname(targetPath);\n\n // Ensure target directory exists\n if (!existsSync(targetDir)) {\n await mkdir(targetDir, { recursive: true });\n }\n\n // Copy the file\n await copyFile(originalPath, targetPath);\n\n envFiles.push({\n originalPath,\n targetPath,\n relativePath,\n copied: true,\n });\n\n this.logger.debug(`Copied: ${relativePath}`);\n } catch (error: any) {\n envFiles.push({\n originalPath,\n targetPath: '',\n relativePath: relative(this.originalDirectory, originalPath),\n copied: false,\n });\n\n this.logger.warn(`Failed to copy ${originalPath}: ${error.message}`);\n }\n }\n\n return envFiles;\n }\n\n /**\n * Recursively find all environment files in a directory\n */\n private async findEnvironmentFiles(directory: string, depth: number = 0): Promise<string[]> {\n const envFiles: string[] = [];\n const maxDepth = 5;\n\n // Stop recursion if we've reached the maximum depth\n if (depth >= maxDepth) {\n return envFiles;\n }\n\n try {\n const entries = await readdir(directory, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = join(directory, entry.name);\n\n if (entry.isDirectory()) {\n // Skip common directories that shouldn't contain env files\n if (this.shouldSkipDirectory(entry.name)) {\n continue;\n }\n\n // Recursively search subdirectories with incremented depth\n const subDirFiles = await this.findEnvironmentFiles(fullPath, depth + 1);\n envFiles.push(...subDirFiles);\n } else if (entry.isFile()) {\n // Check if file matches any env file pattern\n if (this.isEnvironmentFile(entry.name)) {\n envFiles.push(fullPath);\n }\n }\n }\n } catch (error: any) {\n this.logger.debug(`Cannot read directory ${directory}: ${error.message}`);\n }\n\n return envFiles;\n }\n\n /**\n * Check if a filename matches environment file patterns\n */\n private isEnvironmentFile(filename: string): boolean {\n return this.envFilePatterns.some((pattern) => {\n if (pattern.includes('*')) {\n // Handle wildcard patterns if needed in the future\n return false;\n }\n return filename === pattern || filename.startsWith(pattern + '.');\n });\n }\n\n /**\n * Check if a directory should be skipped during env file search\n */\n private shouldSkipDirectory(dirName: string): boolean {\n const skipDirs = [\n 'node_modules',\n '.git',\n '.next',\n '.nuxt',\n 'dist',\n 'build',\n 'coverage',\n '.nyc_output',\n '.cache',\n 'tmp',\n 'temp',\n '.vscode',\n '.idea',\n '__pycache__',\n '.pytest_cache',\n '.mypy_cache',\n ];\n\n return skipDirs.includes(dirName) || dirName.startsWith('.');\n }\n\n /**\n * Install dependencies using the specified package manager\n */\n async installDependencies(packageManager: 'pnpm' | 'npm' | 'yarn' = 'pnpm'): Promise<boolean> {\n try {\n // Check if package.json exists\n const packageJsonPath = join(this.targetDirectory, 'package.json');\n if (!existsSync(packageJsonPath)) {\n this.logger.debug('No package.json found, skipping dependency installation');\n return false;\n }\n\n // Check if package manager is available\n if (!this.isPackageManagerAvailable(packageManager)) {\n this.logger.warn(`${packageManager} is not available, trying npm...`);\n if (this.isPackageManagerAvailable('npm')) {\n packageManager = 'npm';\n } else {\n throw new Error('No package manager available (tried pnpm, npm)');\n }\n }\n\n // Install dependencies\n const installCommand = this.getInstallCommand(packageManager);\n this.logger.info(`Running: ${installCommand}`);\n\n try {\n execSync(installCommand, {\n cwd: this.targetDirectory,\n stdio: 'pipe',\n encoding: 'utf8',\n });\n return true;\n } catch (installError: any) {\n // Check for workspace protocol error which is expected in Docker\n if (installError.message?.includes('EUNSUPPORTEDPROTOCOL') || installError.message?.includes('workspace:')) {\n this.logger.warn('Workspace protocol detected in dependencies, skipping installation');\n this.logger.debug('This is expected in Docker containers where dependencies are pre-installed');\n return false;\n }\n // Re-throw for other errors to be caught by outer catch\n throw installError;\n }\n } catch (error: any) {\n this.logger.error(`Failed to install dependencies: ${error.message}`);\n return false;\n }\n }\n\n /**\n * Check if a package manager is available\n */\n private isPackageManagerAvailable(packageManager: string): boolean {\n try {\n execSync(`${packageManager} --version`, {\n stdio: 'pipe',\n timeout: 5000,\n });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get install command for the specified package manager\n */\n private getInstallCommand(packageManager: 'pnpm' | 'npm' | 'yarn'): string {\n switch (packageManager) {\n case 'pnpm':\n return 'pnpm install';\n case 'yarn':\n return 'yarn install';\n case 'npm':\n default:\n return 'npm install';\n }\n }\n\n /**\n * Get list of environment files that would be copied (dry run)\n */\n async getEnvironmentFiles(): Promise<string[]> {\n if (!this.originalDirectory) {\n return [];\n }\n\n return await this.findEnvironmentFiles(this.originalDirectory);\n }\n\n /**\n * Get the target directory path\n */\n getTargetDirectory(): string {\n return this.targetDirectory;\n }\n\n /**\n * Get the original directory path\n */\n getOriginalDirectory(): string | undefined {\n return this.originalDirectory;\n }\n\n /**\n * Check if the target directory has a package.json\n */\n hasPackageJson(): boolean {\n return existsSync(join(this.targetDirectory, 'package.json'));\n }\n\n /**\n * Check if the target directory appears to be a Node.js project\n */\n isNodeProject(): boolean {\n const indicators = ['package.json', 'node_modules', 'yarn.lock', 'package-lock.json', 'pnpm-lock.yaml'];\n\n return indicators.some((indicator) => existsSync(join(this.targetDirectory, indicator)));\n }\n\n /**\n * Check if the target directory appears to be a Python project\n */\n isPythonProject(): boolean {\n const indicators = ['requirements.txt', 'pyproject.toml', 'setup.py', 'Pipfile', 'poetry.lock', 'uv.lock'];\n\n return indicators.some((indicator) => existsSync(join(this.targetDirectory, indicator)));\n }\n\n /**\n * Check if the target directory is an Nx monorepo\n */\n isNxMonorepo(): boolean {\n const nxIndicators = ['nx.json', 'workspace.json', 'angular.json'];\n\n return nxIndicators.some((indicator) => existsSync(join(this.targetDirectory, indicator)));\n }\n\n /**\n * Get default pre-agent start hooks based on project type\n * Returns empty array if user provides their own hooks\n */\n getDefaultPreAgentHooks(userProvidedHooks?: string[]): string[] {\n // If user provided hooks, don't add defaults\n if (userProvidedHooks && userProvidedHooks.length > 0) {\n this.logger.debug('User provided pre-agent hooks, skipping defaults');\n return userProvidedHooks;\n }\n\n const defaultHooks: string[] = [];\n\n // Check if it's a Node.js project that needs dependencies\n if (this.isNodeProject()) {\n const hasNodeModules = existsSync(join(this.targetDirectory, 'node_modules'));\n if (!hasNodeModules && this.hasPackageJson()) {\n this.logger.info('No node_modules found, adding default pnpm install hook');\n defaultHooks.push('pnpm install');\n\n // If it's an Nx monorepo, also add build command\n if (this.isNxMonorepo()) {\n this.logger.info('Nx monorepo detected, adding default build hook');\n defaultHooks.push('nx run-many -t build');\n }\n }\n }\n\n // Check if it's a Python project that needs dependencies\n if (this.isPythonProject()) {\n const hasVenv = existsSync(join(this.targetDirectory, '.venv')) || existsSync(join(this.targetDirectory, 'venv'));\n if (!hasVenv) {\n this.logger.info('No virtual environment found, adding default Python setup hooks');\n // Check for uv.lock to use uv, otherwise use standard tools\n if (existsSync(join(this.targetDirectory, 'uv.lock'))) {\n defaultHooks.push('uv sync');\n } else if (existsSync(join(this.targetDirectory, 'requirements.txt'))) {\n defaultHooks.push('python -m venv .venv');\n defaultHooks.push('.venv/bin/pip install -r requirements.txt');\n }\n }\n }\n\n return defaultHooks;\n }\n\n /**\n * Pre-agent setup that handles environment files and returns appropriate hooks\n */\n async preAgentSetup(userProvidedHooks?: string[]): Promise<{\n hooks: string[];\n envFilesCopied?: EnvFileInfo[];\n errors?: string[];\n }> {\n const result: {\n hooks: string[];\n envFilesCopied?: EnvFileInfo[];\n errors?: string[];\n } = {\n hooks: [],\n };\n\n // Copy environment files if original directory is provided\n if (this.originalDirectory) {\n const setupResult = await this.setup();\n result.envFilesCopied = setupResult.envFilesCopied;\n result.errors = setupResult.errors;\n }\n\n // Get appropriate pre-agent hooks (user-provided or defaults)\n result.hooks = this.getDefaultPreAgentHooks(userProvidedHooks);\n\n return result;\n }\n\n /**\n * Build the Nx monorepo using nx run-many -t build\n */\n async buildNxMonorepo(): Promise<boolean> {\n try {\n // Check if nx is available\n if (!this.isNxAvailable()) {\n this.logger.warn('Nx is not available, skipping build');\n return false;\n }\n\n this.logger.info('Running: nx run-many -t build');\n\n try {\n execSync('nx run-many -t build', {\n cwd: this.targetDirectory,\n stdio: 'pipe',\n encoding: 'utf8',\n timeout: 300000, // 5 minutes timeout\n });\n return true;\n } catch (buildError: any) {\n // Check for workspace-related errors or missing dependencies which are expected in Docker\n if (\n buildError.message?.includes('workspace:') ||\n buildError.message?.includes('Cannot find module') ||\n buildError.message?.includes('ENOENT')\n ) {\n this.logger.warn('Build failed due to workspace or dependency issues, skipping build');\n this.logger.debug('This is expected in Docker containers with pre-built applications');\n return false;\n }\n // Re-throw for other errors to be caught by outer catch\n throw buildError;\n }\n } catch (error: any) {\n this.logger.error(`Failed to build Nx monorepo: ${error.message}`);\n return false;\n }\n }\n\n /**\n * Check if Nx is available\n */\n private isNxAvailable(): boolean {\n try {\n execSync('nx --version', {\n stdio: 'pipe',\n timeout: 5000,\n });\n return true;\n } catch {\n // Try npx nx as fallback\n try {\n execSync('npx nx --version', {\n stdio: 'pipe',\n timeout: 10000,\n });\n return true;\n } catch {\n return false;\n }\n }\n }\n}\n","/**\n * StdinForwarding Service\n *\n * Manages stdin mode switching between daemon (normal SIGINT) and agent (PTY forwarding).\n */\n\nimport { Logger } from '../utils/logger';\n\ninterface StdinForwardingOptions {\n logger?: Logger;\n onData: (data: string) => void;\n onExit: (data: string) => void | Promise<void>;\n}\n\nexport class StdinForwarding {\n private logger: Logger;\n private onData: (data: string) => void;\n private onExit: (data: string) => void | Promise<void>;\n // Ctrl+C handling for graceful exit\n private ctrlCCount = 0;\n private ctrlCTimeout: NodeJS.Timeout | null = null;\n private readonly CTRL_C_RESET_MS = 3000; // Reset Ctrl+C count after 2 seconds\n\n constructor({ logger, onData, onExit }: StdinForwardingOptions) {\n this.logger = logger ?? new Logger({ verbose: false });\n this.onData = onData;\n this.onExit = onExit;\n this.start();\n }\n\n /**\n * Handle Ctrl+C (SIGINT) signals with double-press requirement\n * First Ctrl+C is used by Claude to clear input, second Ctrl+C exits\n */\n private handleCtrlC(): boolean {\n this.ctrlCCount++;\n\n // Clear any existing timeout\n if (this.ctrlCTimeout) {\n clearTimeout(this.ctrlCTimeout);\n }\n\n if (this.ctrlCCount === 1) {\n this.logger.debug('First Ctrl+C detected - Claude will clear input. Press Ctrl+C again to exit.');\n\n // Reset count after timeout\n this.ctrlCTimeout = setTimeout(() => {\n this.ctrlCCount = 0;\n this.ctrlCTimeout = null;\n }, this.CTRL_C_RESET_MS);\n\n // Don't exit on first Ctrl+C\n return false;\n } else if (this.ctrlCCount >= 2) {\n this.logger.debug('Second Ctrl+C detected - initiating graceful exit.');\n\n // Clear timeout\n if (this.ctrlCTimeout) {\n clearTimeout(this.ctrlCTimeout);\n this.ctrlCTimeout = null;\n }\n\n // Reset count\n this.ctrlCCount = 0;\n\n // Allow exit on second Ctrl+C\n return true;\n }\n\n return false;\n }\n\n /**\n * Enable stdin forwarding for a fullscreen agent's PTY\n */\n start(): void {\n this.logger.info('StdinForwarding starting...');\n\n if (!process.stdin.isTTY) {\n this.logger.warn('No TTY available for stdin forwarding');\n return;\n }\n\n this.logger.debug('Setting up process event handlers...');\n\n process.on('SIGINT', () => {\n this.logger.info('Process received SIGINT');\n this.onExit('SIGINT');\n });\n\n process.on('SIGTERM', () => {\n this.logger.info('Process received SIGTERM');\n this.onExit('SIGTERM');\n });\n\n process.on('uncaughtException', async (error) => {\n this.logger.error('Uncaught exception:', error);\n try {\n this.onExit('uncaughtException');\n } catch {\n // ignore\n }\n process.exit(1);\n });\n\n process.on('unhandledRejection', async (reason: any) => {\n this.logger.error('Unhandled rejection:', reason);\n try {\n this.onExit(reason.toString());\n } catch {\n // ignore\n }\n process.exit(1);\n });\n\n this.logger.debug('Setting stdin to raw mode...');\n try {\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.setEncoding('utf8');\n this.logger.debug('Stdin raw mode enabled successfully');\n } catch (error) {\n this.logger.error('Failed to set stdin raw mode:', error as any);\n return;\n }\n this.logger.debug('Setting up stdin data handler...');\n\n process.stdin.on('data', (data: string) => {\n try {\n this.logger.debug('=== STDIN DATA RECEIVED ===');\n\n // Handle Ctrl+C specifically with double-press requirement\n if (data === '\\u0003') {\n const shouldExit = this.handleCtrlC();\n if (shouldExit) {\n this.logger.debug('Double Ctrl+C detected, exiting agent');\n this.onExit(data);\n return;\n } else {\n this.logger.debug('First Ctrl+C detected, forwarding to Claude to clear input');\n // Forward the first Ctrl+C to Claude to clear input\n this.onData(data);\n return;\n }\n }\n\n // Handle Ctrl+D (EOF) - should exit gracefully\n if (data === '\\u0004') {\n this.logger.debug('Received Ctrl+D (EOF), exiting agent');\n this.onExit(data);\n return;\n }\n\n // Log what we're forwarding for debugging\n this.logger.debug(\n `Forwarding stdin data: ${JSON.stringify(data)} (length: ${data.length}, chars: ${data\n .split('')\n .map((c) => c.charCodeAt(0))\n .join(',')})`,\n );\n\n // Safety check - identify the type of input for better debugging\n const isNormalInput = data.length === 1 && data.charCodeAt(0) >= 32 && data.charCodeAt(0) <= 126;\n const isEnter = data === '\\r' || data === '\\n' || data === '\\r\\n';\n const isTab = data === '\\t';\n const isBackspace = data === '\\b' || data === '\\x7f';\n\n if (isNormalInput) {\n this.logger.debug('Normal typing character detected');\n } else if (isEnter) {\n this.logger.debug('Enter key detected');\n } else if (isTab) {\n this.logger.debug('Tab key detected');\n } else if (isBackspace) {\n this.logger.debug('Backspace detected');\n } else {\n this.logger.debug(`Special character detected (code: ${data.charCodeAt(0)})`);\n }\n\n this.logger.debug('About to call onData...');\n\n // Forward all other data without trimming to preserve formatting\n // The agent should handle the raw input including newlines\n this.onData(data);\n\n this.logger.debug('onData call completed');\n } catch (error) {\n this.logger.error('Error handling stdin data:', error as any);\n // Don't exit here, just log the error\n }\n });\n\n process.stdin.on('error', (error) => {\n this.logger.error('Stdin error:', error);\n });\n\n process.stdin.on('end', () => {\n this.logger.info('Stdin ended');\n });\n\n this.logger.info('Stdin forwarding enabled for fullscreen agent');\n }\n\n /**\n * Restore stdio handler to terminal's original state\n */\n restore(): void {\n this.logger.info('Restoring stdio handler to terminal...');\n\n try {\n // Clear any pending timeout\n if (this.ctrlCTimeout) {\n clearTimeout(this.ctrlCTimeout);\n this.ctrlCTimeout = null;\n }\n\n // Reset Ctrl+C count\n this.ctrlCCount = 0;\n\n // Restore stdin to original state\n if (process.stdin.isTTY) {\n // Remove all listeners we added\n process.stdin.removeAllListeners('data');\n process.stdin.removeAllListeners('error');\n process.stdin.removeAllListeners('end');\n\n // Restore stdin to normal mode (not raw)\n process.stdin.setRawMode(false);\n process.stdin.pause();\n }\n\n this.logger.info('Stdio handler restored to terminal successfully');\n } catch (error) {\n this.logger.error('Error restoring stdio handler:', error as any);\n throw error;\n }\n }\n}\n","/**\n * TerminationService\n *\n * Centralized service for managing graceful termination of PTY processes,\n * agent instances, and daemon cleanup. Ensures proper cleanup order:\n * 1. PTY processes terminate naturally or are killed\n * 2. Agent instances are removed from daemon records\n * 3. Daemon performs final cleanup before exit\n *\n * Signal Handling:\n * - Agent SIGINT (Ctrl+C): Stops only the agent, not the daemon\n * - Daemon SIGINT (Ctrl+C): Stops all agents and the daemon\n * - Natural PTY exit: Cleans up agent resources\n */\n\nimport { EventEmitter } from 'events';\nimport { Logger } from '../utils/logger';\n\nexport interface TerminationContext {\n agentSessionId: string;\n reason: 'natural' | 'daemon_shutdown' | 'agent_error' | 'user_requested' | 'agent_sigint';\n exitCode?: number;\n signal?: NodeJS.Signals;\n}\n\nexport interface TerminationCallbacks {\n onPtyTerminated?: (context: TerminationContext) => Promise<void>;\n onAgentTerminated?: (context: TerminationContext) => Promise<void>;\n onDaemonTerminating?: () => Promise<void>;\n onAgentSigint?: (context: TerminationContext) => Promise<void>;\n}\n\nexport class TerminationService extends EventEmitter {\n private logger: Logger;\n private isShuttingDown = false;\n private activeTerminations = new Map<string, Promise<void>>();\n private callbacks: TerminationCallbacks = {};\n\n constructor(logger?: Logger) {\n super();\n this.logger = logger ?? new Logger({ verbose: false });\n }\n\n /**\n * Register termination callbacks\n */\n registerCallbacks(callbacks: TerminationCallbacks): void {\n this.callbacks = { ...this.callbacks, ...callbacks };\n }\n\n /**\n * Handle agent SIGINT (Ctrl+C in agent PTY)\n * This stops only the agent, not the daemon\n */\n async handleAgentSigint(agentSessionId: string): Promise<void> {\n this.logger.info(`Agent ${agentSessionId} received SIGINT (Ctrl+C), stopping agent only`);\n\n const context: TerminationContext = {\n agentSessionId,\n reason: 'agent_sigint',\n signal: 'SIGINT',\n };\n\n // Prevent concurrent terminations\n const existing = this.activeTerminations.get(agentSessionId);\n if (existing) {\n this.logger.debug(`Termination already in progress for agent ${agentSessionId}`);\n return existing;\n }\n\n const terminationPromise = this.performAgentSigintTermination(context);\n this.activeTerminations.set(agentSessionId, terminationPromise);\n\n try {\n await terminationPromise;\n } finally {\n this.activeTerminations.delete(agentSessionId);\n }\n }\n\n private async performAgentSigintTermination(context: TerminationContext): Promise<void> {\n try {\n // Emit event for agent SIGINT handling\n this.emit('agent:sigint', context);\n\n // Call registered callback to trigger daemon stop-agent\n if (this.callbacks.onAgentSigint) {\n await this.callbacks.onAgentSigint(context);\n }\n\n // Emit cleanup events\n this.emit('agent:cleanup', context);\n if (this.callbacks.onAgentTerminated) {\n await this.callbacks.onAgentTerminated(context);\n }\n } catch (error) {\n this.logger.error(`Error handling agent SIGINT: ${error}`);\n throw error;\n }\n }\n\n /**\n * Handle PTY natural termination\n * Called when a PTY process exits on its own\n */\n async handlePtyTermination(context: TerminationContext): Promise<void> {\n const { agentSessionId, exitCode, signal } = context;\n this.logger.info(\n `PTY terminated naturally for session agent ${agentSessionId}. Exit code: ${exitCode}, Signal: ${signal}`,\n );\n\n // Prevent concurrent terminations for same session\n const existing = this.activeTerminations.get(agentSessionId);\n if (existing) {\n this.logger.debug(`Termination already in progress for agent ${agentSessionId}`);\n return existing;\n }\n\n const terminationPromise = this.performPtyTermination(context);\n this.activeTerminations.set(agentSessionId, terminationPromise);\n\n try {\n await terminationPromise;\n } finally {\n this.activeTerminations.delete(agentSessionId);\n }\n }\n\n private async performPtyTermination(context: TerminationContext): Promise<void> {\n try {\n // Emit event for listeners\n this.emit('pty:terminated', context);\n\n // Call registered callback\n if (this.callbacks.onPtyTerminated) {\n await this.callbacks.onPtyTerminated(context);\n }\n\n // If this is a natural termination, notify daemon to remove from records\n if (context.reason === 'natural') {\n this.emit('agent:cleanup', context);\n if (this.callbacks.onAgentTerminated) {\n await this.callbacks.onAgentTerminated(context);\n }\n }\n } catch (error) {\n this.logger.error(`Error handling PTY termination: ${error}`);\n throw error;\n }\n }\n\n /**\n * Terminate an agent session\n * Called when daemon wants to terminate an agent\n */\n async terminateAgent(agentSessionId: string, options: { force?: boolean; timeout?: number } = {}): Promise<void> {\n const { force = false, timeout = 5000 } = options;\n\n this.logger.info(`Terminating agent ${agentSessionId} for session force: ${force}`);\n\n const context: TerminationContext = {\n agentSessionId,\n reason: 'user_requested',\n };\n\n // Prevent concurrent terminations\n const existing = this.activeTerminations.get(agentSessionId);\n if (existing) {\n this.logger.debug(`Termination already in progress for agent ${agentSessionId}`);\n return existing;\n }\n\n const terminationPromise = this.performAgentTermination(context, { force, timeout });\n this.activeTerminations.set(agentSessionId, terminationPromise);\n\n try {\n await terminationPromise;\n } finally {\n this.activeTerminations.delete(agentSessionId);\n }\n }\n\n private async performAgentTermination(\n context: TerminationContext,\n options: { force?: boolean; timeout?: number },\n ): Promise<void> {\n const { force, timeout } = options;\n\n try {\n // Emit event to trigger PTY termination\n this.emit('agent:terminating', context);\n\n // Wait for graceful termination with timeout\n const timeoutPromise = new Promise<void>((_, reject) => {\n setTimeout(() => reject(new Error(`Termination timeout for agent ${context.agentSessionId}`)), timeout);\n });\n\n const terminationPromise = new Promise<void>((resolve) => {\n const handler = (terminatedContext: TerminationContext) => {\n if (terminatedContext.agentSessionId === context.agentSessionId) {\n this.off('agent:terminated', handler);\n resolve();\n }\n };\n this.on('agent:terminated', handler);\n });\n\n try {\n await Promise.race([terminationPromise, timeoutPromise]);\n this.logger.info(`Agent ${context.agentSessionId} terminated gracefully`);\n } catch (error) {\n if (force) {\n this.logger.warn(`Forcefully terminating agent ${context.agentSessionId} after timeout`);\n this.emit('agent:force-terminate', context);\n } else {\n throw error;\n }\n }\n\n // Cleanup agent from records\n if (this.callbacks.onAgentTerminated) {\n await this.callbacks.onAgentTerminated(context);\n }\n } catch (error) {\n this.logger.error(`Error terminating agent: ${error}`);\n throw error;\n }\n }\n\n /**\n * Initiate daemon shutdown\n * Terminates all agents before shutting down daemon\n */\n async shutdownDaemon(agentSessionIds: string[]): Promise<void> {\n if (this.isShuttingDown) {\n this.logger.debug('Daemon shutdown already in progress');\n return;\n }\n\n this.isShuttingDown = true;\n this.logger.info('Initiating daemon shutdown, terminating all agents...');\n\n try {\n // Notify about daemon shutdown\n if (this.callbacks.onDaemonTerminating) {\n await this.callbacks.onDaemonTerminating();\n }\n\n // Emit daemon shutdown event\n this.emit('daemon:shutting-down');\n\n // Terminate all agents in parallel with timeout\n const terminationPromises = agentSessionIds.map((agentSessionId) => {\n return this.terminateAgent(agentSessionId, { force: true, timeout: 3000 }).catch((error) => {\n this.logger.error(`Failed to terminate agent ${agentSessionId}: ${error}`);\n });\n });\n\n // Wait for all agents to terminate\n await Promise.allSettled(terminationPromises);\n this.logger.info('All agents terminated, daemon can now exit');\n\n // Emit final shutdown event\n this.emit('daemon:shutdown-complete');\n } catch (error) {\n this.logger.error(`Error during daemon shutdown: ${error}`);\n throw error;\n } finally {\n this.isShuttingDown = false;\n }\n }\n\n /**\n * Check if shutdown is in progress\n */\n isShuttingDownNow(): boolean {\n return this.isShuttingDown;\n }\n\n /**\n * Wait for all active terminations to complete\n */\n async waitForActiveTerminations(): Promise<void> {\n if (this.activeTerminations.size === 0) {\n return;\n }\n\n this.logger.info(`Waiting for ${this.activeTerminations.size} active terminations to complete...`);\n await Promise.allSettled(this.activeTerminations.values());\n this.logger.info('All active terminations completed');\n }\n\n /**\n * Clean up resources\n */\n cleanup(): void {\n this.removeAllListeners();\n this.activeTerminations.clear();\n this.callbacks = {};\n }\n}\n","/**\n * Base Agent Class\n *\n * Provides shared functionality for all agent types including:\n * - WebSocket connection management to agent sessions\n * - Message parsing and routing\n * - Session lifecycle management\n * - Common agent operations\n */\n\nimport {\n AGENT_STATUS,\n AGENT_TYPES,\n type AgentSessionDirectControlRequestEvent,\n type AgentSessionMessageInputRequestEvent,\n type AgentSessionMessageStdinRequestEvent,\n type AgentSessionResizeRequestEvent,\n type AgentSessionStatusRequestEvent,\n type DaemonStartAgentRequestEvent,\n OUTPUT_STREAMS,\n} from '@agimonai/universal-agent-events';\nimport fs from 'fs';\nimport path from 'path';\nimport { getServerUrl } from '../config';\nimport { ENV_KEYS } from '../config/subenv';\nimport { AgentHttpService } from '../services/AgentHttpService';\nimport { type AgentWsCallbacks, type AgentWsOptions, AgentWsService } from '../services/AgentWsService';\nimport { CredentialsService } from '../services/CredentialsService';\nimport { PtyRunnerService } from '../services/PtyRunnerService';\nimport { RepoSetupService } from '../services/RepoSetupService';\nimport { StdinForwarding } from '../services/StdinForwarding';\nimport { TerminationService } from '../services/TerminationService';\nimport { Logger } from '../utils/logger';\n\nexport interface AgentInfo {\n agentSessionId: string;\n agentType: string;\n status: (typeof AGENT_STATUS)[keyof typeof AGENT_STATUS];\n workingDir: string;\n process?: any;\n logStream?: fs.WriteStream;\n metadata?: Record<string, any>;\n}\n\nexport interface BaseAgentOptions {\n agentType: string;\n serverUrl?: string; // Optional - only required for WebSocket connectivity\n apiUrl?: string; // HTTP API URL for REST API calls\n apiKey?: string;\n verbose?: boolean;\n organizationId?: string;\n logger?: Logger;\n credentialsService?: CredentialsService;\n terminationService?: TerminationService;\n standalone?: boolean;\n onFullscreenChange?: (agentSessionId: string, isFullscreen: boolean) => void;\n}\n\nexport abstract class BaseAgent {\n protected agentType: string;\n protected serverUrl?: string; // Optional - only set when WebSocket connection is needed\n protected apiUrl?: string;\n protected apiKey?: string;\n protected verbose: boolean;\n protected organizationId?: string;\n protected standalone: boolean;\n protected logger: Logger;\n protected credentialsService: CredentialsService;\n protected terminationService: TerminationService;\n protected onFullscreenChange?: (agentSessionId: string, isFullscreen: boolean) => void;\n\n protected wsService?: AgentWsService; // Optional - only created when serverUrl is provided\n protected httpService?: AgentHttpService; // Optional - only created when apiUrl is provided\n protected ptyRunner: PtyRunnerService;\n protected agentInfo: AgentInfo | null = null;\n protected ptySessionId: string | null = null;\n protected xtermEnabled: boolean = false;\n protected stdinForwarding: StdinForwarding | null = null;\n public isFullscreen: boolean = false;\n\n // Stdout throttling properties\n private stdoutBuffer: string = '';\n private stdoutThrottleTimer: NodeJS.Timeout | null = null;\n private lastStdoutSent: number = 0;\n private readonly STDOUT_THROTTLE_MS = 500; // 500ms throttling\n private readonly STDOUT_BUFFER_LIMIT = 64 * 1024; // 64KB buffer limit\n\n // Background output buffer for non-fullscreen agents - maintains persistent history\n private backgroundOutputBuffer: string[] = [];\n private readonly BACKGROUND_BUFFER_SIZE = 10; // Keep last 10 chunks for better history (increased from 5)\n private readonly BACKGROUND_CHUNK_MAX_SIZE = 2048; // Max size per chunk (2KB)\n\n constructor(options: BaseAgentOptions) {\n this.agentType = options.agentType;\n this.serverUrl = options.serverUrl;\n this.apiUrl = options.apiUrl;\n this.apiKey = options.apiKey;\n this.verbose = options.verbose ?? false;\n this.organizationId = options.organizationId;\n this.standalone = options.standalone ?? false;\n this.logger = options.logger ?? new Logger({ verbose: this.verbose });\n this.credentialsService = options.credentialsService ?? new CredentialsService();\n this.terminationService = options.terminationService ?? new TerminationService(this.logger);\n this.onFullscreenChange = options.onFullscreenChange;\n\n // Initialize PTY runner service\n this.ptyRunner = new PtyRunnerService(this.logger);\n\n // Initialize WebSocket service only if serverUrl is provided\n if (options.serverUrl) {\n const wsOptions: AgentWsOptions = {\n serverUrl: options.serverUrl,\n apiKey: options.apiKey,\n verbose: options.verbose,\n organizationId: options.organizationId,\n credentialsService: this.credentialsService,\n logger: this.logger,\n };\n\n const wsCallbacks: AgentWsCallbacks = {\n onStatusRequest: (message) => this.handleStatusRequest(message),\n onMessageInput: (message) => this.handleMessageInput(message),\n onStdinInput: (message) => this.handleStdinInput(message),\n onResizeRequest: (message) => this.handleResizeRequest(message),\n onDirectControl: (message) => this.handleDirectControl(message),\n onConnect: () => this.onWebSocketConnect(),\n onDisconnect: (code, reason) => this.onWebSocketDisconnect(code, reason),\n onError: (error) => this.onWebSocketError(error),\n };\n\n this.wsService = new AgentWsService(wsOptions, wsCallbacks);\n this.logger.debug('WebSocket service initialized');\n } else {\n this.logger.info('Running in standalone mode without WebSocket connection');\n }\n\n // Initialize HTTP service only if apiUrl or serverUrl is provided\n const serverUrl = getServerUrl();\n const effectiveApiUrl = this.apiUrl || serverUrl || options.serverUrl;\n if (effectiveApiUrl) {\n this.httpService = new AgentHttpService({\n apiUrl: effectiveApiUrl,\n organizationId: this.organizationId,\n apiKey: this.apiKey,\n logger: this.logger,\n });\n this.logger.debug('HTTP service initialized');\n } else {\n this.logger.info('HTTP service not initialized - no API URL provided');\n }\n\n // Initialize stdin forwarding if standalone mode\n if (this.standalone) {\n this.initializeStdinForwarding();\n }\n }\n\n /**\n * Initialize stdin forwarding for standalone mode\n */\n private initializeStdinForwarding(): void {\n this.stdinForwarding = new StdinForwarding({\n logger: this.logger,\n onData: (data: string) => {\n this.logger.debug(`StdinForwarding received data: ${JSON.stringify(data)}`);\n this.sendInputToPty(data);\n },\n onExit: (signal: string) => {\n this.logger.info(`StdinForwarding received exit signal: ${signal}`);\n this.disconnect();\n process.exit(0);\n },\n });\n }\n\n /**\n * Connect to agent session WebSocket (skipped if no serverUrl provided)\n */\n async connectToSession(agentSessionId: string): Promise<void> {\n this.logger.info(`connectToSession called with sessionId: ${agentSessionId}`);\n this.logger.info(`wsService exists: ${!!this.wsService}`);\n this.logger.info(`serverUrl: ${this.serverUrl || 'undefined'}`);\n\n if (!this.wsService) {\n this.logger.info('WebSocket service not available - skipping connection');\n return;\n }\n\n this.logger.info('Attempting to connect to WebSocket...');\n await this.wsService.connect(agentSessionId);\n\n // Send initial status after connection\n this.wsService.sendAgentStatus({\n agentType: this.agentType,\n status: AGENT_STATUS.IDLE,\n message: `${this.agentType} agent connected`,\n });\n }\n\n /**\n * Disconnect from WebSocket and terminate PTY\n */\n disconnect(): void {\n // Restore stdin forwarding if in standalone mode\n if (this.standalone && this.stdinForwarding) {\n try {\n this.stdinForwarding.restore();\n this.stdinForwarding = null;\n } catch (error) {\n this.logger.error('Error restoring stdin forwarding:', error as Error);\n }\n }\n\n // Flush any remaining stdout buffer before disconnecting\n this.flushStdoutBuffer();\n\n // Clear throttle timer\n if (this.stdoutThrottleTimer) {\n clearTimeout(this.stdoutThrottleTimer);\n this.stdoutThrottleTimer = null;\n }\n\n // Kill PTY process if it exists\n if (this.ptySessionId) {\n this.logger.info(`Terminating PTY session: ${this.ptySessionId}`);\n this.ptyRunner.kill();\n this.ptySessionId = null;\n }\n\n // Disconnect from WebSocket if available\n if (this.wsService) {\n this.wsService.disconnect();\n }\n\n // Clear agent info\n this.agentInfo = null;\n }\n\n /**\n * WebSocket event handlers\n */\n protected onWebSocketConnect(): void {\n this.logger.debug(`WebSocket connected for ${this.agentType} agent`);\n }\n\n protected onWebSocketDisconnect(code: number, reason: string): void {\n this.logger.debug(`WebSocket disconnected for ${this.agentType} agent (${code}): ${reason}`);\n }\n\n protected onWebSocketError(error: Error): void {\n this.logger.error(`WebSocket error for ${this.agentType} agent: ${error?.message || 'Unknown error'}`);\n this.logger.error(`Error stack: ${error?.stack || 'No stack trace'}`);\n }\n\n /**\n * Handle status request\n */\n protected async handleStatusRequest(message: AgentSessionStatusRequestEvent): Promise<void> {\n this.logger.debug(`Handling status request for session: ${message.payload.sessionId}`);\n\n // Skip if WebSocket service is not available\n if (!this.wsService) {\n this.logger.debug('WebSocket service not available - cannot handle status request');\n return;\n }\n\n try {\n // Store the session ID if this is a status request for it\n // This ensures we can respond to the session even before an agent is launched\n try {\n const currentSessionId = this.wsService.getCurrentSessionId();\n if (currentSessionId !== message.payload.sessionId) {\n this.wsService.setCurrentSessionId(message.payload.sessionId);\n this.logger.debug(`Set current session ID to: ${message.payload.sessionId}`);\n }\n } catch {\n // No session ID set yet, set it now\n this.wsService.setCurrentSessionId(message.payload.sessionId);\n this.logger.debug(`Set current session ID to: ${message.payload.sessionId}`);\n }\n\n // Determine the actual status\n let currentStatus: (typeof AGENT_STATUS)[keyof typeof AGENT_STATUS] = AGENT_STATUS.IDLE;\n let statusMessage = `${this.agentType} agent is idle`;\n\n if (this.agentInfo && this.agentInfo.agentSessionId === message.payload.sessionId) {\n // Use the agent's current status\n currentStatus = this.agentInfo.status;\n\n // Map status to message\n if (currentStatus === AGENT_STATUS.IDLE) {\n statusMessage = `${this.agentType} agent is running`;\n } else if (currentStatus === AGENT_STATUS.STARTING) {\n statusMessage = `${this.agentType} agent is starting`;\n } else if (currentStatus === AGENT_STATUS.ERROR) {\n statusMessage = `${this.agentType} agent encountered an error`;\n } else if (currentStatus === AGENT_STATUS.STOPPED) {\n statusMessage = `${this.agentType} agent is stopped`;\n }\n } else {\n // No agent launched yet but daemon is ready\n this.logger.debug(`No active agent process for session ${message.payload.sessionId}, but daemon is ready`);\n statusMessage = `${this.agentType} daemon ready, agent not launched`;\n }\n\n // Check if fullscreen mode should be enabled from the request\n if (message.payload.fullscreen === true) {\n this.logger.debug('Status request includes fullscreen=true, enabling fullscreen mode');\n this.setFullscreen(true);\n }\n\n // Send current agent status\n this.wsService.sendAgentStatus({\n agentType: this.agentType as any,\n status: currentStatus,\n message: statusMessage,\n pid: this.agentInfo?.process?.pid || process.pid,\n version: (await this.getVersion()) || undefined,\n capabilities: ['chat', 'code-editing', 'file-operations'],\n });\n } catch (error: any) {\n this.wsService.sendAgentError({\n code: 'STATUS_FAILED',\n message: `Status request failed: ${error.message}`,\n details: { error: error.toString() },\n });\n }\n }\n\n /**\n * Handle message input request\n */\n protected async handleMessageInput(message: AgentSessionMessageInputRequestEvent): Promise<void> {\n this.logger.debug(`Handling message input: ${message.payload.content}`);\n // Simulate typing to process.stdin to trigger StdinForwarding\n const content = message.payload.content;\n\n // Execute preCommands if provided (e.g., ESC to exit prompts)\n if (message.payload.preCommands && Array.isArray(message.payload.preCommands)) {\n this.logger.info(`[PreCommands] Executing ${message.payload.preCommands.length} pre-commands`);\n for (const preCommand of message.payload.preCommands) {\n this.sendInputToPty(preCommand);\n // Wait between commands - each is a complete action\n await new Promise((resolve) => setTimeout(resolve, 350));\n }\n // Wait for pre-commands to take effect\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n // If content is empty, skip sending input (used for testing preCommands only)\n if (!content || content.length === 0) {\n this.logger.info('[Content] Content is empty, skipping input');\n return;\n }\n\n this.sendInputToPty('\\x1b[I');\n // Check if agent type is Gemini - paste content instead of typing\n if (this.agentType.toLowerCase().includes(AGENT_TYPES.GEMINI_CLI)) {\n const typeSpeed = 150;\n // For Gemini, paste the entire content at once with newline\n this.logger.debug('Gemini agent detected - pasting content with newline');\n for (const text of [' ', ' ']) {\n await new Promise((resolve) => {\n setTimeout(() => {\n this.sendInputToPty(text);\n resolve(null);\n }, typeSpeed);\n });\n }\n await new Promise((resolve) => {\n setTimeout(() => {\n this.sendInputToPty(`${content}\\n`);\n resolve(null);\n }, typeSpeed);\n });\n\n await new Promise((resolve) => {\n setTimeout(() => {\n this.sendInputToPty('\\r');\n resolve(null);\n }, typeSpeed);\n });\n } else {\n this.sendInputToPty(content); // For other agents (like Claude Code), simulate typing character by character\n\n // Send Enter key after all characters are typed\n setTimeout(() => {\n this.sendInputToPty('\\r');\n }, 50); // Extra 50ms delay before Enter\n }\n }\n\n /**\n * Handle stdin input request (for xterm functionality)\n */\n protected async handleStdinInput(message: AgentSessionMessageStdinRequestEvent): Promise<void> {\n if (!this.xtermEnabled) {\n this.logger.debug('Stdin input received but xterm is not enabled, ignoring');\n return;\n }\n\n this.logger.debug(`Handling stdin input: ${message.payload.data}`);\n\n // Send the stdin data directly to the PTY\n this.sendInputToPty(message.payload.data);\n }\n\n /**\n * Handle resize request (for xterm functionality)\n */\n protected async handleResizeRequest(message: AgentSessionResizeRequestEvent): Promise<void> {\n this.logger.info(\n `🖥️ Resize request received: ${message.payload.cols}x${message.payload.rows}, xterm enabled: ${this.xtermEnabled}`,\n );\n\n if (!this.xtermEnabled) {\n this.logger.warn('Resize request received but xterm is not enabled, ignoring');\n return;\n }\n\n this.setFullscreen(true);\n // Resize the PTY to match the frontend terminal size\n this.resizePty(message.payload.cols, message.payload.rows);\n setTimeout(() => {\n this.sendBackgroundBuffer();\n }, 1000);\n this.logger.info(`✅ PTY resized to ${message.payload.cols}x${message.payload.rows}`);\n }\n\n /**\n * Handle agent session direct control request (control signals like ESC from controller to agent)\n */\n protected async handleDirectControl(message: AgentSessionDirectControlRequestEvent): Promise<void> {\n this.logger.debug(\n `Handling direct control request: ${message.payload.controlType} - data: ${JSON.stringify(message.payload.data)}`,\n );\n\n try {\n // Send the control signal directly to the PTY process\n this.sendInputToPty(message.payload.data);\n this.logger.debug(`Direct control signal sent to PTY: ${message.payload.controlType}`);\n } catch (error) {\n this.logger.error(`Failed to send direct control signal to PTY: ${error}`);\n }\n }\n\n /**\n * Send stdout data to controller when xterm is enabled and agent is in fullscreen (throttled to 500ms)\n * Always adds data to background buffer to maintain persistent history\n */\n protected sendStdoutEvent(data: string): void {\n if (!this.xtermEnabled || !this.agentInfo) {\n return;\n }\n\n // Always add to background buffer to maintain persistent history\n this.addToBackgroundBuffer(data);\n\n if (!this.isFullscreen) {\n // When not fullscreen, only store in background buffer, don't send to frontend\n return;\n }\n\n // Add data to buffer\n this.stdoutBuffer += data;\n\n // Check buffer size limit - flush immediately if exceeded\n if (this.stdoutBuffer.length > this.STDOUT_BUFFER_LIMIT) {\n this.logger.debug(`📦 Stdout buffer limit exceeded (${this.stdoutBuffer.length} chars), flushing immediately`);\n this.flushStdoutBuffer();\n return;\n }\n\n const now = Date.now();\n const timeSinceLastSent = now - this.lastStdoutSent;\n\n // If we can send immediately (enough time has passed)\n if (timeSinceLastSent >= this.STDOUT_THROTTLE_MS) {\n this.flushStdoutBuffer();\n } else {\n // Schedule a flush if not already scheduled\n if (!this.stdoutThrottleTimer) {\n const remainingTime = this.STDOUT_THROTTLE_MS - timeSinceLastSent;\n this.stdoutThrottleTimer = setTimeout(() => {\n this.flushStdoutBuffer();\n }, remainingTime);\n }\n }\n }\n\n /**\n * Flush the stdout buffer to WebSocket\n */\n private flushStdoutBuffer(): void {\n if (!this.stdoutBuffer || !this.wsService) {\n return;\n }\n\n try {\n // Send the buffered data\n this.wsService.sendStdoutMessage(this.stdoutBuffer);\n this.lastStdoutSent = Date.now();\n\n // Debug logging for throttling\n this.logger.debug(`📤 Stdout buffer flushed: ${this.stdoutBuffer.length} chars`);\n\n // Clear the buffer and timer\n this.stdoutBuffer = '';\n if (this.stdoutThrottleTimer) {\n clearTimeout(this.stdoutThrottleTimer);\n this.stdoutThrottleTimer = null;\n }\n } catch (error) {\n this.logger.error('Failed to send stdout event:', error as Error);\n }\n }\n\n /**\n * Add data to background buffer when agent is not fullscreen\n */\n private addToBackgroundBuffer(data: string): void {\n // Truncate data if it's too large for a single chunk\n const truncatedData =\n data.length > this.BACKGROUND_CHUNK_MAX_SIZE\n ? data.substring(data.length - this.BACKGROUND_CHUNK_MAX_SIZE)\n : data;\n\n // Add to buffer\n this.backgroundOutputBuffer.push(truncatedData);\n\n // Keep only the last N chunks\n if (this.backgroundOutputBuffer.length > this.BACKGROUND_BUFFER_SIZE) {\n this.backgroundOutputBuffer.shift();\n }\n\n this.logger.debug(\n `📦 Added ${truncatedData.length} chars to background buffer (${this.backgroundOutputBuffer.length}/${this.BACKGROUND_BUFFER_SIZE} chunks)`,\n );\n }\n\n /**\n * Send background buffer to stdout when agent becomes fullscreen\n * Note: Does NOT clear the buffer to maintain persistent history\n */\n private sendBackgroundBuffer(): void {\n if (this.backgroundOutputBuffer.length === 0 || !this.wsService) {\n return;\n }\n\n this.logger.debug(`📤 Sending background buffer: ${this.backgroundOutputBuffer.length} chunks`);\n\n // Send all buffered chunks immediately\n const bufferedData = this.backgroundOutputBuffer.join('');\n if (bufferedData) {\n // Send directly to WebSocket without throttling for immediate display\n try {\n this.wsService.sendStdoutMessage(bufferedData);\n this.logger.debug(`📤 Background buffer sent: ${bufferedData.length} chars`);\n } catch (error) {\n this.logger.error('Failed to send background buffer:', error as Error);\n }\n }\n\n // Do NOT clear the background buffer - maintain persistent history\n }\n\n /**\n * Set xterm enabled flag\n */\n protected setXtermEnabled(enabled: boolean): void {\n this.xtermEnabled = enabled;\n this.logger.debug(`Xterm functionality ${enabled ? 'enabled' : 'disabled'}`);\n }\n\n /**\n * Set fullscreen mode flag and notify other agents\n */\n public setFullscreen(enabled: boolean, silent: boolean = false): void {\n const wasFullscreen = this.isFullscreen;\n this.isFullscreen = enabled;\n this.logger.debug(`Agent fullscreen mode ${enabled ? 'enabled' : 'disabled'}`);\n\n // When becoming fullscreen, send any buffered background output (but keep the buffer)\n if (enabled && !wasFullscreen && this.xtermEnabled && this.agentInfo) {\n this.sendBackgroundBuffer();\n }\n\n // Notify other agents if status changed and we have an agent session ID (unless silenced)\n if (!silent && wasFullscreen !== enabled && this.agentInfo && this.onFullscreenChange) {\n this.onFullscreenChange(this.agentInfo.agentSessionId, enabled);\n }\n }\n\n /**\n * Get fullscreen status\n */\n public getFullscreen(): boolean {\n return this.isFullscreen;\n }\n\n /**\n * Send agent status message\n */\n protected sendAgentStatus(payload: {\n agentType?: any;\n status?: (typeof AGENT_STATUS)[keyof typeof AGENT_STATUS];\n pid?: number;\n version?: string;\n capabilities?: string[];\n message?: string;\n }): void {\n if (this.wsService) {\n this.wsService.sendAgentStatus(payload);\n }\n }\n\n /**\n * Send agent output message\n */\n protected sendAgentOutput(payload: {\n messageId: string;\n content: string;\n stream?: (typeof OUTPUT_STREAMS)[keyof typeof OUTPUT_STREAMS];\n isComplete?: boolean;\n metadata?: Record<string, any>;\n }): void {\n if (this.wsService) {\n this.wsService.sendAgentOutput(payload);\n }\n }\n\n /**\n * Send agent error message\n */\n protected sendAgentError(payload: { code: string; message: string; details?: any; stack?: string }): void {\n if (this.wsService) {\n this.wsService.sendAgentError(payload);\n }\n }\n\n // Abstract methods to be implemented by concrete agents\n\n /**\n * Launch the specific agent (e.g., Claude Code, Cursor, etc.)\n */\n abstract launchAgent(request: DaemonStartAgentRequestEvent): Promise<AgentInfo>;\n\n /**\n * Check if the agent is available on the system\n */\n abstract isAvailable(): Promise<boolean>;\n\n /**\n * Get agent version\n */\n abstract getVersion(): Promise<string | null>;\n\n /**\n * Get current agent info\n */\n getAgentInfo(): AgentInfo | null {\n return this.agentInfo;\n }\n\n /**\n * Send input to the PTY\n */\n sendInputToPty(data: string): void {\n this.ptyRunner.sendInput(data);\n }\n\n /**\n * Set agent info (called by concrete implementations after launching)\n */\n protected setAgentInfo(info: AgentInfo): void {\n this.agentInfo = info;\n if (info.agentSessionId && this.wsService) {\n try {\n this.wsService.setCurrentSessionId(info.agentSessionId);\n } catch {\n // Session ID might not be set yet, ignore\n }\n }\n }\n\n /**\n * Get environment variables to pass to the agent PTY session\n * Includes AGENT_API_KEY for agent authentication\n */\n protected getAgentEnvironmentVariables(): Record<string, string> {\n const env: Record<string, string> = {};\n\n // Copy process.env, filtering out undefined values\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined) {\n env[key] = value;\n }\n }\n\n // Pass API key to agent environment if available\n if (this.apiKey) {\n env[ENV_KEYS.AGENT_API_KEY] = this.apiKey;\n }\n\n // Pass organization ID if available\n if (this.organizationId) {\n env[ENV_KEYS.AGENT_ORGANIZATION_ID] = this.organizationId;\n }\n\n // Pass server URL for agent to connect back\n if (this.serverUrl) {\n env[ENV_KEYS.AGENT_SERVER_URL] = this.serverUrl;\n }\n\n // Pass agent type for identification\n env[ENV_KEYS.AGENT_TYPE] = this.agentType;\n\n // Pass verbose flag for debugging\n env[ENV_KEYS.VERBOSE] = this.verbose ? 'true' : 'false';\n\n return env;\n }\n\n /**\n * Configure NODE_OPTIONS to include network logging hook\n * This enables HTTP/HTTPS request interception for LLM API calls\n */\n protected configureNodeOptions(existingEnv: Record<string, string>): string {\n // Check for network logging hook - try same directory first, then parent directory\n let networkLogPath: string | null = null;\n\n // Define all paths for logging\n const sameDirJs = path.join(__dirname, 'networkLog.js');\n const sameDirTs = path.join(__dirname, 'networkLog.ts');\n const parentDirJs = path.join(__dirname, '..', 'networkLog.js');\n const parentDirTs = path.join(__dirname, '..', 'networkLog.ts');\n\n // Check same directory first\n if (fs.existsSync(sameDirJs)) {\n networkLogPath = sameDirJs;\n } else if (fs.existsSync(sameDirTs)) {\n networkLogPath = sameDirTs;\n } else {\n // Check parent directory\n if (fs.existsSync(parentDirJs)) {\n networkLogPath = parentDirJs;\n } else if (fs.existsSync(parentDirTs)) {\n networkLogPath = parentDirTs;\n }\n }\n\n // Get existing NODE_OPTIONS or empty string\n const NODE_OPTIONS_KEY = 'NODE_OPTIONS';\n let nodeOptions = existingEnv[NODE_OPTIONS_KEY] || '';\n\n this.logger.debug('Network logging hook configuration:', {\n sameDirJs,\n sameDirTs,\n parentDirJs,\n parentDirTs,\n foundPath: networkLogPath,\n existingNodeOptions: nodeOptions,\n alreadyIncludes: nodeOptions.includes('networkLog'),\n });\n\n // Add the network logging hook if it exists and is not already included\n if (networkLogPath && !nodeOptions.includes('networkLog')) {\n nodeOptions = `${nodeOptions} --require ${networkLogPath}`.trim();\n this.logger.debug(`Network logging hook added to NODE_OPTIONS: ${networkLogPath}`);\n } else if (!networkLogPath) {\n this.logger.warn('Network logging hook not found at any expected location');\n } else {\n this.logger.debug('Network logging hook already included in NODE_OPTIONS');\n }\n\n this.logger.debug(`Final NODE_OPTIONS: ${nodeOptions}`);\n return nodeOptions;\n }\n\n /**\n * Send input to the agent's stdin/PTY (implementation for PTY-based agents)\n */\n async sendInputToAgent(input: string) {\n const success = this.ptyRunner.sendInput(input);\n if (!success) {\n this.logger.warn(`Failed to send input to PTY session`);\n }\n }\n\n /**\n * Resize the PTY session\n */\n resizePty(cols: number, rows: number): void {\n this.ptyRunner.resize(cols, rows);\n }\n\n /**\n * Execute pre-agent start hooks in the working directory\n * If no hooks are provided, automatically determines default hooks based on project type\n * Reports errors to task if hook execution fails\n */\n protected async executePreAgentStartHooks(\n hooks: string[] | undefined,\n workingDir: string,\n agentSessionId?: string,\n ): Promise<void> {\n // Use RepoSetupService to determine appropriate hooks\n const repoSetupService = new RepoSetupService({\n targetDirectory: workingDir,\n logger: this.logger,\n });\n\n // Get default hooks if none provided\n const hooksToExecute = repoSetupService.getDefaultPreAgentHooks(hooks);\n\n if (!hooksToExecute || hooksToExecute.length === 0) {\n this.logger.debug('No pre-agent start hooks to execute');\n return;\n }\n\n this.logger.info(`Executing ${hooksToExecute.length} pre-agent start hook(s) in ${workingDir}`);\n\n const failedHooks: { hook: string; error: string; stderr?: string }[] = [];\n\n for (let i = 0; i < hooksToExecute.length; i++) {\n const hook = hooksToExecute[i];\n this.logger.info(`[${i + 1}/${hooksToExecute.length}] Executing hook: ${hook}`);\n\n // Start a message for this hook execution\n let messageId: string | undefined;\n if (agentSessionId && this.httpService) {\n try {\n const startResponse = await this.httpService.startMessage(agentSessionId, {\n messageType: 'output',\n metadata: {\n hookIndex: i + 1,\n totalHooks: hooksToExecute.length,\n command: hook,\n status: 'running',\n },\n });\n messageId = startResponse.id;\n } catch (error) {\n this.logger.debug('Failed to start hook message:', error as Error);\n }\n }\n\n try {\n // Use child_process to execute the hook command\n const { spawn } = await import('child_process');\n\n const hookResult = await new Promise<{ success: boolean; stdout?: string; stderr?: string; error?: string }>(\n (resolve) => {\n const child = spawn(hook, {\n cwd: workingDir,\n shell: true,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n\n child.stdout?.on('data', (data) => {\n const output = data.toString();\n stdout += output;\n // Log stdout in real-time for debugging\n this.logger.debug(`[Hook stdout] ${output.trim()}`);\n });\n\n child.stderr?.on('data', (data) => {\n const output = data.toString();\n stderr += output;\n // Log stderr in real-time for debugging\n this.logger.warn(`[Hook stderr] ${output.trim()}`);\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n this.logger.success(`Hook completed successfully: ${hook}`);\n if (stdout.trim()) {\n this.logger.debug(`Hook stdout: ${stdout.trim()}`);\n }\n resolve({ success: true, stdout: stdout.trim() });\n } else {\n this.logger.error(`Hook failed with exit code ${code}: ${hook}`);\n // Log both stdout and stderr for failed hooks\n if (stdout.trim()) {\n this.logger.error(`Hook stdout (full output): ${stdout.trim()}`);\n }\n if (stderr.trim()) {\n this.logger.error(`Hook stderr (full error): ${stderr.trim()}`);\n }\n\n // Create more detailed error message\n const errorDetails: string[] = [];\n if (stderr.trim()) {\n errorDetails.push(`stderr: ${stderr.trim()}`);\n }\n if (stdout.trim()) {\n errorDetails.push(`stdout: ${stdout.trim()}`);\n }\n\n const detailedError =\n errorDetails.length > 0\n ? `Hook failed with exit code ${code}. ${errorDetails.join(' | ')}`\n : `Hook failed with exit code ${code}`;\n\n resolve({\n success: false,\n error: detailedError,\n stderr: stderr.trim() || stdout.trim() || undefined, // Use stdout if stderr is empty\n });\n }\n });\n\n child.on('error', (error) => {\n this.logger.error(`Hook execution error: ${hook}`, error);\n resolve({\n success: false,\n error: error.message,\n });\n });\n },\n );\n\n // Update the message with the result\n if (agentSessionId && messageId && this.httpService) {\n try {\n const status = hookResult.success ? 'completed' : 'failed';\n const content = hookResult.success\n ? `✅ Hook completed: ${hook}`\n : `❌ Hook failed: ${hook}\\n${hookResult.error}`;\n\n await this.httpService.updateMessage(agentSessionId, messageId, {\n parts: [{ type: 'text', text: content }],\n metadata: {\n hookIndex: i + 1,\n totalHooks: hooksToExecute.length,\n command: hook,\n status,\n exitCode: hookResult.success ? 0 : 1,\n stdout: hookResult.stdout,\n stderr: hookResult.stderr,\n error: hookResult.error,\n },\n });\n } catch (error) {\n this.logger.debug('Failed to update hook message:', error as Error);\n }\n }\n\n if (!hookResult.success) {\n failedHooks.push({\n hook,\n error: hookResult.error || 'Unknown error',\n stderr: hookResult.stderr,\n });\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.logger.error(`Failed to execute hook: ${hook}`, error instanceof Error ? error : new Error(errorMessage));\n\n // Update message with error if we have a message ID and HTTP service\n if (agentSessionId && messageId && this.httpService) {\n try {\n await this.httpService.updateMessage(agentSessionId, messageId, {\n parts: [{ type: 'text', text: `❌ Hook execution failed: ${hook}\\nError: ${errorMessage}` }],\n metadata: {\n hookIndex: i + 1,\n totalHooks: hooksToExecute.length,\n command: hook,\n status: 'failed',\n error: errorMessage,\n },\n });\n } catch (updateError) {\n this.logger.debug('Failed to update hook message with error:', updateError as Error);\n }\n }\n\n failedHooks.push({\n hook,\n error: errorMessage,\n });\n }\n }\n\n // Report all hook failures to task if any occurred\n if (failedHooks.length > 0) {\n if (agentSessionId) {\n await this.reportHookFailuresToTask(agentSessionId, failedHooks);\n }\n\n // Throw error after reporting to stop execution\n const firstFailure = failedHooks[0];\n throw new Error(`Pre-agent hook(s) failed. First failure: ${firstFailure.hook} - ${firstFailure.error}`);\n }\n\n this.logger.success('All pre-agent start hooks completed successfully');\n }\n\n /**\n * Report hook failures to the task via comment\n */\n private async reportHookFailuresToTask(\n agentSessionId: string,\n failedHooks: { hook: string; error: string; stderr?: string }[],\n ): Promise<void> {\n if (!this.httpService) {\n this.logger.debug('HTTP service not available - cannot report hook failures to task');\n return;\n }\n\n try {\n const errorDetails = failedHooks\n .map((failure) => {\n let details = `• **Command**: \\`${failure.hook}\\`\\n **Error**: ${failure.error}`;\n if (failure.stderr) {\n details += `\\n **Output**: \\`\\`\\`\\n${failure.stderr}\\n\\`\\`\\``;\n }\n return details;\n })\n .join('\\n\\n');\n\n const comment = `⚠️ **Pre-agent start hook(s) failed**\\n\\n${errorDetails}\\n\\n**Suggestion**: Please check the hook commands and ensure all dependencies are installed correctly.`;\n\n await this.httpService.createTaskComment(agentSessionId, comment, undefined, {\n type: 'hook_failure',\n failedHooks,\n });\n\n this.logger.info('Hook failure reported to task');\n } catch (error) {\n this.logger.warn('Failed to report hook errors to task:', error as Error);\n // Don't throw - this is a nice-to-have feature\n }\n }\n\n /**\n * Setup repository with environment files and dependencies when using Docker\n * This should be called after the Docker container is set up but before the agent starts\n */\n protected async setupDockerRepository(request: any): Promise<void> {\n const agentConfig = request.payload?.agentConfig;\n const isDockerMode = agentConfig?.docker === true;\n\n if (!isDockerMode) {\n this.logger.debug('Not using Docker, skipping repository setup');\n return;\n }\n\n const workingDirectory = agentConfig?.workingDirectory || this.agentInfo?.workingDir;\n if (!workingDirectory) {\n this.logger.warn('No working directory specified for Docker repository setup');\n return;\n }\n\n try {\n this.logger.info('Setting up Docker repository with environment files...');\n\n // Use the current working directory as the original directory for copying env files\n const originalDirectory = process.cwd();\n\n const repoSetupService = new RepoSetupService({\n targetDirectory: workingDirectory,\n originalDirectory,\n logger: this.logger,\n });\n\n // Copy environment files only\n const result = await repoSetupService.setup();\n\n // Log results\n if (result.envFilesCopied.length > 0) {\n const copiedCount = result.envFilesCopied.filter((f) => f.copied).length;\n this.logger.success(`Copied ${copiedCount} environment files to Docker container`);\n }\n\n if (result.errors.length > 0) {\n this.logger.warn(`Docker repository setup completed with ${result.errors.length} errors`);\n result.errors.forEach((error) => this.logger.debug(`Setup error: ${error}`));\n }\n\n // Execute pre-agent start hooks (will use defaults if none provided)\n // Pass the agent session ID for error reporting\n const agentSessionId = agentConfig?.agentSessionId || this.agentInfo?.agentSessionId;\n // Support both preAgentStart and preAgentStartHooks property names for backward compatibility\n const userHooks = agentConfig?.hooks?.preAgentStartHooks || agentConfig?.hooks?.preAgentStart;\n await this.executePreAgentStartHooks(userHooks, workingDirectory, agentSessionId);\n } catch (error) {\n this.logger.error(`Failed to setup Docker repository: ${error}`);\n // Don't throw - Docker container creation succeeded, setup is optional\n }\n }\n\n /**\n * Detect and set initial PTY size based on current terminal dimensions\n * This is used when xterm is not enabled to ensure PTY fits the terminal\n */\n protected setupInitialPtySize(): void {\n try {\n // Get terminal size from process.stdout if available\n const cols = process.stdout.columns || 80; // Default to 80 if not available\n const rows = process.stdout.rows || 24; // Default to 24 if not available\n\n // Resize PTY to match terminal size\n this.resizePty(cols, rows);\n this.logger.info(`🖥️ PTY resized to fit terminal: ${cols}x${rows}`);\n } catch (error) {\n this.logger.warn('Failed to detect terminal size, using defaults:', error as Error);\n // Fallback to common terminal size\n this.resizePty(80, 24);\n }\n }\n}\n","/**\n * Claude Code Agent\n *\n * Concrete implementation of BaseAgent for Claude Code.\n * Handles Claude-specific operations including:\n * - Launching Claude Code with appropriate arguments\n * - Managing Claude Code processes and sessions\n * - Parsing Claude Code output and errors\n * - Handling Claude-specific commands\n */\n\nimport {\n AGENT_STATUS,\n AGENT_TYPES,\n type AgentSessionMessageInputRequestEvent,\n type DaemonStartAgentRequestEvent,\n} from '@agimonai/universal-agent-events';\nimport fs from 'fs';\nimport fsPromises from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\nimport stripAnsi from 'strip-ansi';\nimport { ENV_KEYS, SubEnvManager } from '../config/subenv';\nimport { FileSystemUtils } from '../utils/fileSystem';\nimport { AgentInfo, BaseAgent, BaseAgentOptions } from './base';\n\nexport interface ClaudeCodeOptions extends BaseAgentOptions {\n claudePath?: string;\n}\n\nexport class ClaudeAgent extends BaseAgent {\n private claudePath: string;\n private claudeArgs: string[] = [];\n\n // Track whether the interactive input area (\"box input\") has appeared\n private agentInputReady = false;\n // Startup commands provided via agentConfig.commands\n private startupCommands: string[] = [];\n private startupCommandsExecuted = false;\n // Path to generated MCP config file (if any)\n private tempMcpConfigPath: string | null = null;\n // Path to temporary project MCP config file (if any)\n private tempProjectMcpConfigPath: string | null = null;\n // Path to temporary settings file (if any)\n private tempSettingsPath: string | null = null;\n // Claude Code version info\n private claudeVersion: string | null = null;\n private supportsSettingsFlag = false;\n // Ctrl+C handling for graceful exit\n private ctrlCCount = 0;\n private ctrlCTimeout: NodeJS.Timeout | null = null;\n private readonly CTRL_C_RESET_MS = 2000; // Reset Ctrl+C count after 2 seconds\n // Complex input detection for optimistic ESC handling\n private complexInputDetected = false;\n // Whitelist of simple keyboard commands that don't trigger complex input\n private readonly KEYBOARD_WHITELIST = new Set([\n '\\r', // Enter\n '\\n', // Newline\n '\\x1b[A', // Arrow Up\n '\\x1b[B', // Arrow Down\n '\\x1b[C', // Arrow Right\n '\\x1b[D', // Arrow Left\n '\\t', // Tab\n '\\x7f', // Backspace\n '\\x03', // Ctrl+C\n '\\x04', // Ctrl+D\n ]);\n\n constructor(options: ClaudeCodeOptions) {\n super({\n ...options,\n agentType: AGENT_TYPES.CLAUDE_CODE,\n });\n\n this.claudePath = options.claudePath || 'claude';\n }\n\n /**\n * Detect if using Claude binary or npm package.\n *\n * IMPORTANT: Native binaries (Mach-O executables compiled with Bun) do NOT support\n * NODE_OPTIONS environment variable for security reasons. This means hooks cannot be\n * injected via --require or --preload flags.\n *\n * SOLUTION: When a native binary is detected, we automatically switch to using\n * `npx -y @anthropic-ai/claude-code` which runs as a Node.js process and supports\n * NODE_OPTIONS, allowing hooks to work properly.\n *\n * Detection logic:\n * 1. Check if the binary is a Mach-O executable (native binary)\n * 2. Check if it's a Node.js script (npm package)\n * 3. Default to npm package via npx for maximum compatibility\n *\n * @returns Object with command and args\n */\n private detectClaudeType(): { command: string; args: string[] } {\n const { execSync } = require('child_process');\n\n try {\n // Try to get the path to claude binary\n const claudePath = execSync(`which ${this.claudePath}`, { encoding: 'utf-8' }).trim();\n\n // Check if it's a Bun standalone binary (Mach-O)\n try {\n const fileType = execSync(`file \"${claudePath}\"`, { encoding: 'utf-8' });\n if (fileType.includes('Mach-O') || fileType.includes('executable')) {\n this.logger.info(`Detected standalone binary at ${claudePath}`);\n this.logger.info('Using npx @anthropic-ai/claude-code instead to enable hooks');\n return { command: 'npx', args: ['-y', '@anthropic-ai/claude-code'] };\n }\n } catch {\n // file command failed, continue\n }\n\n // Check if it's a npm package (contains 'node' or 'npx' in shebang)\n try {\n const content = fs.readFileSync(claudePath, 'utf-8');\n if (content.startsWith('#!/usr/bin/env node') || content.includes('npx')) {\n this.logger.info(`Detected npm package script at ${claudePath}`);\n return { command: this.claudePath, args: [] };\n }\n } catch {\n // Read failed, assume binary and use npx\n }\n\n // Default: Use npx for native binaries\n this.logger.info('Using npx @anthropic-ai/claude-code to enable hooks');\n return { command: 'npx', args: ['-y', '@anthropic-ai/claude-code'] };\n } catch {\n // Claude binary not found, use npm package\n this.logger.info('Claude binary not found, using npx @anthropic-ai/claude-code');\n return { command: 'npx', args: ['-y', '@anthropic-ai/claude-code'] };\n }\n }\n\n /**\n * Check if a command is a simple keyboard input (whitelisted)\n * Simple inputs include: numbers, escape sequences, arrows, tab, etc.\n */\n private isSimpleKeyboardInput(input: string): boolean {\n // Check if input is in whitelist\n if (this.KEYBOARD_WHITELIST.has(input)) {\n return true;\n }\n\n // Check if input starts with a number (0-9)\n if (/^[0-9]/.test(input)) {\n return true;\n }\n\n // Check if input is an escape sequence\n if (input.startsWith('\\x1b')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Detect complex input patterns in Claude Code output\n * Complex inputs include: prompts, menus, selection dialogs, etc.\n */\n private detectComplexInputPattern(data: string): boolean {\n const cleaned = stripAnsi(data);\n\n // Patterns that indicate complex input mechanisms\n const complexPatterns: RegExp[] = [\n /select|choose|pick/i, // Selection prompts\n /\\[[ x]\\]\\s+.*\\s+\\[[ x]\\]/i, // Multiple choice indicators (e.g., \"[x] Option 1 [ ] Option 2\")\n />\\s*\\[\\s*\\]/i, // Checkbox patterns\n /\\(\\s*\\)\\s*\\[\\s*\\]/i, // Radio button patterns\n /press.*to/i, // \"Press X to Y\" prompts\n /enter.*select/i, // \"Enter to select\" prompts\n /use.*arrows/i, // Arrow key navigation hints\n /space.*to.*select/i, // Space bar selection hints\n ];\n\n return complexPatterns.some((pattern) => pattern.test(cleaned));\n }\n\n /**\n * Optimistically send ESC to exit complex input if detected\n * This allows users to interact with Claude properly from both terminal and remote UI\n */\n private async handleComplexInputEscape(): Promise<void> {\n if (!this.complexInputDetected) {\n return;\n }\n\n this.logger.debug('Complex input detected, sending ESC to exit...');\n\n // Send ESC key to exit complex input mode\n await this.sendInputToAgent('\\x1b');\n\n // Reset detection flag after sending ESC\n this.complexInputDetected = false;\n\n // Small delay to allow Claude to process ESC\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n /**\n * Detect when the agent's interactive input box becomes available.\n * We look for common textual / box‑drawing indicators that the prompt\n * area is ready (heuristic patterns). Fires only once per session.\n */\n private verifyAgentReady(data: string): void {\n // Check for complex input patterns even if agent is already ready\n const hasComplexInput = this.detectComplexInputPattern(data);\n if (hasComplexInput && !this.complexInputDetected) {\n this.complexInputDetected = true;\n this.logger.debug('Complex input pattern detected in Claude Code output');\n }\n\n if (this.agentInputReady) return;\n\n const cleaned = stripAnsi(data);\n // Heuristic patterns that may indicate the input box / prompt is ready\n const patterns: RegExp[] = [\n /Type (your )?(message|prompt)/i,\n /Enter (your )?(message|prompt)/i,\n /Press Enter to send/i,\n // Box drawing multi-line prompt areas (╭ ... ╰ or ┌ ... └)\n /╭[\\s\\S]*?╰/m,\n /┌[\\s\\S]*?└/m,\n ];\n\n const isReady = patterns.some((p) => p.test(cleaned));\n if (!isReady) return;\n\n this.agentInputReady = true;\n\n // Send internal status only; per request we do NOT emit a readiness message to the session\n this.sendAgentStatus({\n agentType: AGENT_TYPES.CLAUDE_CODE,\n status: AGENT_STATUS.IDLE,\n message: 'Agent input box detected. Ready for commands.',\n });\n\n // Send session ready status to backend for deterministic frontend UI control\n void this.sendSessionReadyStatus();\n\n // Execute any configured startup commands once\n void this.executeStartupCommands();\n }\n\n /**\n * Send session ready status to backend API\n * This allows frontend to deterministically enable chat input\n */\n private async sendSessionReadyStatus(): Promise<void> {\n if (!this.agentInfo || !this.httpService) {\n return;\n }\n\n try {\n await this.httpService.sendAgentSessionReady(this.agentInfo.agentSessionId);\n this.logger.info('Session ready status sent to backend');\n } catch (error) {\n this.logger.warn('Failed to send session ready status', error as Error);\n // Non-critical error, continue without throwing\n }\n }\n\n /**\n * Override handleMessageInput to detect and handle complex input\n */\n protected async handleMessageInput(message: AgentSessionMessageInputRequestEvent): Promise<void> {\n const content = message.payload.content;\n\n // Check if this is a simple keyboard input\n const isSimple = this.isSimpleKeyboardInput(content);\n\n // If complex input was detected and current input is NOT a simple keyboard command,\n // optimistically send ESC to exit complex input mode\n if (this.complexInputDetected && !isSimple) {\n await this.handleComplexInputEscape();\n }\n\n // Call parent implementation to handle the actual input\n await super.handleMessageInput(message);\n }\n\n /**\n * Execute configured startup commands sequentially once the input box is ready.\n */\n private async executeStartupCommands(): Promise<void> {\n if (this.startupCommandsExecuted) return;\n if (!this.startupCommands.length) return;\n this.startupCommandsExecuted = true;\n\n for (const cmd of this.startupCommands) {\n try {\n await this.sendInputToAgent(`${cmd}\\r`);\n // Small delay to allow agent to process before next command\n await new Promise((r) => setTimeout(r, 250));\n } catch (err) {\n this.logger.warn(`Failed executing startup command: ${cmd}`, err as Error);\n }\n }\n }\n\n /**\n * Handle Ctrl+C (SIGINT) signals with double-press requirement\n * First Ctrl+C is used by Claude to clear input, second Ctrl+C exits\n */\n private handleCtrlC(): boolean {\n this.ctrlCCount++;\n\n // Clear any existing timeout\n if (this.ctrlCTimeout) {\n clearTimeout(this.ctrlCTimeout);\n }\n\n if (this.ctrlCCount === 1) {\n // Reset count after timeout\n this.ctrlCTimeout = setTimeout(() => {\n this.ctrlCCount = 0;\n this.ctrlCTimeout = null;\n }, this.CTRL_C_RESET_MS);\n\n // Don't exit on first Ctrl+C\n return false;\n } else if (this.ctrlCCount >= 2) {\n // Clear timeout\n if (this.ctrlCTimeout) {\n clearTimeout(this.ctrlCTimeout);\n this.ctrlCTimeout = null;\n }\n\n // Reset count\n this.ctrlCCount = 0;\n\n // Allow exit on second Ctrl+C\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if two MCP server configs have the same command and args\n */\n private isSameMcpCommand(\n config1: { command?: string; args?: string[] },\n config2: { command?: string; args?: string[] },\n ): boolean {\n if (!config1.command || !config2.command) return false;\n if (config1.command !== config2.command) return false;\n\n const args1 = config1.args || [];\n const args2 = config2.args || [];\n\n if (args1.length !== args2.length) return false;\n\n return args1.every((arg, index) => arg === args2[index]);\n }\n\n /**\n * Merge project MCP config with agent config, removing duplicates.\n * Returns merged config with project servers that don't duplicate agent servers.\n */\n private mergeProjectMcpConfig(projectMcpPath: string, agentMcps: any): Record<string, any> | null {\n try {\n // Read project MCP config\n if (!fs.existsSync(projectMcpPath)) {\n return null;\n }\n\n const projectConfigContent = fs.readFileSync(projectMcpPath, 'utf-8');\n const projectConfig = JSON.parse(projectConfigContent);\n\n if (!projectConfig.mcpServers || typeof projectConfig.mcpServers !== 'object') {\n return null;\n }\n\n // Normalize agent MCPs into record\n const agentMcpServers: Record<string, any> = {};\n if (Array.isArray(agentMcps)) {\n for (const item of agentMcps) {\n if (!item || typeof item !== 'object') continue;\n const name = item.name || item.id || item.key;\n if (!name) continue;\n agentMcpServers[name] = {\n type: item.type || 'stdio',\n command: item.command,\n args: item.args || item.arguments || [],\n url: item.url,\n env: item.env || {},\n disabled: item.disabled ?? false,\n headers: item.headers || {},\n };\n }\n } else if (typeof agentMcps === 'object' && agentMcps) {\n for (const [key, value] of Object.entries(agentMcps)) {\n if (value && typeof value === 'object') {\n agentMcpServers[key] = {\n ...value,\n headers: (value as any).headers || {},\n };\n }\n }\n }\n\n // Filter out project MCP servers that duplicate agent servers\n const mergedServers: Record<string, any> = {};\n const removedServers: string[] = [];\n\n for (const [serverName, serverConfig] of Object.entries(projectConfig.mcpServers)) {\n if (!serverConfig || typeof serverConfig !== 'object') continue;\n\n // Check if server name exists in agent config\n const hasDuplicateName = serverName in agentMcpServers;\n\n // Check if any agent MCP server has the same command and args\n const hasDuplicateCommand = Object.values(agentMcpServers).some((agentServer) =>\n this.isSameMcpCommand(serverConfig as any, agentServer),\n );\n\n if (hasDuplicateName || hasDuplicateCommand) {\n removedServers.push(serverName);\n const reason = hasDuplicateName ? 'duplicate name' : 'duplicate command/args';\n this.logger.info(`Removed duplicate MCP server '${serverName}' from project config (${reason})`);\n } else {\n mergedServers[serverName] = serverConfig;\n }\n }\n\n if (removedServers.length > 0) {\n this.logger.info(`Removed ${removedServers.length} duplicate MCP server(s): ${removedServers.join(', ')}`);\n }\n\n return Object.keys(mergedServers).length > 0 ? mergedServers : null;\n } catch (err) {\n this.logger.warn('Failed to merge project MCP config', err as Error);\n return null;\n }\n }\n\n /**\n * Write merged project MCP config to temporary file.\n * Clones project MCP config and removes duplicates with agent config.\n */\n private writeProjectMcpConfigFile(projectMcpPath: string, agentMcps: any, agentSessionId: string): string | null {\n try {\n const mergedServers = this.mergeProjectMcpConfig(projectMcpPath, agentMcps);\n\n if (!mergedServers) {\n return null;\n }\n\n // Write to temporary file\n const data = { mcpServers: mergedServers };\n const fileName = `claude-project-mcps-${agentSessionId}.json`;\n const filePath = path.join(os.tmpdir(), fileName);\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');\n\n this.logger.info(`Created temporary project MCP config at ${filePath}`);\n return filePath;\n } catch (err) {\n this.logger.warn('Failed to write project MCP config file', err as Error);\n return null;\n }\n }\n\n /**\n * Write MCP server configuration file to a temporary location.\n * Accepts various input shapes (array or record). Returns file path or null.\n */\n private writeMcpConfigFile(rawMcps: any, agentSessionId: string): string | null {\n if (!rawMcps) {\n return null;\n }\n\n try {\n // Normalize into record keyed by name\n const mcpServers: Record<string, any> = {};\n if (Array.isArray(rawMcps)) {\n for (const item of rawMcps) {\n if (!item || typeof item !== 'object') continue;\n const name = item.name || item.id || item.key;\n if (!name) continue;\n // Pick allowed fields including headers\n mcpServers[name] = {\n type: item.type || 'stdio',\n command: item.command,\n args: item.args || item.arguments || [],\n url: item.url,\n env: item.env || {},\n disabled: item.disabled ?? false,\n headers: item.headers || {},\n };\n }\n } else if (typeof rawMcps === 'object') {\n // Assume already in desired record shape – clone & ensure headers default\n for (const [key, value] of Object.entries(rawMcps)) {\n if (value && typeof value === 'object') {\n mcpServers[key] = {\n ...value,\n headers: (value as any).headers || {},\n };\n }\n }\n }\n\n if (Object.keys(mcpServers).length === 0) return null;\n\n // Ensure format matches required schema: { mcpServers: { ... } }\n const data = { mcpServers };\n const fileName = `claude-mcps-${agentSessionId}.json`;\n const filePath = path.join(os.tmpdir(), fileName);\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');\n this.tempMcpConfigPath = filePath;\n return filePath;\n } catch (err) {\n this.logger.warn('Failed to write MCP config file', err as Error);\n return null;\n }\n }\n\n /**\n * Discover Claude subagents from project and user directories\n */\n private async discoverSubagents(workingDir: string): Promise<string[]> {\n const subagents: string[] = [];\n\n try {\n // Project-level subagents (.claude/agents/ in working directory)\n const projectAgentsDir = path.join(workingDir, '.claude', 'agents');\n if (fs.existsSync(projectAgentsDir)) {\n const files = fs.readdirSync(projectAgentsDir);\n const projectAgents = files.filter((file) => file.endsWith('.md'));\n for (const agent of projectAgents) {\n const agentName = path.basename(agent, '.md');\n subagents.push(`${agentName} (project)`);\n }\n }\n\n // User-level subagents (~/.claude/agents/)\n const userAgentsDir = path.join(os.homedir(), '.claude', 'agents');\n if (fs.existsSync(userAgentsDir)) {\n const files = fs.readdirSync(userAgentsDir);\n const userAgents = files.filter((file) => file.endsWith('.md'));\n for (const agent of userAgents) {\n const agentName = path.basename(agent, '.md');\n // Only add if not already present from project level (project takes precedence)\n const projectAgentExists = subagents.some((sa) => sa.startsWith(`${agentName} (`));\n if (!projectAgentExists) {\n subagents.push(`${agentName} (user)`);\n }\n }\n }\n } catch (error) {\n this.logger.warn('Failed to discover subagents:', error as Error);\n }\n\n return subagents;\n }\n\n /**\n * Detect Claude Code version and check if --settings flag is supported\n */\n private async detectClaudeVersion(): Promise<void> {\n try {\n const { execSync } = await import('child_process');\n const versionOutput = execSync(`${this.claudePath} --version`, { encoding: 'utf-8' });\n const match = versionOutput.match(/(\\d+\\.\\d+\\.\\d+)/);\n\n if (match) {\n this.claudeVersion = match[1];\n const [major] = this.claudeVersion.split('.').map(Number);\n // --settings flag is available in version 2.0.0 and above\n this.supportsSettingsFlag = major >= 2;\n this.logger.info(\n `Detected Claude Code version ${this.claudeVersion} (--settings flag: ${this.supportsSettingsFlag})`,\n );\n }\n } catch (error) {\n this.logger.warn('Failed to detect Claude Code version, assuming legacy version', error as Error);\n this.supportsSettingsFlag = false;\n }\n }\n\n /**\n * Create temporary settings file with PreToolUse and PostToolUse hooks\n */\n private async createTempSettingsFile(agentSessionId: string): Promise<string | null> {\n try {\n // Find the PostToolUse hook file path\n const possiblePostToolUsePaths = [\n path.join(__dirname, '..', '..', 'dist', 'claudePostToolUse.js'),\n path.join(__dirname, '..', 'dist', 'claudePostToolUse.js'),\n path.join(__dirname, 'dist', 'claudePostToolUse.js'),\n path.join(process.cwd(), 'dist', 'claudePostToolUse.js'),\n ];\n\n let postToolUseHookPath: string | null = null;\n for (const candidatePath of possiblePostToolUsePaths) {\n if (fs.existsSync(candidatePath)) {\n postToolUseHookPath = candidatePath;\n break;\n }\n }\n\n if (!postToolUseHookPath) {\n this.logger.warn('PostToolUse hook file not found at any expected location');\n return null;\n }\n\n // Find the PreToolUse hook file path\n const possiblePreToolUsePaths = [\n path.join(__dirname, '..', '..', 'dist', 'claudePreToolUse.js'),\n path.join(__dirname, '..', 'dist', 'claudePreToolUse.js'),\n path.join(__dirname, 'dist', 'claudePreToolUse.js'),\n path.join(process.cwd(), 'dist', 'claudePreToolUse.js'),\n ];\n\n let preToolUseHookPath: string | null = null;\n for (const candidatePath of possiblePreToolUsePaths) {\n if (fs.existsSync(candidatePath)) {\n preToolUseHookPath = candidatePath;\n break;\n }\n }\n\n // Find the Notification hook file path\n const possibleNotificationPaths = [\n path.join(__dirname, '..', '..', 'dist', 'claudeNotification.js'),\n path.join(__dirname, '..', 'dist', 'claudeNotification.js'),\n path.join(__dirname, 'dist', 'claudeNotification.js'),\n path.join(process.cwd(), 'dist', 'claudeNotification.js'),\n ];\n\n let notificationHookPath: string | null = null;\n for (const candidatePath of possibleNotificationPaths) {\n if (fs.existsSync(candidatePath)) {\n notificationHookPath = candidatePath;\n break;\n }\n }\n\n // Find the SessionStart hook file path\n const possibleSessionStartPaths = [\n path.join(__dirname, '..', '..', 'dist', 'claudeSessionStart.js'),\n path.join(__dirname, '..', 'dist', 'claudeSessionStart.js'),\n path.join(__dirname, 'dist', 'claudeSessionStart.js'),\n path.join(process.cwd(), 'dist', 'claudeSessionStart.js'),\n ];\n\n let sessionStartHookPath: string | null = null;\n for (const candidatePath of possibleSessionStartPaths) {\n if (fs.existsSync(candidatePath)) {\n sessionStartHookPath = candidatePath;\n break;\n }\n }\n\n // Create settings object with SessionStart, PreToolUse, PostToolUse, and Notification hooks\n const settings = {\n hooks: {\n ...(sessionStartHookPath\n ? {\n SessionStart: [\n {\n matcher: 'startup',\n hooks: [\n {\n type: 'command',\n command: `node ${sessionStartHookPath}`,\n },\n ],\n },\n ],\n }\n : {}),\n ...(preToolUseHookPath\n ? {\n PreToolUse: [\n {\n matcher: '*',\n hooks: [\n {\n type: 'command',\n command: `node ${preToolUseHookPath}`,\n },\n ],\n },\n ],\n }\n : {}),\n PostToolUse: [\n {\n matcher: '*',\n hooks: [\n {\n type: 'command',\n command: `node ${postToolUseHookPath}`,\n },\n ],\n },\n ],\n ...(notificationHookPath\n ? {\n Notification: [\n {\n matcher: '*',\n hooks: [\n {\n type: 'command',\n command: `node ${notificationHookPath}`,\n },\n ],\n },\n ],\n }\n : {}),\n },\n };\n\n // Write to temporary file\n const fileName = `claude-settings-${agentSessionId}.json`;\n const filePath = path.join(os.tmpdir(), fileName);\n await fsPromises.writeFile(filePath, JSON.stringify(settings, null, 2), 'utf8');\n this.tempSettingsPath = filePath;\n this.logger.info(`Created temporary settings file at ${filePath}`);\n if (sessionStartHookPath) {\n this.logger.info('SessionStart hook enabled - session ready status will be sent on startup');\n }\n if (preToolUseHookPath) {\n this.logger.info('PreToolUse hook enabled - tool inputs will be logged for inspection');\n }\n if (notificationHookPath) {\n this.logger.info(\n 'Notification hook enabled - notifications will be logged to .claude-logs/notifications.jsonl',\n );\n }\n\n return filePath;\n } catch (error) {\n this.logger.error(`Failed to create temporary settings file: ${error}`);\n return null;\n }\n }\n\n /**\n * Add PostToolUse hook to Claude settings (legacy method for Claude Code < 2.0)\n */\n private async addPostToolUseHook(workingDir: string): Promise<void> {\n const settingsPath = path.join(workingDir, '.claude', 'settings.local.json');\n const settingsDir = path.dirname(settingsPath);\n\n try {\n // Ensure .claude directory exists\n await fsPromises.mkdir(settingsDir, { recursive: true });\n\n let settings: any = {};\n\n // Read existing settings if file exists\n try {\n const content = await fsPromises.readFile(settingsPath, 'utf-8');\n settings = JSON.parse(content);\n } catch (error) {\n // File doesn't exist or is invalid, start with empty settings\n this.logger.debug('No existing settings.local.json found, creating new one');\n }\n\n // Ensure hooks structure exists\n if (!settings.hooks) {\n settings.hooks = {};\n }\n if (!settings.hooks.PostToolUse) {\n settings.hooks.PostToolUse = [];\n }\n\n // Add our PostToolUse hook with matcher configuration\n // Find the actual dist directory since bundling changes directory structure\n let hookPath: string | null = null;\n\n // Try different potential locations for the dist folder\n const possibleDistPaths = [\n path.join(__dirname, '..', '..', 'dist', 'claudePostToolUse.js'), // Development structure\n path.join(__dirname, '..', 'dist', 'claudePostToolUse.js'), // One level up\n path.join(__dirname, 'dist', 'claudePostToolUse.js'), // Same level\n path.join(process.cwd(), 'dist', 'claudePostToolUse.js'), // From current working directory\n ];\n\n for (const candidatePath of possibleDistPaths) {\n if (fs.existsSync(candidatePath)) {\n hookPath = candidatePath;\n break;\n }\n }\n\n if (!hookPath) {\n this.logger.warn('PostToolUse hook file not found at any expected location');\n return; // Skip adding hook if file doesn't exist\n }\n const ourHook = {\n matcher: '*', // Match all tools\n hooks: [\n {\n type: 'command',\n command: `node ${hookPath}`,\n },\n ],\n };\n\n // Check if our hook is already present\n const hookExists = settings.hooks.PostToolUse.some((hook: any) => {\n if (hook.hooks && Array.isArray(hook.hooks)) {\n return hook.hooks.some((h: any) => h.type === 'command' && h.command === `node ${hookPath}`);\n }\n return false;\n });\n\n if (!hookExists) {\n settings.hooks.PostToolUse.push(ourHook);\n await fsPromises.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n this.logger.info(`Added PostToolUse hook to ${settingsPath}`);\n }\n } catch (error) {\n this.logger.error(`Failed to add PostToolUse hook: ${error}`);\n // Non-critical error, continue without hook\n }\n }\n\n /**\n * Remove PostToolUse hook from Claude settings\n */\n private async removePostToolUseHook(workingDir: string): Promise<void> {\n const settingsPath = path.join(workingDir, '.claude', 'settings.local.json');\n\n try {\n // Check if settings file exists\n const content = await fsPromises.readFile(settingsPath, 'utf-8');\n const settings = JSON.parse(content);\n\n if (settings.hooks?.PostToolUse) {\n // Find the actual dist directory since bundling changes directory structure\n let hookPath: string | null = null;\n\n // Try different potential locations for the dist folder\n const possibleDistPaths = [\n path.join(__dirname, '..', '..', 'dist', 'claudePostToolUse.js'), // Development structure\n path.join(__dirname, '..', 'dist', 'claudePostToolUse.js'), // One level up\n path.join(__dirname, 'dist', 'claudePostToolUse.js'), // Same level\n path.join(process.cwd(), 'dist', 'claudePostToolUse.js'), // From current working directory\n ];\n\n for (const candidatePath of possibleDistPaths) {\n if (fs.existsSync(candidatePath)) {\n hookPath = candidatePath;\n break;\n }\n }\n\n if (!hookPath) {\n return; // Skip removal if file doesn't exist\n }\n\n const hookCommand = `node ${hookPath}`;\n\n // Filter out our hook\n settings.hooks.PostToolUse = settings.hooks.PostToolUse.filter((hook: any) => {\n if (hook.hooks && Array.isArray(hook.hooks)) {\n // Remove our specific command from the hooks array\n hook.hooks = hook.hooks.filter((h: any) => !(h.type === 'command' && h.command === hookCommand));\n // Keep the matcher entry only if it has other hooks\n return hook.hooks.length > 0;\n }\n return true;\n });\n\n // Clean up empty structures\n if (settings.hooks.PostToolUse.length === 0) {\n delete settings.hooks.PostToolUse;\n }\n if (Object.keys(settings.hooks).length === 0) {\n delete settings.hooks;\n }\n\n // Write back the settings\n await fsPromises.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n this.logger.info(`Removed PostToolUse hook from ${settingsPath}`);\n }\n } catch (error) {\n // File might not exist or be invalid, which is fine\n this.logger.debug(`Could not remove PostToolUse hook: ${error}`);\n }\n }\n\n /**\n * Write session settings to ~/.agiflow/sessions.json for dynamic routing\n */\n private writeSessionSettings(\n sessionId: string,\n provider?: string,\n model?: string,\n alias?: string,\n reasoningEffort?: string,\n ): void {\n try {\n const agiflowDir = path.join(os.homedir(), '.agiflow');\n const sessionsFile = path.join(agiflowDir, 'sessions.json');\n\n // Ensure .agiflow directory exists\n if (!fs.existsSync(agiflowDir)) {\n fs.mkdirSync(agiflowDir, { recursive: true });\n }\n\n // Load existing sessions or create new object\n let sessions: Record<string, any> = {};\n if (fs.existsSync(sessionsFile)) {\n try {\n sessions = JSON.parse(fs.readFileSync(sessionsFile, 'utf-8'));\n } catch {\n // Invalid JSON, start fresh\n this.logger.warn('Invalid sessions.json, creating new one');\n }\n }\n\n // Write session settings (with or without provider/model)\n sessions[sessionId] = {\n ...(provider && { provider }),\n ...(model && { model }),\n ...(alias && { alias }),\n ...(reasoningEffort && { reasoningEffort }),\n };\n\n fs.writeFileSync(sessionsFile, JSON.stringify(sessions, null, 2), 'utf-8');\n this.logger.info(`Session settings written to ${sessionsFile}`);\n if (provider && model) {\n this.logger.info(`Session: ${alias || sessionId} (${provider}/${model})`);\n } else {\n this.logger.info(`Session: ${alias || sessionId} (default Claude)`);\n }\n } catch (err) {\n this.logger.error('Failed to write session settings', err as Error);\n }\n }\n\n /**\n * Launch Claude Code agent\n */\n async launchAgent(request: DaemonStartAgentRequestEvent): Promise<AgentInfo> {\n const { payload } = request;\n const agentSessionId = payload.agentSessionId;\n const workingDir = payload.agentConfig?.workingDirectory\n ? FileSystemUtils.getAbsolutePath(payload.agentConfig.workingDirectory)\n : process.cwd();\n // Capture startup commands early\n this.startupCommands = payload.agentConfig?.commands ?? [];\n this.startupCommandsExecuted = false;\n // Check if xterm is enabled\n const xtermEnabled = payload.agentConfig?.xterm ?? false;\n this.setXtermEnabled(xtermEnabled);\n\n // Write session settings - always initialize even without LLM routing\n const llmConfig = payload.agentConfig?.llmConfig;\n const sessionAlias = payload.agentConfig?.sessionAlias;\n\n if (llmConfig?.provider) {\n // LLM routing configured\n this.writeSessionSettings(\n agentSessionId,\n llmConfig.provider,\n llmConfig.model || 'default',\n sessionAlias,\n undefined, // reasoningEffort can be added later if needed\n );\n } else {\n // No LLM routing - create session entry with alias only\n this.writeSessionSettings(agentSessionId, undefined, undefined, sessionAlias, undefined);\n }\n\n // Detect if Claude is a native binary or npm package\n // Native binaries don't support NODE_OPTIONS, so we need to use npx to enable hooks\n const { command, args: detectedArgs } = this.detectClaudeType();\n this.claudePath = command;\n this.claudeArgs = detectedArgs;\n\n // Detect Claude Code version and capabilities\n await this.detectClaudeVersion();\n\n // Execute pre-agent start hooks (will use defaults if none provided)\n // Support both preAgentStart and preAgentStartHooks property names for backward compatibility\n const userHooks = payload.agentConfig?.hooks?.preAgentStartHooks || payload.agentConfig?.hooks?.preAgentStart;\n await this.executePreAgentStartHooks(userHooks, workingDir, agentSessionId);\n\n // When running inside Docker container, enable fullscreen mode for terminal output\n // Docker containers have a single PTY session that should always stream to frontend\n const isInsideDocker = SubEnvManager.isContainerMode;\n if (isInsideDocker && xtermEnabled) {\n this.setFullscreen(true);\n }\n\n // Setup PostToolUse hook based on Claude Code version (only if server URL is provided)\n if (this.serverUrl) {\n if (this.supportsSettingsFlag) {\n // Claude Code >= 2.0: Create temporary settings file\n await this.createTempSettingsFile(agentSessionId);\n } else {\n // Legacy Claude Code < 2.0: Modify local settings file\n await this.addPostToolUseHook(workingDir);\n }\n } else {\n this.logger.info('Running in standalone mode - PostToolUse hook will not be configured');\n }\n\n // Discover available subagents\n const subagents = await this.discoverSubagents(workingDir);\n if (subagents.length > 0) {\n this.logger.info(`Discovered ${subagents.length} Claude subagent(s): ${subagents.join(', ')}`);\n }\n\n const mcpConfigPath = this.writeMcpConfigFile(payload.agentConfig?.mcps, agentSessionId);\n // Detect project-level MCP config (.mcp.json) in working directory\n const projectMcpConfigPath = path.join(workingDir, '.mcp.json');\n\n // Create merged project MCP config file (removes duplicates with agent config)\n const mergedProjectMcpConfigPath = this.writeProjectMcpConfigFile(\n projectMcpConfigPath,\n payload.agentConfig?.mcps,\n agentSessionId,\n );\n if (mergedProjectMcpConfigPath) {\n this.tempProjectMcpConfigPath = mergedProjectMcpConfigPath;\n }\n\n // Connect to agent session WebSocket (only in daemon mode with serverUrl)\n if (this.serverUrl) {\n await this.connectToSession(agentSessionId);\n } else {\n this.logger.info('Running in standalone mode - skipping WebSocket connection');\n }\n\n // Setup Docker repository if Docker mode is enabled\n await this.setupDockerRepository(request);\n\n // Build Claude Code arguments\n const args = this.buildClaudeArgs(request);\n\n // Append MCP config flag if any config files exist\n const mcpConfigFiles: string[] = [];\n\n // Use merged project config if available, otherwise use original\n if (mergedProjectMcpConfigPath) {\n mcpConfigFiles.push(mergedProjectMcpConfigPath);\n } else if (fs.existsSync(projectMcpConfigPath)) {\n mcpConfigFiles.push(projectMcpConfigPath);\n }\n\n if (mcpConfigPath) {\n mcpConfigFiles.push(mcpConfigPath);\n }\n if (mcpConfigFiles.length) {\n args.push('--mcp-config', ...mcpConfigFiles);\n }\n\n try {\n // Get environment variables for the agent\n const agentEnv = this.getAgentEnvironmentVariables();\n\n // Configure NODE_OPTIONS with network logging hook\n const nodeOptions = this.configureNodeOptions(agentEnv);\n\n // Set up SIGINT handler for double Ctrl+C requirement\n const originalSigintHandlers = process.listeners('SIGINT');\n const sigintHandler = () => {\n const shouldExit = this.handleCtrlC();\n if (shouldExit) {\n this.logger.info('Double Ctrl+C detected, terminating Claude agent...');\n // Restore original handlers and exit\n process.removeListener('SIGINT', sigintHandler);\n originalSigintHandlers.forEach((handler) => {\n if (typeof handler === 'function') {\n process.on('SIGINT', handler);\n }\n });\n // Kill the PTY process\n this.ptyRunner.kill('SIGINT');\n } else {\n // First Ctrl+C - send to Claude to clear input\n this.ptyRunner.sendInput('\\x03'); // Send Ctrl+C to Claude\n }\n };\n\n // Replace SIGINT handler\n process.removeAllListeners('SIGINT');\n process.on('SIGINT', sigintHandler);\n\n // Launch Claude Code using PtyRunnerService\n const ptySession = this.ptyRunner.spawn(\n {\n command: this.claudePath,\n args,\n workingDir,\n agentSessionId,\n logger: this.logger,\n // Pass agent environment variables\n agentApiKey: this.apiKey,\n agentOrganizationId: this.organizationId,\n agentServerUrl: this.serverUrl,\n agentType: this.agentType,\n env: {\n ...agentEnv,\n NODE_OPTIONS: nodeOptions,\n [ENV_KEYS.AGENT_SESSION_ID]: agentSessionId,\n [ENV_KEYS.AGENT_TYPE]: this.agentType,\n ...(mcpConfigPath ? { CLAUDE_MCP_CONFIG_FILE: mcpConfigPath } : {}),\n ...(payload.data ? { [ENV_KEYS.CONTEXT_DATA]: payload.data } : {}),\n },\n },\n {\n onExit: async (exitCode, signal) => {\n // Restore original SIGINT handlers when PTY exits\n process.removeListener('SIGINT', sigintHandler);\n originalSigintHandlers.forEach((handler) => {\n if (typeof handler === 'function') {\n process.on('SIGINT', handler);\n }\n });\n\n // Clean up Ctrl+C timeout\n if (this.ctrlCTimeout) {\n clearTimeout(this.ctrlCTimeout);\n this.ctrlCTimeout = null;\n }\n\n // Clean up PostToolUse hook based on mode (only if it was created)\n if (this.serverUrl) {\n if (this.supportsSettingsFlag) {\n // Claude Code >= 2.0: Remove temporary settings file\n if (this.tempSettingsPath) {\n try {\n fs.unlinkSync(this.tempSettingsPath);\n this.logger.info(`Removed temporary settings file: ${this.tempSettingsPath}`);\n } catch (e) {\n this.logger.warn('Failed to delete temp settings file', e as Error);\n }\n this.tempSettingsPath = null;\n }\n } else {\n // Legacy Claude Code < 2.0: Remove hook from local settings\n await this.removePostToolUseHook(workingDir);\n }\n }\n\n // Remove temp MCP config file\n if (this.tempMcpConfigPath) {\n try {\n fs.unlinkSync(this.tempMcpConfigPath);\n } catch (e) {\n this.logger.warn('Failed to delete temp MCP config file', e as Error);\n }\n this.tempMcpConfigPath = null;\n }\n\n // Remove temp project MCP config file\n if (this.tempProjectMcpConfigPath) {\n try {\n fs.unlinkSync(this.tempProjectMcpConfigPath);\n this.logger.info(`Removed temporary project MCP config file: ${this.tempProjectMcpConfigPath}`);\n } catch (e) {\n this.logger.warn('Failed to delete temp project MCP config file', e as Error);\n }\n this.tempProjectMcpConfigPath = null;\n }\n\n this.logger.info(`Claude Code PTY exited with code ${exitCode}, signal: ${signal}`);\n\n // Note: stdin cleanup is handled by daemon when PTY exits\n\n // Send final status\n this.sendAgentStatus({\n agentType: AGENT_TYPES.CLAUDE_CODE,\n status: exitCode === 0 ? AGENT_STATUS.STOPPED : AGENT_STATUS.ERROR,\n message: `Claude Code session ended (exit code: ${exitCode})`,\n });\n\n // Clean up WebSocket connection when PTY exits naturally\n if (this.wsService) {\n this.wsService.disconnect();\n }\n this.ptySessionId = null;\n\n // Notify TerminationService about natural PTY termination\n if (this.agentInfo) {\n await this.terminationService.handlePtyTermination({\n agentSessionId: this.agentInfo.agentSessionId,\n reason: signal === 2 ? 'agent_sigint' : 'natural',\n exitCode,\n signal: signal as NodeJS.Signals | undefined,\n });\n }\n },\n onData: async (data) => {\n // Detect readiness of the input box\n this.verifyAgentReady(data);\n // Send stdout event if xterm is enabled\n if (this.xtermEnabled) {\n this.sendStdoutEvent(data);\n }\n },\n },\n );\n\n this.logger.success(`Claude Code launched successfully for session agentSessionId: ${agentSessionId}`);\n\n // Store PTY session ID for termination handling\n this.ptySessionId = ptySession.id;\n\n // Setup initial PTY size if xterm is not enabled to fit terminal\n if (!xtermEnabled) {\n this.setupInitialPtySize();\n } else {\n this.resizePty(80, 24);\n }\n\n // Create and return AgentInfo\n const agentInfo: AgentInfo = {\n agentSessionId: agentSessionId,\n agentType: AGENT_TYPES.CLAUDE_CODE,\n status: AGENT_STATUS.IDLE,\n workingDir: workingDir,\n process: ptySession.ptyProcess,\n metadata: {\n agentSessionId: agentSessionId,\n agentType: payload.agentType,\n config: payload.agentConfig,\n ptySessionId: ptySession.id,\n },\n };\n this.setAgentInfo(agentInfo);\n return agentInfo;\n } catch (error) {\n throw new Error(`Failed to launch Claude Code: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Check if Claude Code is available\n */\n async isAvailable(): Promise<boolean> {\n // For PTY-based agents, we assume availability\n // Real availability check would require spawning the process\n return true;\n }\n\n /**\n * Get Claude Code version\n */\n async getVersion(): Promise<string | null> {\n // Version info would need to be obtained through PTY interaction\n return 'claude-pty-agent';\n }\n\n /**\n * Build Claude Code command arguments\n */\n private buildClaudeArgs(request: DaemonStartAgentRequestEvent): string[] {\n // Start with detected args (e.g., ['-y', '@anthropic-ai/claude-code'] for npx)\n const claudeArgs: string[] = [...this.claudeArgs, ...(request.payload?.agentConfig?.args || [])];\n\n // Add session-id flag if conversationSessionId is provided\n const conversationSessionId = request.payload?.agentConfig?.conversationSessionId;\n if (conversationSessionId) {\n claudeArgs.push('--session-id', conversationSessionId);\n }\n\n // Add settings flag if supported and temp settings file was created\n if (this.supportsSettingsFlag && this.tempSettingsPath) {\n claudeArgs.push('--settings', this.tempSettingsPath);\n }\n\n // Note: AGENT_API_KEY is passed via environment variables in the env object\n // rather than CLI flags since Claude Code doesn't support --env option\n\n return claudeArgs;\n }\n}\n","/**\n * Docker Runner Service\n *\n * Centralized service for managing Docker containers for agent execution.\n * Handles spawning, I/O, and cleanup for containerized Claude agents.\n * Follows the same pattern as PtyRunnerService but for Docker containers.\n */\n\nimport { ChildProcess, spawn } from 'child_process';\nimport * as fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport { ulid } from 'ulidx';\nimport { ENV_KEYS, SubEnvManager } from '../config/subenv';\nimport { Logger } from '../utils/logger';\n\nexport interface DockerOptions {\n agentSessionId?: string;\n dockerImage?: string;\n workingDir?: string;\n logStream?: fs.WriteStream;\n logger?: Logger;\n // Agent-specific environment variables\n agentApiKey?: string;\n agentOrganizationId?: string;\n agentServerUrl?: string;\n agentApiUrl?: string;\n agentType?: string;\n // Agent configuration as JSON string\n agentConfig?: string;\n args?: string[];\n verbose?: boolean;\n // Additional Docker options\n additionalVolumes?: Array<{ host: string; container: string; readonly?: boolean; type?: 'bind' | 'volume' }>;\n additionalEnvVars?: Record<string, string>;\n networkMode?: string;\n ports?: Array<{ host: number; container: number }>;\n privileged?: boolean;\n user?: string;\n}\n\nexport interface DockerCallbacks {\n onData?: (data: string) => void;\n onExit?: (exitCode: number, signal?: number) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface DockerSession {\n id: string;\n dockerProcess: ChildProcess;\n containerId: string;\n command: string;\n workingDir: string;\n status: 'running' | 'stopped' | 'error';\n createdAt: Date;\n lastActivity: Date;\n logStream?: fs.WriteStream;\n metadata?: Record<string, any>;\n tempMcpConfigPath?: string;\n}\n\nexport class DockerRunnerService {\n private session!: DockerSession;\n private logger: Logger;\n\n constructor(logger?: Logger) {\n this.logger = logger ?? new Logger({ verbose: false });\n }\n\n /**\n * Check if Docker is available on the system\n */\n async isDockerAvailable(): Promise<boolean> {\n return new Promise((resolve) => {\n const docker = spawn('docker', ['--version'], { stdio: 'pipe' });\n\n docker.on('close', (code) => {\n resolve(code === 0);\n });\n\n docker.on('error', () => {\n resolve(false);\n });\n });\n }\n\n /**\n * Spawn a Docker container\n */\n spawn(options: DockerOptions, callbacks?: DockerCallbacks): DockerSession {\n const agentSessionId = options.agentSessionId || ulid();\n const workingDir = options.workingDir ?? process.cwd();\n const dockerImage = options.dockerImage || 'agiflow/claude-agent:latest';\n\n // Build Docker run command\n const dockerArgs = this.buildDockerArgs(agentSessionId, options, dockerImage);\n const fullCommand = `docker ${dockerArgs.join(' ')}`;\n\n this.logger.info(`🐳 Docker Command: ${fullCommand}`);\n this.logger.debug('Spawning Docker container with args:', dockerArgs);\n\n // Spawn Docker container\n const dockerProcess = spawn('docker', dockerArgs, {\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n const containerId = `claude-agent-${agentSessionId}`;\n\n // Create session object\n const session: DockerSession = {\n id: agentSessionId,\n dockerProcess,\n containerId,\n command: `docker ${dockerArgs.join(' ')}`,\n workingDir,\n status: 'running',\n createdAt: new Date(),\n lastActivity: new Date(),\n logStream: options.logStream,\n };\n\n // Handle Docker container output\n dockerProcess.stdout?.on('data', (data) => {\n session.lastActivity = new Date();\n\n const dataStr = data.toString();\n\n // Log raw data to file if stream provided\n if (session.logStream) {\n session.logStream.write(dataStr);\n }\n\n // Write to stdout so user can see output\n process.stdout.write(dataStr);\n\n // Invoke callback with raw data if provided\n if (callbacks?.onData) {\n callbacks.onData(dataStr);\n }\n });\n\n dockerProcess.stderr?.on('data', (data) => {\n const dataStr = data.toString();\n this.logger.error(`🐳 Container ${containerId} stderr: ${dataStr.trim()}`);\n // Also write stderr to process.stderr so it's visible\n process.stderr.write(dataStr);\n });\n\n // Handle Docker container exit\n dockerProcess.on('close', (code) => {\n session.status = code === 0 ? 'stopped' : 'error';\n session.lastActivity = new Date();\n\n this.logger.info(`Container ${containerId} exited with code ${code}`);\n\n // Close log stream\n if (session.logStream) {\n session.logStream.end();\n }\n\n // Invoke exit callback\n if (callbacks?.onExit) {\n callbacks.onExit(code || 0, undefined);\n }\n });\n\n dockerProcess.on('error', (error) => {\n session.status = 'error';\n this.logger.error(`Container ${containerId} error:`, error);\n\n if (callbacks?.onError) {\n callbacks.onError(error);\n }\n });\n\n this.session = session;\n\n return session;\n }\n\n /**\n * Build Docker run arguments\n */\n private buildDockerArgs(agentSessionId: string, options: DockerOptions, dockerImage: string): string[] {\n const containerId = `claude-agent-${agentSessionId}`;\n\n const args = [\n 'run',\n '--rm',\n '--name',\n containerId,\n '-i', // Interactive mode (removed -t to avoid TTY issues with pipes)\n ];\n\n // Security and user options\n if (options.privileged) {\n args.push('--privileged');\n }\n // Only set user if explicitly provided, otherwise use the USER from Dockerfile (node)\n if (options.user) {\n args.push('--user', options.user);\n }\n\n // Network configuration\n if (options.networkMode) {\n args.push('--network', options.networkMode);\n }\n\n // Port mappings\n if (options.ports && options.ports.length > 0) {\n for (const port of options.ports) {\n args.push('-p', `${port.host}:${port.container}`);\n }\n }\n\n // Standard environment variables\n // Use SubEnvManager for environment variables\n const serverUrl = options.agentServerUrl || SubEnvManager.serverUrl;\n if (serverUrl) {\n args.push('-e', `${ENV_KEYS.AGENT_SERVER_URL}=${serverUrl}`);\n }\n\n const apiKey = options.agentApiKey || SubEnvManager.apiKey;\n if (apiKey) {\n args.push('-e', `${ENV_KEYS.AGENT_API_KEY}=${apiKey}`);\n }\n\n const orgId = options.agentOrganizationId || SubEnvManager.organizationId;\n if (orgId) {\n args.push('-e', `${ENV_KEYS.AGENT_ORGANIZATION_ID}=${orgId}`);\n }\n\n const agentType = options.agentType || SubEnvManager.agentType;\n if (agentType) {\n args.push('-e', `${ENV_KEYS.AGENT_TYPE}=${agentType}`);\n }\n\n const sessionId = agentSessionId || SubEnvManager.sessionId;\n if (sessionId) {\n args.push('-e', `${ENV_KEYS.AGENT_SESSION_ID}=${sessionId}`);\n }\n\n // Additional environment variables\n if (options.additionalEnvVars) {\n for (const [key, value] of Object.entries(options.additionalEnvVars)) {\n args.push('-e', `${key}=${value}`);\n }\n }\n\n // Standard volume mounts\n if (options.workingDir) {\n args.push('-v', `${options.workingDir}:/workspace`);\n args.push('-w', '/workspace');\n }\n\n // Mount credentials directory so container can access stored API keys\n const credentialsDir = path.join(os.homedir(), '.agiflow');\n if (fs.existsSync(credentialsDir)) {\n // Mount to /home/node/.agiflow since the Docker container runs as node user\n args.push('-v', `${credentialsDir}:/home/node/.agiflow:ro`);\n this.logger.debug(`Mounting credentials directory: ${credentialsDir} -> /home/node/.agiflow`);\n } else {\n this.logger.warn(`Credentials directory not found at: ${credentialsDir}`);\n }\n\n // Additional volume mounts\n if (options.additionalVolumes && options.additionalVolumes.length > 0) {\n for (const volume of options.additionalVolumes) {\n let mountStr: string;\n\n if (volume.type === 'volume') {\n // Named volume mount - Docker will create and manage the volume\n mountStr = volume.readonly ? `${volume.host}:${volume.container}:ro` : `${volume.host}:${volume.container}`;\n this.logger.debug(`Mounting named volume: ${volume.host} -> ${volume.container}`);\n } else {\n // Bind mount (default behavior) - mount host path to container path\n mountStr = volume.readonly ? `${volume.host}:${volume.container}:ro` : `${volume.host}:${volume.container}`;\n this.logger.debug(`Mounting bind volume: ${volume.host} -> ${volume.container}`);\n }\n\n args.push('-v', mountStr);\n }\n }\n\n // Mount host's Docker socket for development (if needed)\n if (SubEnvManager.isDebugMode) {\n args.push('-v', '/var/run/docker.sock:/var/run/docker.sock');\n }\n\n // Image name\n args.push(dockerImage);\n\n // Add the claude subcommand (this was missing!)\n args.push('claude');\n\n // Claude command arguments\n if (serverUrl) {\n args.push('--server-url', serverUrl);\n }\n if (options.agentApiUrl) {\n args.push('--api-url', options.agentApiUrl);\n }\n if (apiKey) {\n args.push('--api-key', apiKey);\n }\n if (orgId) {\n args.push('--organization-id', orgId);\n }\n // Note: --agent-type is not recognized by the Docker entry point\n // The agent type is already passed via environment variable AGENT_TYPE\n if (sessionId) {\n args.push('--agent-session-id', sessionId);\n }\n if (options.workingDir) {\n args.push('--working-directory', '/workspace');\n }\n if (options.agentConfig) {\n // URL encode the JSON config to safely pass through command line\n const encodedConfig = encodeURIComponent(options.agentConfig);\n args.push('--agent-config', encodedConfig);\n }\n if (options.verbose) {\n args.push('--verbose');\n }\n if (options.args && options.args.length > 0) {\n args.push('--args', ...options.args);\n }\n\n return args;\n }\n\n /**\n * Send input to the Docker container\n */\n sendInput(input: string): boolean {\n if (!this.session?.dockerProcess?.stdin) {\n this.logger.warn('No active Docker container to send input to');\n return false;\n }\n\n try {\n this.session.dockerProcess.stdin.write(input);\n this.session.lastActivity = new Date();\n return true;\n } catch (error) {\n this.logger.error('Failed to send input to Docker container:', error as Error);\n return false;\n }\n }\n\n /**\n * Kill the Docker container\n */\n kill(signal?: NodeJS.Signals): boolean {\n if (!this.session?.dockerProcess) {\n this.logger.warn('No active Docker container to kill');\n return false;\n }\n\n try {\n this.logger.info(`Stopping Docker container: ${this.session.containerId}`);\n this.session.dockerProcess.kill(signal || 'SIGTERM');\n\n // Force kill after timeout\n setTimeout(() => {\n if (this.session.dockerProcess && !this.session.dockerProcess.killed) {\n this.logger.warn(`Force killing container ${this.session.containerId}`);\n this.session.dockerProcess.kill('SIGKILL');\n }\n }, 5000);\n\n this.session.status = 'stopped';\n return true;\n } catch (error) {\n this.logger.error(`Failed to kill Docker container: ${error}`);\n return false;\n }\n }\n\n /**\n * Get the current Docker session\n */\n getSession(): DockerSession | undefined {\n return this.session;\n }\n\n /**\n * Check if a Docker session exists and is running\n */\n isSessionRunning(): boolean {\n return this.session?.status === 'running';\n }\n}\n","/**\n * Base Docker Agent Class\n *\n * Provides shared functionality for Docker-based agents.\n * Unlike BaseAgent, this class doesn't handle WebSocket connections,\n * input/output, or PTY management since the agent inside the Docker\n * container handles all of that directly.\n */\n\nimport { AGENT_STATUS, type DaemonStartAgentRequestEvent } from '@agimonai/universal-agent-events';\nimport { ENV_KEYS } from '../config/subenv';\nimport { DockerRunnerService } from '../services/DockerRunnerService';\nimport { TerminationService } from '../services/TerminationService';\nimport { Logger } from '../utils/logger';\n\nexport interface DockerAgentInfo {\n agentSessionId: string;\n agentType: string;\n status: (typeof AGENT_STATUS)[keyof typeof AGENT_STATUS];\n workingDir: string;\n containerId?: string;\n dockerSessionId?: string;\n process?: any;\n metadata?: Record<string, any>;\n}\n\nexport interface BaseDockerAgentOptions {\n agentType: string;\n serverUrl?: string; // Optional - only required for WebSocket connectivity\n apiKey?: string;\n verbose?: boolean;\n organizationId?: string;\n logger?: Logger;\n terminationService?: TerminationService;\n dockerImage?: string;\n onFullscreenChange?: (agentSessionId: string, isFullscreen: boolean) => void;\n}\n\nexport abstract class BaseDockerAgent {\n protected agentType: string;\n protected serverUrl?: string; // Optional - only required for WebSocket connectivity\n protected apiKey?: string;\n protected verbose: boolean;\n protected organizationId?: string;\n protected logger: Logger;\n protected terminationService: TerminationService;\n protected dockerImage: string;\n protected onFullscreenChange?: (agentSessionId: string, isFullscreen: boolean) => void;\n\n protected dockerRunner: DockerRunnerService;\n protected agentInfo: DockerAgentInfo | null = null;\n public isFullscreen: boolean = false;\n\n // Background output buffer for non-fullscreen Docker agents\n private backgroundOutputBuffer: string[] = [];\n private readonly BACKGROUND_BUFFER_SIZE = 5; // Keep last 5 chunks when not fullscreen\n private readonly BACKGROUND_CHUNK_MAX_SIZE = 2048; // Max size per chunk (2KB)\n\n constructor(options: BaseDockerAgentOptions) {\n this.agentType = options.agentType;\n this.serverUrl = options.serverUrl;\n this.apiKey = options.apiKey;\n this.verbose = options.verbose ?? false;\n this.organizationId = options.organizationId;\n this.logger = options.logger ?? new Logger({ verbose: this.verbose });\n this.terminationService = options.terminationService ?? new TerminationService(this.logger);\n this.dockerImage = options.dockerImage || 'agiflowai/agent-cli:latest';\n this.onFullscreenChange = options.onFullscreenChange;\n\n // Initialize Docker runner service\n this.dockerRunner = new DockerRunnerService(this.logger);\n }\n\n /**\n * Check if Docker is available\n */\n async isAvailable(): Promise<boolean> {\n return await this.dockerRunner.isDockerAvailable();\n }\n\n /**\n * Get current agent info\n */\n getAgentInfo(): DockerAgentInfo | null {\n return this.agentInfo;\n }\n\n /**\n * Set agent info (called by concrete implementations after launching)\n */\n protected setAgentInfo(info: DockerAgentInfo): void {\n this.agentInfo = info;\n }\n\n /**\n * Get environment variables to pass to the Docker container\n * Includes AGENT_API_KEY for agent authentication\n */\n protected getAgentEnvironmentVariables(): Record<string, string> {\n const env: Record<string, string> = {};\n\n // Copy process.env, filtering out undefined values\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined) {\n env[key] = value;\n }\n }\n\n // Pass API key to agent environment if available\n if (this.apiKey) {\n env[ENV_KEYS.AGENT_API_KEY] = this.apiKey;\n }\n\n // Pass organization ID if available\n if (this.organizationId) {\n env[ENV_KEYS.AGENT_ORGANIZATION_ID] = this.organizationId;\n }\n\n // Pass server URL for agent to connect back\n if (this.serverUrl) {\n env[ENV_KEYS.AGENT_SERVER_URL] = this.serverUrl;\n }\n\n // Pass agent type for identification\n env[ENV_KEYS.AGENT_TYPE] = this.agentType;\n\n // Pass verbose flag for debugging\n env[ENV_KEYS.VERBOSE] = this.verbose ? 'true' : 'false';\n\n return env;\n }\n\n /**\n * Add Docker container output to background buffer when agent is not fullscreen\n */\n protected addToBackgroundBuffer(data: string): void {\n // Truncate data if it's too large for a single chunk\n const truncatedData =\n data.length > this.BACKGROUND_CHUNK_MAX_SIZE\n ? data.substring(data.length - this.BACKGROUND_CHUNK_MAX_SIZE)\n : data;\n\n // Add to buffer\n this.backgroundOutputBuffer.push(truncatedData);\n\n // Keep only the last N chunks\n if (this.backgroundOutputBuffer.length > this.BACKGROUND_BUFFER_SIZE) {\n this.backgroundOutputBuffer.shift();\n }\n\n this.logger.debug(\n `🐳 Added ${truncatedData.length} chars to Docker background buffer (${this.backgroundOutputBuffer.length}/${this.BACKGROUND_BUFFER_SIZE} chunks)`,\n );\n }\n\n /**\n * Flush background buffer when Docker agent becomes fullscreen\n * Note: Docker agents don't have direct WebSocket connection, so this would\n * typically output to console or be handled by the container's stdout\n */\n protected flushBackgroundBuffer(): void {\n if (this.backgroundOutputBuffer.length === 0) {\n return;\n }\n\n this.logger.debug(`🐳 Flushing Docker background buffer: ${this.backgroundOutputBuffer.length} chunks`);\n\n // For Docker agents, we output buffered content to console\n // since the agent inside the container handles WebSocket communication\n const bufferedData = this.backgroundOutputBuffer.join('');\n if (bufferedData) {\n // Output to console for Docker agents (the container agent handles WebSocket)\n console.log(bufferedData);\n this.logger.debug(`🐳 Docker background buffer flushed: ${bufferedData.length} chars`);\n }\n\n // Clear the background buffer after flushing\n this.backgroundOutputBuffer = [];\n }\n\n /**\n * Set fullscreen mode flag and notify other agents\n */\n public setFullscreen(enabled: boolean, silent: boolean = false): void {\n const wasFullscreen = this.isFullscreen;\n this.isFullscreen = enabled;\n this.logger.debug(`Docker agent fullscreen mode ${enabled ? 'enabled' : 'disabled'}`);\n\n // When becoming fullscreen, flush any buffered background output\n if (enabled && !wasFullscreen && this.agentInfo) {\n this.flushBackgroundBuffer();\n }\n\n // Notify other agents if status changed and we have an agent session ID (unless silenced)\n if (!silent && wasFullscreen !== enabled && this.agentInfo && this.onFullscreenChange) {\n this.onFullscreenChange(this.agentInfo.agentSessionId, enabled);\n }\n }\n\n /**\n * Get fullscreen status\n */\n public getFullscreen(): boolean {\n return this.isFullscreen;\n }\n\n /**\n * Disconnect and cleanup Docker container\n */\n disconnect(): void {\n this.logger.info(`Disconnecting ${this.agentType} Docker agent`);\n\n // Kill Docker container\n this.dockerRunner.kill('SIGTERM');\n\n // Clear agent info\n this.agentInfo = null;\n }\n\n // Abstract methods to be implemented by concrete Docker agents\n\n /**\n * Launch the specific Docker agent (e.g., Claude Code, Cursor, etc.)\n */\n abstract launchAgent(request: DaemonStartAgentRequestEvent): Promise<DockerAgentInfo>;\n\n /**\n * Get agent version\n */\n abstract getVersion(): Promise<string | null>;\n\n /**\n * Process agent-specific configuration (e.g., MCP config for Claude)\n */\n protected abstract processAgentConfig(config: any): any;\n\n /**\n * Get agent-specific Docker options\n */\n protected abstract getDockerOptions(request: DaemonStartAgentRequestEvent): any;\n}\n","/**\n * Claude Docker Agent\n *\n * Docker-based implementation of Claude Code agent.\n * Handles Claude-specific Docker container configuration, volume mounting,\n * and environment setup for containerized execution.\n */\n\nimport { AGENT_STATUS, AGENT_TYPES, type DaemonStartAgentRequestEvent } from '@agimonai/universal-agent-events';\nimport fs from 'fs';\nimport { config } from '../config';\nimport { ENV_KEYS, SubEnvManager } from '../config/subenv';\nimport { FileSystemUtils } from '../utils/fileSystem';\nimport { BaseDockerAgent, BaseDockerAgentOptions, DockerAgentInfo } from './baseDocker';\n\nexport interface ClaudeDockerOptions extends BaseDockerAgentOptions {\n dockerImage?: string;\n onBeforeTerminate?: () => Promise<void>;\n}\n\nexport class ClaudeDockerAgent extends BaseDockerAgent {\n private onBeforeTerminate?: () => Promise<void>;\n\n constructor(options: ClaudeDockerOptions) {\n super({\n ...options,\n agentType: AGENT_TYPES.CLAUDE_CODE,\n dockerImage: options.dockerImage || config.VITE_AGENT_CLI_DOCKER_IMAGE,\n });\n this.onBeforeTerminate = options.onBeforeTerminate;\n }\n\n /**\n * Get Claude Docker agent version\n */\n async getVersion(): Promise<string | null> {\n return 'claude-docker-agent';\n }\n\n /**\n * Launch Claude Code agent in Docker container\n */\n async launchAgent(request: DaemonStartAgentRequestEvent): Promise<DockerAgentInfo> {\n const { payload } = request;\n const agentSessionId = payload.agentSessionId;\n const workingDir = payload.agentConfig?.workingDirectory\n ? FileSystemUtils.getAbsolutePath(payload.agentConfig.workingDirectory)\n : process.cwd();\n\n // Check if Docker is available\n if (!(await this.isAvailable())) {\n throw new Error('Docker is not available. Please install Docker to use containerized agents.');\n }\n\n this.logger.info(`Launching Claude agent in Docker container for session: ${agentSessionId}`);\n\n // Build Docker options specific to Claude\n const dockerOptions = this.getDockerOptions(request);\n\n try {\n // Spawn Docker container using DockerRunnerService\n const dockerSession = this.dockerRunner.spawn(dockerOptions, {\n onExit: async (exitCode, signal) => {\n this.logger.info(`Docker Claude agent exited with code ${exitCode}, signal: ${signal}`);\n\n // Call cleanup callback before firing termination events\n if (this.onBeforeTerminate) {\n try {\n this.logger.info('Executing cleanup callback before termination...');\n await this.onBeforeTerminate();\n this.logger.info('Cleanup callback completed successfully');\n } catch (error) {\n this.logger.error('Error during cleanup callback:', error as Error);\n }\n }\n\n // Notify TerminationService about container termination\n if (this.agentInfo) {\n await this.terminationService.handlePtyTermination({\n agentSessionId: this.agentInfo.agentSessionId,\n reason: signal === 2 ? 'agent_sigint' : 'natural',\n exitCode,\n signal: signal as NodeJS.Signals | undefined,\n });\n }\n },\n onData: async (data) => {\n // Handle any special processing for Docker output if needed\n // The DockerRunnerService already handles stdout forwarding\n this.logger.debug('Docker container output:', data);\n },\n onError: (error) => {\n this.logger.error('Docker container error:', error);\n },\n });\n\n this.logger.success(`Docker Claude agent launched successfully for session: ${agentSessionId}`);\n\n // Create and return DockerAgentInfo\n const agentInfo: DockerAgentInfo = {\n agentSessionId: agentSessionId,\n agentType: AGENT_TYPES.CLAUDE_CODE,\n status: AGENT_STATUS.IDLE,\n workingDir: workingDir,\n containerId: dockerSession.containerId,\n dockerSessionId: dockerSession.id,\n process: dockerSession.dockerProcess,\n metadata: {\n agentSessionId: agentSessionId,\n agentType: payload.agentType,\n config: payload.agentConfig,\n docker: true,\n containerId: dockerSession.containerId,\n dockerSessionId: dockerSession.id,\n },\n };\n\n this.setAgentInfo(agentInfo);\n return agentInfo;\n } catch (error) {\n throw new Error(\n `Failed to launch Claude Docker agent: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /**\n * Disconnect and cleanup Docker container\n */\n disconnect(): void {\n this.logger.info('Disconnecting Claude Docker agent');\n\n try {\n // Kill Docker container gracefully\n if (this.dockerRunner.isSessionRunning()) {\n this.dockerRunner.kill('SIGTERM');\n\n // Give container time for graceful shutdown\n setTimeout(() => {\n if (this.dockerRunner.isSessionRunning()) {\n this.logger.warn('Force killing Docker container...');\n this.dockerRunner.kill('SIGKILL');\n }\n }, 3000);\n }\n\n // Clear agent info\n this.agentInfo = null;\n\n this.logger.info('Claude Docker agent disconnected successfully');\n } catch (error) {\n this.logger.error('Error during Docker agent disconnect:', error as Error);\n // Continue with cleanup even if there's an error\n }\n }\n\n /**\n * Get Claude-specific Docker options\n */\n protected getDockerOptions(request: DaemonStartAgentRequestEvent): any {\n const { payload } = request;\n const agentSessionId = payload.agentSessionId;\n const workingDir = payload.agentConfig?.workingDirectory\n ? FileSystemUtils.getAbsolutePath(payload.agentConfig.workingDirectory)\n : process.cwd();\n\n // Use Docker-specific server URL for container environment\n // Schema now handles converting empty strings to undefined\n const dockerHttpUrl = config.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT || this.serverUrl;\n // Convert HTTP URL to WebSocket URL for agent server connection (only if dockerHttpUrl exists)\n const dockerWsUrl = dockerHttpUrl ? dockerHttpUrl.replace(/^http/, 'ws') : undefined;\n\n // Process MCP config if provided\n let processedMcpConfig = null;\n if (payload.agentConfig?.mcps) {\n processedMcpConfig = this.processAgentConfig(payload.agentConfig.mcps);\n }\n\n // Build the complete agent config to pass as JSON string\n // Always use /workspace as the container's working directory regardless of the host path\n const agentConfigForContainer = {\n ...payload.agentConfig,\n workingDirectory: '/workspace', // Always use container path, not host path\n };\n\n // If we have processed MCP config, include it\n if (processedMcpConfig) {\n agentConfigForContainer.mcps = processedMcpConfig;\n }\n\n return {\n agentSessionId,\n dockerImage: payload.agentConfig?.dockerImage || this.dockerImage,\n workingDir: workingDir,\n agentApiKey: this.apiKey,\n agentOrganizationId: this.organizationId,\n agentServerUrl: dockerWsUrl, // WebSocket URL for agent server connection (optional)\n agentApiUrl: dockerHttpUrl, // HTTP URL for REST API calls (optional)\n agentType: AGENT_TYPES.CLAUDE_CODE,\n agentConfig: JSON.stringify(agentConfigForContainer), // Pass entire config as JSON string including args\n // args: payload.agentConfig?.args, // Removed - args are already included in agentConfig\n verbose: this.verbose,\n // Additional Docker-specific options\n additionalEnvVars: {\n [ENV_KEYS.NODE_ENV]: SubEnvManager.nodeEnv,\n [ENV_KEYS.AGENT_SESSION_ID]: agentSessionId,\n [ENV_KEYS.AGENT_CONTAINER_MODE]: SubEnvManager.isContainerMode ? 'true' : 'false',\n IS_SANDBOX: '1', // Allow dangerous permissions in sandboxed Docker environment\n },\n additionalVolumes: this.getAdditionalVolumes(payload),\n networkMode: config.VITE_AGENT_CLI_DOCKER_NETWORK, // Use configured network mode\n user: undefined, // Use default user from DockerRunnerService\n };\n }\n\n /**\n * Get additional bind mounts for development and MCP servers\n */\n private getAdditionalVolumes(\n _payload: any,\n ): Array<{ host: string; container: string; readonly?: boolean; type?: 'bind' | 'volume' }> {\n const volumes: Array<{ host: string; container: string; readonly?: boolean; type?: 'bind' | 'volume' }> = [];\n\n const homeDir = SubEnvManager.homeDir;\n if (homeDir) {\n // Mount SSH keys for git access (readonly)\n volumes.push({\n host: `${homeDir}/.ssh`,\n container: '/root/.ssh',\n readonly: true,\n type: 'bind',\n });\n\n // Add Docker named volumes for package manager caches\n // These will persist between container runs and improve install performance\n\n // pnpm cache volume\n volumes.push({\n host: 'agiflow-pnpm-cache',\n container: '/root/.pnpm-store',\n readonly: false,\n type: 'volume',\n });\n\n // npm cache volume\n volumes.push({\n host: 'agiflow-npm-cache',\n container: '/root/.npm',\n readonly: false,\n type: 'volume',\n });\n\n // node-gyp cache volume (for native module compilation)\n volumes.push({\n host: 'agiflow-node-gyp-cache',\n container: '/root/.cache/node-gyp',\n readonly: false,\n type: 'volume',\n });\n\n // Mount Claude credentials based on platform\n const isMacOS = SubEnvManager.isMacOS;\n\n if (isMacOS) {\n // macOS: Use tmp files due to encrypted keychain storage\n // Ensure .claude_tmp.json file exists before mounting\n const claudeTmpJsonPath = `${homeDir}/.claude_tmp.json`;\n if (!fs.existsSync(claudeTmpJsonPath)) {\n fs.writeFileSync(claudeTmpJsonPath, '{}', 'utf8');\n }\n volumes.push({\n host: claudeTmpJsonPath,\n container: '/root/.claude.json',\n readonly: false,\n type: 'bind',\n });\n\n // Mount .claude_tmp directory\n const claudeTmpDirPath = `${homeDir}/.claude_tmp`;\n if (!fs.existsSync(claudeTmpDirPath)) {\n fs.mkdirSync(claudeTmpDirPath, { recursive: true });\n }\n volumes.push({\n host: claudeTmpDirPath,\n container: '/root/.claude',\n readonly: false,\n type: 'bind',\n });\n } else {\n // Linux: Use normal Claude credentials files\n // Ensure .claude.json file exists before mounting\n const claudeJsonPath = `${homeDir}/.claude.json`;\n if (!fs.existsSync(claudeJsonPath)) {\n fs.writeFileSync(claudeJsonPath, '{}', 'utf8');\n }\n volumes.push({\n host: claudeJsonPath,\n container: '/root/.claude.json',\n readonly: false,\n type: 'bind',\n });\n\n // Mount .claude directory\n const claudeDirPath = `${homeDir}/.claude`;\n if (!fs.existsSync(claudeDirPath)) {\n fs.mkdirSync(claudeDirPath, { recursive: true });\n }\n volumes.push({\n host: claudeDirPath,\n container: '/root/.claude',\n readonly: false,\n type: 'bind',\n });\n }\n }\n\n return volumes;\n }\n\n /**\n * Send input to the agent (for compatibility with BaseAgent interface)\n */\n async sendInputToAgent(_input: string): Promise<void> {\n // For Docker agents, this is a no-op since the agent inside the container handles input directly\n this.logger.debug('sendInputToAgent called on Docker agent - no action needed');\n }\n\n /**\n * Get container status for monitoring\n */\n getContainerStatus(): {\n isRunning: boolean;\n containerId?: string;\n status?: string;\n lastActivity?: Date;\n } {\n const session = this.dockerRunner.getSession();\n return {\n isRunning: this.dockerRunner.isSessionRunning(),\n containerId: session?.containerId,\n status: session?.status,\n lastActivity: session?.lastActivity,\n };\n }\n\n /**\n * Check if agent is healthy and responsive\n */\n async isHealthy(): Promise<boolean> {\n try {\n if (!this.dockerRunner.isSessionRunning()) {\n return false;\n }\n\n // Additional health checks could be added here\n // For example, checking if the container responds to ping\n return true;\n } catch (error) {\n this.logger.error('Health check failed:', error as Error);\n return false;\n }\n }\n\n /**\n * Get Docker session information\n */\n getDockerSession() {\n return this.dockerRunner.getSession();\n }\n\n /**\n * Process MCP config for Claude-specific requirements\n */\n protected processAgentConfig(rawMcps: any): any {\n // Normalize into record keyed by name (same logic as ClaudeAgent)\n const mcpServers: Record<string, any> = {};\n\n if (Array.isArray(rawMcps)) {\n for (const item of rawMcps) {\n if (!item || typeof item !== 'object') continue;\n const name = item.name || item.id || item.key;\n if (!name) continue;\n\n // Pick allowed fields including headers\n mcpServers[name] = {\n type: item.type || 'stdio',\n command: item.command,\n args: item.args || item.arguments || [],\n url: item.url,\n env: item.env || {},\n disabled: item.disabled ?? false,\n headers: item.headers || {},\n };\n }\n } else if (typeof rawMcps === 'object') {\n // Assume already in desired record shape – clone & ensure headers default\n for (const [key, value] of Object.entries(rawMcps)) {\n if (value && typeof value === 'object') {\n mcpServers[key] = {\n ...value,\n headers: (value as any).headers || {},\n };\n }\n }\n }\n\n // Return just the mcpServers object (Claude Code CLI expects this format directly)\n return mcpServers;\n }\n}\n","import {\n AGENT_TYPES,\n type DaemonStartAgentRequestEvent,\n DaemonStartAgentRequestEventSchema,\n} from '@agimonai/universal-agent-events';\nimport { Command } from 'commander';\nimport { randomUUID } from 'crypto';\nimport { ClaudeAgent } from '../agents/claude';\nimport { ClaudeDockerAgent } from '../agents/claudeDocker';\nimport { config } from '../config';\nimport { SubEnvManager } from '../config/subenv';\nimport { CredentialsService } from '../services/CredentialsService';\nimport { TerminationService } from '../services/TerminationService';\nimport { FileSystemUtils } from '../utils/fileSystem';\nimport { Logger } from '../utils/logger';\nimport { BaseCommand } from './baseCommand';\n\ninterface ClaudeOptions {\n serverUrl?: string;\n apiUrl?: string;\n apiKey?: string;\n organizationId?: string;\n verbose?: boolean;\n claudePath?: string;\n workingDirectory?: string;\n agentSessionId?: string;\n agentConfig?: string;\n args?: string[];\n docker?: boolean;\n dockerImage?: string;\n llmProvider?: string;\n llmModel?: string;\n alias?: string;\n standalone?: boolean;\n}\n\nexport class ClaudeCommand extends BaseCommand {\n register(program: Command): void {\n program\n .command('claude')\n .description('Launch Claude Code agent with full functionality')\n .option('-s, --server-url <url>', 'WebSocket server URL')\n .option('-a, --api-url <url>', 'HTTP API URL')\n .option('-k, --api-key <key>', 'API key for authentication')\n .option('-o, --organization-id <id>', 'Organization ID')\n .option('-v, --verbose', 'Enable verbose logging', false)\n .option('-p, --claude-path <path>', 'Path to Claude executable', 'claude')\n .option('-w, --working-directory <dir>', 'Working directory', process.cwd())\n .option('-i, --agent-session-id <id>', 'Agent session ID')\n .option('-c, --agent-config <json>', 'Agent configuration as JSON string')\n .option('--args <args...>', 'Additional arguments to pass to Claude')\n .option('--docker', 'Run Claude agent in Docker container', false)\n .option('--docker-image <image>', 'Docker image to use for containerized agent')\n .option('--llm-provider <provider>', 'LLM provider to route requests to (e.g., openai)')\n .option('--llm-model <model>', 'LLM model to use (e.g., gpt-4-turbo, gpt-5)')\n .option('--alias <alias>', 'Custom session alias for easy identification')\n .option('--standalone', 'Run in standalone mode without backend connection', false)\n .action(async (options) => {\n try {\n await this.execute(options);\n } catch (error) {\n this.handleError(error);\n }\n });\n }\n\n private async execute(options: ClaudeOptions): Promise<void> {\n // Get environment manager instance\n\n // Validate LLM provider if specified\n let llmConfig: { provider: string; model?: string } | undefined;\n if (options.llmProvider) {\n // Validate provider - only allow codex and gpt (openai)\n const allowedProviders = ['codex', 'gpt', 'openai', 'chatgpt'];\n const normalizedProvider = options.llmProvider.toLowerCase();\n\n if (!allowedProviders.includes(normalizedProvider)) {\n this.error(`Invalid LLM provider: ${options.llmProvider}`);\n this.error(`Allowed providers: ${allowedProviders.join(', ')}`);\n process.exit(1);\n }\n\n // Store LLM config to pass to agent\n llmConfig = {\n provider: normalizedProvider,\n model: options.llmModel,\n };\n }\n\n // Use options or environment defaults\n // In standalone mode, ensure all connection values are undefined\n const serverUrl = options.standalone ? undefined : options.serverUrl || config.VITE_INJECT_AGIFLOW_APP_ENDPOINT;\n const apiUrl = options.standalone ? undefined : options.apiUrl || config.VITE_INJECT_AGIFLOW_APP_ENDPOINT;\n const apiKey = options.standalone ? undefined : options.apiKey || SubEnvManager.apiKey;\n const organizationId = options.standalone ? undefined : options.organizationId || SubEnvManager.organizationId;\n\n // Generate session ID if not provided\n let agentSessionId = options.agentSessionId || SubEnvManager.sessionId;\n if (!agentSessionId) {\n agentSessionId = randomUUID();\n if (options.verbose) {\n this.info(`Generated session ID: ${agentSessionId}`);\n }\n }\n\n // Log standalone mode if no server URL provided or explicitly enabled\n if (!serverUrl) {\n if (options.verbose) {\n if (options.standalone) {\n this.info('Running in standalone mode (--standalone flag)');\n } else {\n this.info('Running in standalone mode (no server URL configured)');\n }\n this.info('Agent will launch without remote connectivity');\n }\n } else {\n // Validate WebSocket URL only if provided\n try {\n new URL(serverUrl);\n } catch (error) {\n this.error('Invalid server URL. Must be a valid WebSocket URL (ws:// or wss://).');\n process.exit(1);\n }\n }\n\n // Validate API URL if provided\n if (apiUrl) {\n try {\n new URL(apiUrl);\n } catch (error) {\n this.error('Invalid API URL. Must be a valid HTTP URL.');\n process.exit(1);\n }\n } else if (!serverUrl && options.verbose) {\n this.info('No API URL provided - HTTP features will be unavailable');\n }\n\n // Generate session alias for easy identification\n const generateSessionAlias = (): string => {\n const now = new Date();\n const timestamp = now.toISOString().replace(/[-:]/g, '').replace('T', '-').split('.')[0];\n const provider = options.llmProvider || 'claude';\n const model = options.llmModel?.replace(/[^a-z0-9]/gi, '') || 'default';\n return `${provider}-${model}-${timestamp}`;\n };\n\n const sessionAlias = options.alias || generateSessionAlias();\n\n const logger = new Logger({ verbose: options.verbose });\n\n if (options.verbose) {\n this.info(`Starting Claude agent${options.docker ? ' in Docker container' : ''}...`);\n this.info(`Session: ${sessionAlias} (ID: ${agentSessionId})`);\n logger.debug('Options:', options);\n\n // Log routing configuration if enabled\n if (options.llmProvider) {\n this.info(`LLM Routing enabled: ${options.llmProvider} → ${options.llmModel || 'default model'}`);\n }\n }\n\n // Create services\n const credentialsService = new CredentialsService();\n const terminationService = new TerminationService(logger);\n\n // Create appropriate agent instance based on docker flag\n const claudeAgent = options.docker\n ? new ClaudeDockerAgent({\n agentType: AGENT_TYPES.CLAUDE_CODE,\n serverUrl,\n apiKey,\n organizationId,\n verbose: options.verbose,\n dockerImage: options.dockerImage,\n logger,\n terminationService,\n })\n : new ClaudeAgent({\n agentType: AGENT_TYPES.CLAUDE_CODE,\n serverUrl,\n apiUrl,\n apiKey,\n organizationId,\n verbose: options.verbose,\n claudePath: options.claudePath,\n standalone: true,\n logger,\n credentialsService,\n terminationService,\n });\n\n // Build agent config from options\n let agentConfig: any = {\n workingDirectory: options.workingDirectory\n ? FileSystemUtils.getAbsolutePath(options.workingDirectory)\n : process.cwd(),\n args: options.args || [],\n sessionAlias,\n ...(llmConfig && { llmConfig }),\n };\n\n // Parse agent config JSON if provided\n if (options.agentConfig) {\n try {\n // URL decode the config string first (in case it was encoded for command line safety)\n const decodedConfig = decodeURIComponent(options.agentConfig);\n const parsedConfig = JSON.parse(decodedConfig);\n agentConfig = { ...agentConfig, ...parsedConfig };\n } catch (error) {\n // If URL decoding fails, try parsing the original string directly (for backward compatibility)\n try {\n const parsedConfig = JSON.parse(options.agentConfig);\n agentConfig = { ...agentConfig, ...parsedConfig };\n } catch (fallbackError) {\n this.error(`Failed to parse agent config JSON: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }\n }\n\n // Create launch request using schema for correct values and defaults\n const launchRequest: DaemonStartAgentRequestEvent = DaemonStartAgentRequestEventSchema.parse({\n payload: {\n sessionId: agentSessionId,\n agentType: AGENT_TYPES.CLAUDE_CODE,\n agentSessionId,\n agentConfig,\n },\n });\n\n try {\n // Launch the agent\n await claudeAgent.launchAgent(launchRequest);\n this.success(\n `Claude agent${options.docker ? ' (Docker)' : ''} launched successfully for session: ${sessionAlias}`,\n );\n\n // Handle graceful shutdown\n const handleShutdown = async (signal: string) => {\n if (options.verbose) {\n this.info(`Received ${signal}, shutting down Claude agent${options.docker ? ' container' : ''}...`);\n }\n try {\n claudeAgent.disconnect();\n this.info(`Claude agent${options.docker ? ' container' : ''} shutdown complete`);\n process.exit(0);\n } catch (error) {\n this.error(`Error during shutdown: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n };\n\n // Register signal handlers\n process.on('SIGINT', () => handleShutdown('SIGINT'));\n process.on('SIGTERM', () => handleShutdown('SIGTERM'));\n\n // Keep the process alive\n this.info(`Claude agent${options.docker ? ' container' : ''} is running. Press Ctrl+C to stop.`);\n\n // Wait indefinitely\n await new Promise(() => {});\n } catch (error) {\n this.error(`Failed to start Claude agent: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }\n}\n","import { exec } from 'child_process';\nimport { promises as fs } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nexport interface AgentProfile {\n name: string;\n description: string;\n color: string;\n prompt: string;\n filePath: string;\n}\n\nexport interface AgentProfilesOptions {\n claudeAgentsPath?: string;\n}\n\nexport class AgentProfiles {\n private claudeAgentsPath: string;\n\n constructor(options: AgentProfilesOptions = {}) {\n this.claudeAgentsPath = options.claudeAgentsPath || join(homedir(), '.claude', 'agents');\n }\n\n async findAgentsDirectory(): Promise<string | null> {\n // First try the project's .claude directory (relative to current working directory)\n const projectClaudePath = join(process.cwd(), '.claude', 'agents');\n try {\n const stats = await fs.stat(projectClaudePath);\n if (stats.isDirectory()) {\n return projectClaudePath;\n }\n } catch (error) {\n // Project .claude directory doesn't exist, continue searching\n }\n\n // Try the default path\n try {\n const stats = await fs.stat(this.claudeAgentsPath);\n if (stats.isDirectory()) {\n return this.claudeAgentsPath;\n }\n } catch (error) {\n // Directory doesn't exist at default location, search recursively\n }\n\n try {\n // Use find command to recursively search for .claude/agents with depth limit of 7\n // Use a more restrictive approach - only search in likely directories\n const homeDir = homedir();\n\n // Search only in common development/config directories to avoid permission issues\n const searchPaths = [\n `\"${homeDir}/.config\"`,\n `\"${homeDir}/.local\"`,\n `\"${homeDir}/workspace\"`,\n `\"${homeDir}/projects\"`,\n `\"${homeDir}/dev\"`,\n `\"${homeDir}/code\"`,\n `\"${homeDir}/.claude\"`,\n `\"${homeDir}\"`, // Direct in home, but with maxdepth 1\n ];\n\n for (const searchPath of searchPaths) {\n try {\n // For direct home directory search, use maxdepth 1, for subdirectories use maxdepth 5\n const isDirectHome = searchPath === `\"${homeDir}\"`;\n const maxDepth = isDirectHome ? 1 : 5;\n const command = `find ${searchPath} -maxdepth ${maxDepth} -type d -name \"agents\" -path \"*/.claude/agents\" 2>/dev/null | head -1`;\n\n const { stdout } = await execAsync(command);\n const foundPath = stdout.trim();\n\n if (foundPath && foundPath.length > 0) {\n // Verify the found path is actually a directory\n const stats = await fs.stat(foundPath);\n if (stats.isDirectory()) {\n return foundPath;\n }\n }\n } catch (error) {}\n }\n } catch (error) {\n console.error('Error searching for .claude/agents directory:', error);\n }\n\n return null;\n }\n\n async listAgentFiles(): Promise<string[]> {\n const agentsDir = await this.findAgentsDirectory();\n if (!agentsDir) {\n return [];\n }\n\n try {\n const files = await fs.readdir(agentsDir);\n return files.filter((file) => file.endsWith('.md')).map((file) => join(agentsDir, file));\n } catch (error) {\n console.error('Error reading agents directory:', error);\n return [];\n }\n }\n\n async parseAgentFile(filePath: string): Promise<AgentProfile | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return this.parseAgentContent(content, filePath);\n } catch (error) {\n console.error(`Error reading agent file ${filePath}:`, error);\n return null;\n }\n }\n\n private parseAgentContent(content: string, filePath: string): AgentProfile | null {\n const lines = content.split('\\n');\n\n // Find frontmatter boundaries\n const frontmatterStart = lines.findIndex((line) => line.trim() === '---');\n const frontmatterEnd = lines.findIndex((line, index) => index > frontmatterStart && line.trim() === '---');\n\n if (frontmatterStart === -1 || frontmatterEnd === -1) {\n console.error(`Invalid frontmatter in ${filePath}`);\n return null;\n }\n\n // Parse frontmatter\n const frontmatterLines = lines.slice(frontmatterStart + 1, frontmatterEnd);\n const frontmatter: Record<string, string> = {};\n\n for (const line of frontmatterLines) {\n const colonIndex = line.indexOf(':');\n if (colonIndex > 0) {\n const key = line.substring(0, colonIndex).trim();\n const value = line.substring(colonIndex + 1).trim();\n frontmatter[key] = value;\n }\n }\n\n // Extract prompt content (everything after the second ---)\n const promptLines = lines.slice(frontmatterEnd + 1);\n const prompt = promptLines.join('\\n').trim();\n\n // Validate required fields\n if (!frontmatter.name || !frontmatter.description) {\n console.error(`Missing required fields in ${filePath}`);\n return null;\n }\n\n return {\n name: frontmatter.name,\n description: frontmatter.description,\n color: frontmatter.color || 'default',\n prompt,\n filePath,\n };\n }\n\n async getAllAgentProfiles(): Promise<AgentProfile[]> {\n const agentFiles = await this.listAgentFiles();\n const profiles: AgentProfile[] = [];\n\n for (const filePath of agentFiles) {\n const profile = await this.parseAgentFile(filePath);\n if (profile) {\n profiles.push(profile);\n }\n }\n\n return profiles;\n }\n\n async getAgentProfile(name: string): Promise<AgentProfile | null> {\n const profiles = await this.getAllAgentProfiles();\n return profiles.find((profile) => profile.name === name) || null;\n }\n\n async searchAgentProfiles(query: string): Promise<AgentProfile[]> {\n const profiles = await this.getAllAgentProfiles();\n const lowerQuery = query.toLowerCase();\n\n return profiles.filter(\n (profile) =>\n profile.name.toLowerCase().includes(lowerQuery) || profile.description.toLowerCase().includes(lowerQuery),\n );\n }\n}\n","import { confirm, input } from '@inquirer/prompts';\nimport { join } from 'path';\nimport { FileSystemUtils, Logger } from '../utils';\nimport { AgentProfiles } from './AgentProfiles';\n\nexport interface DeviceCodeResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n expires_in: number;\n interval?: number;\n}\n\n// API Key response from device token endpoint\nexport interface DeviceTokenExchangeResponse {\n api_key: string;\n expires_in: number;\n organization_id?: string;\n}\n\nexport interface ApiKeyToken {\n api_key: string;\n key_id: string;\n expires_at: number;\n organization_id: string;\n prefix: string;\n device_id?: string; // Database device ID for WebSocket connections\n}\n\nexport interface AuthOptions {\n clientId: string;\n baseUrl: string;\n verbose?: boolean;\n logger?: Logger;\n}\n\nexport class DeviceCodeAuthService {\n private options: AuthOptions;\n private apiKeyPath: string;\n private logger: Logger;\n\n constructor(options: AuthOptions) {\n this.options = options;\n this.logger = options.logger || new Logger({ verbose: options.verbose || false });\n\n // Setup token storage paths\n this.apiKeyPath = join(FileSystemUtils.AGIFLOW_DIR, 'api-key.json');\n }\n\n /**\n * Get valid API key for daemon authentication\n * Uses device code flow instead of local server OAuth\n */\n async getValidApiKey(): Promise<ApiKeyToken> {\n try {\n // Try to get existing API key first\n const apiKey = await this.loadApiKey();\n if (apiKey && this.isTokenValid(apiKey.expires_at)) {\n this.logger.info('Using existing API key');\n return apiKey;\n }\n\n // Need fresh authentication via device code flow\n this.logger.info('Starting device code authentication flow...');\n const apiKeyToken = await this.performDeviceCodeFlow();\n await this.storeApiKey(apiKeyToken);\n return apiKeyToken;\n } catch (error) {\n throw new Error(`Authentication failed: ${error instanceof Error ? error.message : error}`);\n }\n }\n\n /**\n * Perform OAuth device code flow (RFC 8628)\n */\n private async performDeviceCodeFlow(): Promise<ApiKeyToken> {\n // Step 1: Request device code\n const deviceCodeResponse = await fetch(`${this.options.baseUrl}/api/v1/oauth/device/authorize`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n client_id: this.options.clientId,\n scope: 'openid profile email',\n }),\n });\n\n if (!deviceCodeResponse.ok) {\n const errorText = await deviceCodeResponse.text();\n throw new Error(`Device authorization failed: ${deviceCodeResponse.status} ${errorText}`);\n }\n\n const deviceData: DeviceCodeResponse = await deviceCodeResponse.json();\n\n // Construct verification URL with user_code query param for convenience\n const verificationUrl = `${deviceData.verification_uri}?code=${encodeURIComponent(deviceData.user_code)}`;\n\n // Step 2: Show user instructions (no polling)\n this.logger.info('To authenticate your CLI:');\n this.logger.info(`1. Open (or we opened): ${verificationUrl}`);\n this.logger.info('2. Sign in (if needed) and confirm device authorization');\n this.logger.info('3. Copy the verification token (JWT) shown after confirmation');\n this.logger.info('4. Paste it below to complete authentication');\n this.logger.info('');\n this.logger.info(`User Code: ${deviceData.user_code}`);\n\n // Step 3: Browser opening disabled - user will manually visit URL\n // this.openBrowser(verificationUrl);\n\n // Step 4: Ask user for verification token JWT\n const verificationToken = await input({\n message: 'Paste verification token (JWT):',\n validate: (value) => {\n if (!value || value.trim().split('.').length !== 3) {\n return 'Invalid verification token format. Please enter a valid JWT token.';\n }\n return true;\n },\n });\n\n // Step 5: Exchange verification token + device_code for API key\n const exchangeResp = await fetch(`${this.options.baseUrl}/api/v1/oauth/device/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: deviceData.device_code,\n verification_token: verificationToken.trim(),\n client_id: this.options.clientId,\n }),\n });\n\n if (!exchangeResp.ok) {\n const errText = await exchangeResp.text();\n throw new Error(`Token exchange failed: ${exchangeResp.status} ${errText}`);\n }\n\n const tokenData: DeviceTokenExchangeResponse = await exchangeResp.json();\n if (!tokenData.api_key) {\n throw new Error('Token exchange response missing api_key');\n }\n\n if (!tokenData.organization_id) {\n throw new Error('Token exchange response missing organization_id');\n }\n\n this.logger.success('Authentication successful!\\n');\n\n // Build ApiKeyToken structure\n const apiKeyToken: ApiKeyToken = {\n api_key: tokenData.api_key,\n key_id: 'device-flow',\n expires_at: Date.now() + tokenData.expires_in * 1000,\n organization_id: tokenData.organization_id,\n prefix: 'agiflow_',\n };\n\n // Check for local agent profiles and offer to add them to the organization\n await this.checkAndOfferAgentProfiles(apiKeyToken);\n\n return apiKeyToken;\n }\n\n /**\n * Create API key using OAuth access token\n */\n\n /**\n * Load API key from storage\n */\n private async loadApiKey(): Promise<ApiKeyToken | null> {\n try {\n const exists = await FileSystemUtils.exists(this.apiKeyPath);\n if (!exists) return null;\n return await FileSystemUtils.readJson<ApiKeyToken>(this.apiKeyPath);\n } catch (error) {\n return null;\n }\n }\n\n /**\n * Store API key to storage\n */\n private async storeApiKey(apiKey: ApiKeyToken): Promise<void> {\n await this.ensureAgiflowDir();\n await FileSystemUtils.writeJson(this.apiKeyPath, apiKey);\n this.logger.debug(`API key stored at ${this.apiKeyPath}`);\n }\n\n /**\n * Ensure ~/.agiflow directory exists\n */\n private async ensureAgiflowDir(): Promise<void> {\n await FileSystemUtils.ensureDir(FileSystemUtils.AGIFLOW_DIR);\n }\n\n /**\n * Check if token is still valid (with 5 minute buffer)\n */\n private isTokenValid(expiresAt: number): boolean {\n const buffer = 5 * 60 * 1000; // 5 minutes\n return Date.now() < expiresAt - buffer;\n }\n\n /**\n * Clear stored tokens (for logout)\n */\n async clearTokens(): Promise<void> {\n try {\n const exists = await FileSystemUtils.exists(this.apiKeyPath);\n if (exists) {\n await FileSystemUtils.remove(this.apiKeyPath);\n }\n } catch (error) {\n // File might not exist\n }\n this.logger.debug('Cleared stored tokens');\n }\n\n /**\n * Get organization ID from stored API key\n */\n async getOrganizationId(): Promise<string | null> {\n const apiKey = await this.loadApiKey();\n return apiKey?.organization_id || null;\n }\n\n /**\n * Get device ID from stored API key\n */\n async getDeviceId(): Promise<string | null> {\n const apiKey = await this.loadApiKey();\n return apiKey?.device_id || null;\n }\n\n /**\n * Update stored API key with device ID\n */\n async updateDeviceId(deviceId: string): Promise<void> {\n const apiKey = await this.loadApiKey();\n if (apiKey) {\n apiKey.device_id = deviceId;\n await this.storeApiKey(apiKey);\n this.logger.debug(`Updated device ID in stored API key: ${deviceId}`);\n }\n }\n\n /**\n * Check for local agent profiles and offer to add them to the organization\n */\n private async checkAndOfferAgentProfiles(apiKeyToken: ApiKeyToken): Promise<void> {\n try {\n this.logger.info('Checking for local agent profiles...');\n\n const agentProfiles = new AgentProfiles();\n const profiles = await agentProfiles.getAllAgentProfiles();\n\n if (profiles.length === 0) {\n this.logger.info('No local agent profiles found.');\n return;\n }\n\n this.logger.info(`Found ${profiles.length} local agent profile(s):`);\n profiles.forEach((profile, index) => {\n this.logger.info(` ${index + 1}. ${profile.name} - ${profile.description.substring(0, 80)}...`);\n });\n\n const shouldUpload = await confirm({\n message: 'Would you like to add these agent profiles to your organization?',\n default: false,\n });\n\n if (shouldUpload) {\n await this.uploadAgentProfiles(profiles, apiKeyToken);\n } else {\n this.logger.info('Skipping agent profile upload.');\n }\n } catch (error) {\n this.logger.warn(`Could not check agent profiles: ${error instanceof Error ? error.message : error}`);\n // Don't fail authentication if agent profile check fails\n }\n }\n\n /**\n * Upload agent profiles to the organization\n */\n private async uploadAgentProfiles(profiles: any[], apiKeyToken: ApiKeyToken): Promise<void> {\n this.logger.info('Uploading agent profiles to organization...');\n\n try {\n // Use the batch API endpoint for creating agent members\n const response = await fetch(\n `${this.options.baseUrl}/api/v1/organizations/${apiKeyToken.organization_id}/members/agents`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKeyToken.api_key,\n },\n body: JSON.stringify({\n agents: profiles.map((profile) => ({\n name: profile.name,\n description: profile.description,\n prompt: profile.prompt,\n })),\n }),\n },\n );\n\n if (response.ok) {\n const result = await response.json();\n const successCount = result.created?.length || 0;\n const errorCount = result.errors?.length || 0;\n\n if (successCount > 0) {\n this.logger.success(`Successfully uploaded ${successCount} agent profile(s) to your organization!`);\n result.created.forEach((agent: any) => {\n this.logger.info(`✅ Created: ${agent.user.name}`);\n });\n }\n\n if (errorCount > 0) {\n this.logger.warn(`Failed to upload ${errorCount} agent profile(s):`);\n result.errors.forEach((error: any) => {\n this.logger.warn(`❌ ${error.name}: ${error.error}`);\n });\n }\n } else {\n const errorText = await response.text();\n this.logger.warn(`❌ Failed to upload agent profiles: ${response.status} ${errorText}`);\n }\n } catch (error) {\n this.logger.warn(`❌ Error uploading agent profiles: ${error instanceof Error ? error.message : error}`);\n }\n }\n}\n","/**\n * Simple semaphore implementation for managing concurrent access to resources\n */\nexport class Semaphore {\n private permits: number;\n private waitQueue: Array<() => void> = [];\n\n constructor(permits = 1) {\n this.permits = permits;\n }\n\n async acquire(): Promise<void> {\n if (this.permits > 0) {\n this.permits--;\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n this.waitQueue.push(resolve);\n });\n }\n\n release(): void {\n if (this.waitQueue.length > 0) {\n const resolve = this.waitQueue.shift();\n if (resolve) {\n resolve();\n }\n } else {\n this.permits++;\n }\n }\n\n async runExclusive<T>(fn: () => Promise<T>): Promise<T> {\n await this.acquire();\n try {\n return await fn();\n } finally {\n this.release();\n }\n }\n\n get available(): number {\n return this.permits;\n }\n\n get waiting(): number {\n return this.waitQueue.length;\n }\n}\n\n/**\n * Keyed semaphore for managing access to resources by key\n */\nexport class KeyedSemaphore<K = string> {\n private semaphores = new Map<K, Semaphore>();\n private permits: number;\n\n constructor(permits = 1) {\n this.permits = permits;\n }\n\n private getSemaphore(key: K): Semaphore {\n let semaphore = this.semaphores.get(key);\n if (!semaphore) {\n semaphore = new Semaphore(this.permits);\n this.semaphores.set(key, semaphore);\n }\n return semaphore;\n }\n\n async acquire(key: K): Promise<void> {\n const semaphore = this.getSemaphore(key);\n return semaphore.acquire();\n }\n\n release(key: K): void {\n const semaphore = this.semaphores.get(key);\n if (semaphore) {\n semaphore.release();\n // Clean up if no one is waiting\n if (semaphore.available === this.permits && semaphore.waiting === 0) {\n this.semaphores.delete(key);\n }\n }\n }\n\n async runExclusive<T>(key: K, fn: () => Promise<T>): Promise<T> {\n const semaphore = this.getSemaphore(key);\n return semaphore.runExclusive(fn);\n }\n\n isLocked(key: K): boolean {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.available === 0 : false;\n }\n\n clear(): void {\n this.semaphores.clear();\n }\n}\n","import { AGENT_STATUS, AGENT_TYPES, type DaemonStartAgentRequestEvent } from '@agimonai/universal-agent-events';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport stripAnsi from 'strip-ansi';\nimport { createSelectComponent, createToolInvocationInput, DetectedOption } from '../llms/messages';\nimport { FileSystemUtils } from '../utils/fileSystem';\nimport { AgentInfo, BaseAgent, BaseAgentOptions } from './base';\n\nexport interface GeminiAgentOptions extends BaseAgentOptions {\n geminiPath?: string; // executable path (default: 'gemini')\n}\n\n/**\n * GeminiAgent: PTY-based agent for Gemini CLI.\n * Responsibilities:\n * - Spawn gemini CLI process\n * - Relay stdout to BaseAgent output channel\n * - Uses PtyRunnerService from BaseAgent\n * - Uses network logging hook (NODE_OPTIONS --require networkLog) like ClaudeAgent\n */\nexport class GeminiAgent extends BaseAgent {\n private geminiPath: string;\n // Path to generated Gemini extension config file (if any)\n private tempExtensionConfigPath: string | null = null;\n // Track agent ready state\n private agentInputReady: boolean = false;\n // Option detection state (mirrors ClaudeAgent minimal subset)\n private optionBuffer = '';\n private optionTimeout: NodeJS.Timeout | null = null;\n private isCollectingOptions = false;\n private readonly OPTION_WAIT_MS = 1000; // collect for 1s after first detection\n\n constructor(opts: GeminiAgentOptions) {\n super({ ...opts, agentType: AGENT_TYPES.GEMINI_CLI });\n this.geminiPath = opts.geminiPath || 'gemini';\n }\n\n async launchAgent(request: DaemonStartAgentRequestEvent): Promise<AgentInfo> {\n const { payload } = request;\n const agentSessionId = payload.agentSessionId;\n const workingDir = payload.agentConfig?.workingDirectory\n ? FileSystemUtils.getAbsolutePath(payload.agentConfig.workingDirectory)\n : process.cwd();\n\n // Check if xterm is enabled\n const xtermEnabled = payload.agentConfig?.xterm ?? false;\n this.setXtermEnabled(xtermEnabled);\n\n // Execute pre-agent start hooks (will use defaults if none provided)\n // Support both preAgentStart and preAgentStartHooks property names for backward compatibility\n const userHooks = payload.agentConfig?.hooks?.preAgentStartHooks || payload.agentConfig?.hooks?.preAgentStart;\n await this.executePreAgentStartHooks(userHooks, workingDir, agentSessionId);\n\n // Generate Gemini extension config file if mcps provided\n this.logger.debug('Agent config MCPs:', payload.agentConfig?.mcps);\n const extensionConfigPath = await this.writeGeminiExtensionFile(payload.agentConfig?.mcps, workingDir);\n this.logger.debug('Custom Gemini extension config result:', extensionConfigPath);\n\n // Detect project-level Gemini extension config (agiflow-extension.json) in working directory\n const projectExtensionConfigPath = path.join(workingDir, 'agiflow-extension.json');\n this.logger.debug('Project Gemini extension config path:', projectExtensionConfigPath);\n\n // Establish WebSocket session first\n await this.connectToSession(agentSessionId);\n\n // Setup Docker repository if Docker mode is enabled\n await this.setupDockerRepository(request);\n\n // Build Gemini CLI args\n const args = this.buildGeminiArgs(request);\n\n // Log extension config files for debugging (Gemini auto-discovers them from .gemini/extensions/)\n if (fs.existsSync(projectExtensionConfigPath)) {\n this.logger.debug(`Found project Gemini extension config: ${projectExtensionConfigPath}`);\n } else {\n this.logger.debug('No project agiflow-extension.json found in working directory');\n }\n if (extensionConfigPath) {\n this.logger.debug(`Created Gemini extension config: ${extensionConfigPath}`);\n }\n\n try {\n const agentEnv = this.getAgentEnvironmentVariables();\n const nodeOptions = this.configureNodeOptions(agentEnv); // adds network logging hook\n\n const ptySession = this.ptyRunner.spawn(\n {\n command: this.geminiPath,\n args,\n workingDir,\n agentSessionId,\n logger: this.logger,\n agentApiKey: this.apiKey,\n agentOrganizationId: this.organizationId,\n agentServerUrl: this.serverUrl,\n agentType: this.agentType,\n env: {\n ...agentEnv,\n NODE_OPTIONS: nodeOptions,\n GEMINI_SESSION_ID: agentSessionId,\n GEMINI_AGENT_SESSION_ID: agentSessionId,\n GEMINI_AGENT_MODE: 'true',\n ...(extensionConfigPath ? { GEMINI_EXTENSION_CONFIG_FILE: extensionConfigPath } : {}),\n },\n },\n {\n onData: async (data) => {\n // Detect readiness of the Gemini CLI\n this.verifyAgentReady(data);\n\n // Option detection (Gemini prompt style)\n this.processDataForOptions(data);\n\n // Send stdout event if xterm is enabled\n if (this.xtermEnabled) {\n this.sendStdoutEvent(data);\n }\n },\n onExit: async (exitCode, signal) => {\n // Remove temp Gemini extension config file\n if (this.tempExtensionConfigPath) {\n try {\n fs.unlinkSync(this.tempExtensionConfigPath);\n this.logger.debug(`Deleted temp Gemini extension config file: ${this.tempExtensionConfigPath}`);\n } catch (e) {\n this.logger.warn('Failed to delete temp Gemini extension config file', e as Error);\n }\n this.tempExtensionConfigPath = null;\n }\n\n this.logger.info(`Gemini PTY exited with code ${exitCode}, signal: ${signal}`);\n this.sendAgentStatus({\n agentType: AGENT_TYPES.GEMINI_CLI,\n status: exitCode === 0 ? AGENT_STATUS.STOPPED : AGENT_STATUS.ERROR,\n message: `Gemini session ended (exit code: ${exitCode})`,\n });\n // Clean up WebSocket connection when PTY exits naturally\n if (this.wsService) {\n this.wsService.disconnect();\n }\n this.ptySessionId = null;\n if (this.agentInfo) {\n await this.terminationService.handlePtyTermination({\n agentSessionId: this.agentInfo.agentSessionId,\n reason: 'natural',\n exitCode,\n signal: signal as NodeJS.Signals | undefined,\n });\n }\n },\n },\n );\n\n this.logger.success(`Gemini launched successfully for session agentSessionId: ${agentSessionId}`);\n this.ptySessionId = ptySession.id;\n\n // Setup initial PTY size if xterm is not enabled to fit terminal\n if (!xtermEnabled) {\n this.setupInitialPtySize();\n } else {\n this.resizePty(80, 24);\n }\n\n const agentInfo: AgentInfo = {\n agentSessionId,\n agentType: AGENT_TYPES.GEMINI_CLI,\n status: AGENT_STATUS.IDLE,\n workingDir,\n process: ptySession.ptyProcess,\n metadata: {\n agentSessionId,\n agentType: payload.agentType,\n config: payload.agentConfig,\n ptySessionId: ptySession.id,\n },\n };\n this.setAgentInfo(agentInfo);\n return agentInfo;\n } catch (error) {\n throw new Error(`Failed to launch Gemini: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async isAvailable(): Promise<boolean> {\n return true;\n }\n\n async getVersion(): Promise<string | null> {\n return 'gemini-pty-agent';\n }\n\n /**\n * Detect when Gemini's interactive input becomes available.\n * Similar to Claude's ready detection but adapted for Gemini CLI patterns.\n */\n private verifyAgentReady(data: string): void {\n if (this.agentInputReady) return;\n\n // Remove ANSI escape codes for clean pattern matching\n const stripAnsi = (str: string): string => {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequence regex intentionally uses \\x1b control character\n return str.replace(/\\x1b\\[[0-9;]*m/g, '');\n };\n\n const cleaned = stripAnsi(data);\n\n // Patterns that may indicate Gemini CLI is ready for input\n const patterns: RegExp[] = [\n /Type (your )?(message|prompt)/i,\n /Enter (your )?(message|command)/i,\n /gemini>/i, // Gemini prompt\n /Ready for input/i,\n /Session started/i,\n // Box drawing patterns that might indicate prompt area\n /╭[\\s\\S]*?╰/m,\n /┌[\\s\\S]*?└/m,\n />/, // Simple prompt indicator\n ];\n\n const isReady = patterns.some((p) => p.test(cleaned));\n if (!isReady) return;\n\n this.agentInputReady = true;\n this.logger.debug('Gemini agent detected as ready for input');\n\n // Send agent status update\n this.sendAgentStatus({\n agentType: AGENT_TYPES.GEMINI_CLI,\n status: AGENT_STATUS.IDLE,\n message: 'Gemini ready for commands',\n });\n }\n\n private buildGeminiArgs(request: DaemonStartAgentRequestEvent): string[] {\n const args: string[] = request.payload?.agentConfig?.args || [];\n\n // Add session-id flag if conversationSessionId is provided\n const conversationSessionId = request.payload?.agentConfig?.conversationSessionId;\n if (conversationSessionId) {\n args.push('--session-id', conversationSessionId);\n }\n\n return args;\n }\n\n /**\n * Process incoming PTY data for option detection. We look for numbered options\n * inside box-drawing prompts similar to the example provided:\n * ● 1. Yes, allow once\n * 2. Yes, allow always\n * 3. No, suggest changes (esc)\n * We trigger collection when we see either a leading bullet (●) with a number option\n * or boxed question line (\"Do you want to proceed?\") combined with numbered lines.\n */\n private processDataForOptions(data: string): void {\n this.optionBuffer += data;\n const cleaned = stripAnsi(data);\n\n const hasOptions =\n /Do you want to proceed\\?/m.test(cleaned) || // explicit confirmation style\n /●\\s*\\d+\\.\\s+/.test(cleaned) || // selected / primary option line\n /\\n\\s{0,4}\\d+\\.\\s+[^\\n]+/.test(cleaned); // generic numbered options\n\n if (hasOptions && !this.isCollectingOptions) {\n this.startOptionCollection();\n }\n }\n\n /** Start the timed collection window for grouping option chunks */\n private startOptionCollection(): void {\n this.isCollectingOptions = true;\n if (this.optionTimeout) clearTimeout(this.optionTimeout);\n this.optionTimeout = setTimeout(() => {\n void this.processCollectedOptions();\n }, this.OPTION_WAIT_MS);\n }\n\n /** After timeout, extract and send detected options */\n private async processCollectedOptions(): Promise<void> {\n const cleanedBuffer = stripAnsi(this.optionBuffer);\n const options = this.extractOptions(cleanedBuffer);\n if (options.length) {\n await this.handleDetectedOptions(options);\n }\n this.resetOptionState();\n }\n\n private resetOptionState(): void {\n this.optionBuffer = '';\n this.optionTimeout = null;\n this.isCollectingOptions = false;\n }\n\n /** Extract numbered options; treat a leading bullet (●) as selected */\n private extractOptions(text: string): DetectedOption[] {\n const out: DetectedOption[] = [];\n const lines = text.split('\\n');\n for (const raw of lines) {\n const line = raw.trim();\n // Selected (bullet) line e.g. \"● 1. Yes, allow once\"\n let m = line.match(/^●\\s*(\\d+)\\.\\s+(.+)$/);\n if (m) {\n out.push({ number: parseInt(m[1], 10), text: m[2].trim(), selected: true });\n continue;\n }\n // Unselected numbered option line (allow preceding optional box border or bullet spacing)\n m = line.match(/^(?:[│|]?\\s*)?(\\d+)\\.\\s+(.+)$/);\n if (m) {\n out.push({ number: parseInt(m[1], 10), text: m[2].trim() });\n }\n }\n // Deduplicate by number (keep first occurrence which might preserve selection)\n const seen = new Set<number>();\n return out.filter((o) => {\n if (seen.has(o.number)) return false;\n seen.add(o.number);\n return true;\n });\n }\n\n /** Send structured select component message via HTTP service using request approval endpoint */\n private async handleDetectedOptions(options: DetectedOption[]): Promise<void> {\n if (!options.length || !this.agentInfo || !this.httpService) return;\n const timestamp = new Date().toISOString();\n\n try {\n const optionsData = options.map((o) => ({ label: o.text, value: o.number, selected: !!o.selected }));\n const selectComponent = createSelectComponent(optionsData);\n const toolInput = createToolInvocationInput(false, selectComponent);\n\n // Use the request approval endpoint instead of sending a regular message\n await this.httpService.requestApproval(this.agentInfo.agentSessionId, {\n toolName: 'selectOption',\n toolArgs: { timestamp, options: optionsData },\n input: toolInput,\n });\n\n this.logger.debug('Sent Gemini option selection approval request');\n } catch (err) {\n this.logger.warn('Failed to send Gemini options approval request', err as Error);\n }\n }\n\n /**\n * Write Gemini extension configuration file to .gemini/extensions/ folder in git repo root.\n * Converts MCP server configuration to Gemini extension format.\n * Returns file path or null.\n */\n private async writeGeminiExtensionFile(rawMcps: any, workingDir: string): Promise<string | null> {\n this.logger.debug('writeGeminiExtensionFile called', { rawMcps, workingDir });\n if (!rawMcps) {\n this.logger.debug('No MCPs provided, returning null');\n return null;\n }\n\n try {\n // Normalize into record of MCP servers\n const mcpServers: Record<string, any> = {};\n if (Array.isArray(rawMcps)) {\n for (const item of rawMcps) {\n if (!item || typeof item !== 'object') continue;\n const name = item.name || item.id || item.key;\n if (!name) continue;\n\n // Convert MCP server config to Gemini extension format\n const serverConfig: any = {};\n\n if (item.type === 'sse') {\n // SSE servers use url\n serverConfig.url = item.url;\n if (item.headers && Object.keys(item.headers).length > 0) {\n serverConfig.headers = item.headers;\n }\n } else {\n // Stdio servers use command and args\n serverConfig.command = item.command;\n if (item.args && item.args.length > 0) {\n serverConfig.args = item.args;\n }\n }\n\n if (item.env && Object.keys(item.env).length > 0) {\n serverConfig.env = item.env;\n }\n\n if (item.disabled) {\n serverConfig.disabled = item.disabled;\n }\n\n mcpServers[name] = serverConfig;\n }\n } else if (typeof rawMcps === 'object') {\n // Convert record format - already in desired shape, just clean up\n for (const [key, value] of Object.entries(rawMcps)) {\n if (value && typeof value === 'object') {\n const item = value as any;\n const serverConfig: any = {};\n\n if (item.type === 'sse' || item.url) {\n serverConfig.url = item.url;\n if (item.headers && Object.keys(item.headers).length > 0) {\n serverConfig.headers = item.headers;\n }\n } else {\n serverConfig.command = item.command;\n if (item.args && item.args.length > 0) {\n serverConfig.args = item.args;\n }\n }\n\n if (item.env && Object.keys(item.env).length > 0) {\n serverConfig.env = item.env;\n }\n\n if (item.disabled) {\n serverConfig.disabled = item.disabled;\n }\n\n mcpServers[key] = serverConfig;\n }\n }\n }\n\n if (Object.keys(mcpServers).length === 0) return null;\n\n // Find git repo root, fallback to user home directory\n const gitRepoRoot = await this.findGitRepoRoot(workingDir);\n const baseDir = gitRepoRoot || os.homedir();\n this.logger.debug(`Using base directory for Gemini extension: ${baseDir}`);\n\n // Create .gemini/extensions directory if it doesn't exist\n const geminiExtensionsDir = path.join(baseDir, '.gemini', 'extensions');\n if (!fs.existsSync(geminiExtensionsDir)) {\n fs.mkdirSync(geminiExtensionsDir, { recursive: true });\n this.logger.debug(`Created directory: ${geminiExtensionsDir}`);\n }\n\n // Create Gemini extension format\n const extensionData = {\n name: 'agiflow-mcps',\n version: '1.0.0',\n mcpServers,\n contextFileName: 'GEMINI.md',\n excludeTools: ['run_shell_command'],\n };\n\n const fileName = 'agiflow-extension.json';\n const filePath = path.join(geminiExtensionsDir, fileName);\n fs.writeFileSync(filePath, JSON.stringify(extensionData, null, 2), 'utf8');\n this.logger.debug(`Gemini extension config written to: ${filePath}`);\n this.tempExtensionConfigPath = filePath;\n\n // Ensure .gitignore includes this file (only if in a git repo)\n if (gitRepoRoot) {\n await this.ensureGitignoreEntry(gitRepoRoot, '.gemini/extensions/agiflow-extension.json');\n }\n\n return filePath;\n } catch (err) {\n this.logger.warn('Failed to write Gemini extension config file', err as Error);\n return null;\n }\n }\n\n /**\n * Find the git repository root by walking up the directory tree\n */\n private async findGitRepoRoot(startDir: string): Promise<string | null> {\n let currentDir = path.resolve(startDir);\n const root = path.parse(currentDir).root;\n\n while (currentDir !== root) {\n const gitDir = path.join(currentDir, '.git');\n if (fs.existsSync(gitDir)) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n\n return null;\n }\n\n /**\n * Ensure .gitignore contains the specified entry\n */\n private async ensureGitignoreEntry(gitRepoRoot: string, entry: string): Promise<void> {\n const gitignorePath = path.join(gitRepoRoot, '.gitignore');\n\n try {\n let gitignoreContent = '';\n if (fs.existsSync(gitignorePath)) {\n gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');\n }\n\n // Check if entry already exists\n const lines = gitignoreContent.split('\\n');\n const entryExists = lines.some((line) => line.trim() === entry);\n\n if (!entryExists) {\n // Add entry to .gitignore\n const newContent =\n gitignoreContent.endsWith('\\n') || gitignoreContent === ''\n ? gitignoreContent + entry + '\\n'\n : gitignoreContent + '\\n' + entry + '\\n';\n\n fs.writeFileSync(gitignorePath, newContent, 'utf8');\n this.logger.debug(`Added '${entry}' to .gitignore`);\n } else {\n this.logger.debug(`Entry '${entry}' already exists in .gitignore`);\n }\n } catch (error) {\n this.logger.warn(`Failed to update .gitignore: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n}\n","import { execSync } from 'child_process';\nimport { existsSync } from 'fs';\nimport { basename, join, resolve } from 'path';\nimport { Logger } from '../utils';\n\nexport interface GitWorktreeOptions {\n repositoryPath: string;\n branch?: string;\n worktreeName?: string;\n logger?: Logger;\n}\n\nexport interface GitWorktreeInfo {\n path: string;\n branch: string;\n commit: string;\n isActive: boolean;\n name: string;\n}\n\nexport class GitWorktreeService {\n private logger: Logger;\n private repositoryPath: string;\n private originalRepositoryPath: string;\n private activeWorktrees: Map<string, GitWorktreeInfo> = new Map();\n private canPush: boolean | null = null; // Cache push capability check\n\n constructor(repositoryPath: string, logger?: Logger) {\n this.originalRepositoryPath = resolve(repositoryPath);\n this.repositoryPath = this.originalRepositoryPath;\n this.logger = logger ?? new Logger({ verbose: false });\n\n // Validate that the repository path is a git repository\n if (!this.isGitRepository()) {\n throw new Error(`Path ${this.originalRepositoryPath} is not a git repository`);\n }\n }\n\n /**\n * Check if the given path is within a git repository\n * Traverses up the directory tree to find the git root\n */\n private isGitRepository(): boolean {\n try {\n let currentPath = resolve(this.repositoryPath);\n const rootPath = resolve('/');\n let iterations = 0;\n const maxIterations = 15; // Safety limit to prevent infinite loops\n\n while (currentPath !== rootPath && iterations < maxIterations) {\n const gitDir = join(currentPath, '.git');\n if (existsSync(gitDir)) {\n // Update repositoryPath to the actual git root\n this.repositoryPath = currentPath;\n return true;\n }\n\n const parentPath = resolve(currentPath, '..');\n // Additional safety check: if parent is same as current, we've reached the top\n if (parentPath === currentPath) {\n break;\n }\n\n currentPath = parentPath;\n iterations++;\n }\n\n return false;\n } catch {\n return false;\n }\n }\n\n /**\n * Execute git command in the repository\n */\n private execGit(command: string, cwd?: string): string {\n try {\n const result = execSync(`git ${command}`, {\n cwd: cwd || this.repositoryPath,\n encoding: 'utf8',\n stdio: 'pipe',\n });\n return result.trim();\n } catch (error: any) {\n // Preserve the original error with status code for proper handling\n // Don't log errors that are expected (like diff --exit-code returning 1)\n const isExpectedError = command.includes('diff --cached --exit-code') && error.status === 1;\n\n if (!isExpectedError) {\n this.logger.error(`Git command failed: git ${command}`, error);\n }\n\n const gitError = new Error(`Git command failed: ${error.message}`) as any;\n gitError.status = error.status;\n gitError.signal = error.signal;\n gitError.output = error.output;\n throw gitError;\n }\n }\n\n /**\n * Get current branch name\n */\n getCurrentBranch(): string {\n return this.execGit('branch --show-current');\n }\n\n /**\n * Get current commit hash\n */\n getCurrentCommit(): string {\n return this.execGit('rev-parse HEAD');\n }\n\n /**\n * List all existing worktrees\n */\n listWorktrees(): GitWorktreeInfo[] {\n try {\n const output = this.execGit('worktree list --porcelain');\n const worktrees: GitWorktreeInfo[] = [];\n\n const entries = output.split('\\n\\n').filter((entry) => entry.trim());\n\n for (const entry of entries) {\n const lines = entry.split('\\n');\n let path = '';\n let branch = '';\n let commit = '';\n\n for (const line of lines) {\n if (line.startsWith('worktree ')) {\n path = line.substring(9);\n } else if (line.startsWith('branch ')) {\n branch = line.substring(7);\n } else if (line.startsWith('HEAD ')) {\n commit = line.substring(5);\n }\n }\n\n if (path) {\n worktrees.push({\n path,\n branch: branch || 'detached',\n commit,\n isActive: path === this.repositoryPath,\n name: basename(path),\n });\n }\n }\n\n return worktrees;\n } catch (error) {\n this.logger.debug('No worktrees found or git worktree not supported');\n return [];\n }\n }\n\n /**\n * Create a new worktree\n */\n async createWorktree(options: GitWorktreeOptions): Promise<GitWorktreeInfo> {\n const { branch, worktreeName } = options;\n\n // Get repository name from git root to avoid recursion\n // Always use the git root directory name, not any subdirectory\n const gitRoot = this.repositoryPath;\n const repoName = basename(gitRoot);\n\n // Generate branch name if not provided\n const finalBranch = branch || this.generateUniqueBranchName();\n\n // Create worktree directory name based on repo and branch\n const sanitizedBranch = this.sanitizeBranchName(finalBranch);\n const worktreeDirName = `${repoName}-worktrees`;\n const worktreeName_final = worktreeName || sanitizedBranch;\n\n // Create worktree path in parent directory with consistent naming\n const parentDir = join(this.repositoryPath, '..');\n const worktreesDir = join(parentDir, worktreeDirName);\n const worktreePath = join(worktreesDir, worktreeName_final);\n\n // Ensure the worktrees directory exists\n if (!existsSync(worktreesDir)) {\n const fs = await import('fs/promises');\n await fs.mkdir(worktreesDir, { recursive: true });\n }\n\n try {\n // Check if branch exists\n let gitCommand = `worktree add \"${worktreePath}\"`;\n\n // Check if branch is already checked out in another worktree\n if (this.isBranchCheckedOutInWorktree(finalBranch)) {\n throw new Error(\n `Branch '${finalBranch}' is already checked out in another worktree. Use a different branch name or specify a unique branch.`,\n );\n }\n\n // Check if branch exists locally\n const localBranchExists = this.checkBranchExists(`refs/heads/${finalBranch}`);\n let remoteBranchExists = false;\n\n if (localBranchExists) {\n gitCommand += ` ${finalBranch}`;\n } else {\n // Branch doesn't exist locally, check if it exists on remote\n remoteBranchExists = this.checkBranchExists(`refs/remotes/origin/${finalBranch}`);\n if (remoteBranchExists) {\n gitCommand += ` -b ${finalBranch} origin/${finalBranch}`;\n } else {\n // Create new branch\n gitCommand += ` -b ${finalBranch}`;\n }\n }\n\n this.logger.info(`Creating worktree at ${worktreePath}`);\n this.execGit(gitCommand);\n\n // Get worktree info\n const commit = this.execGit('rev-parse HEAD', worktreePath);\n const currentBranch = finalBranch || this.execGit('branch --show-current', worktreePath);\n\n const worktreeInfo: GitWorktreeInfo = {\n path: worktreePath,\n branch: currentBranch,\n commit,\n isActive: false,\n name: worktreeName_final,\n };\n\n this.activeWorktrees.set(worktreeName_final, worktreeInfo);\n this.logger.success(`Worktree created successfully at ${worktreePath}`);\n\n // Push the new branch to remote immediately to avoid issues during cleanup\n // This ensures the branch exists remotely for later operations\n if (!localBranchExists && !remoteBranchExists) {\n try {\n this.logger.info(`Pushing new branch ${currentBranch} to remote`);\n this.execGit(`push --set-upstream origin ${currentBranch}`, worktreePath);\n this.logger.success(`Branch ${currentBranch} pushed to remote`);\n } catch (pushError: any) {\n this.logger.warn(`Could not push branch to remote: ${pushError.message}`);\n // Don't fail worktree creation if push fails - it can be pushed later\n }\n }\n\n return worktreeInfo;\n } catch (error: any) {\n this.logger.error(`Failed to create worktree: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Commit changes in a worktree\n */\n async commitChanges(worktreePath: string, message: string, addAll = true, skipVerify = false): Promise<void> {\n try {\n // First, respect .gitignore by cleaning up any untracked files that should be ignored\n try {\n this.execGit('clean -fd -e node_modules', worktreePath);\n } catch (cleanError) {\n this.logger.debug('Git clean warning (non-fatal):', cleanError);\n }\n\n if (addAll) {\n // Only add tracked files and respect .gitignore\n this.execGit('add -u', worktreePath);\n // Then add any new files that aren't ignored\n this.execGit('add .', worktreePath);\n }\n\n // Check if there are changes to commit\n try {\n this.execGit('diff --cached --exit-code', worktreePath);\n this.logger.info('No changes to commit in worktree');\n return;\n } catch (error: any) {\n // Exit code 1 means there are changes to commit (expected)\n // Any other exit code is a real error\n if (error.status !== 1 && error.status !== undefined) {\n this.logger.error(`Git diff failed with unexpected status: ${error.status}`);\n throw error;\n }\n // Status 1 or undefined (from execSync) means changes exist - continue with commit\n this.logger.debug('Changes detected in staging area, proceeding with commit');\n }\n\n const skipVerifyFlag = skipVerify ? '--no-verify' : '';\n this.execGit(`commit ${skipVerifyFlag} -m \"${message}\"`.trim(), worktreePath);\n this.logger.success(`Changes committed in worktree: ${worktreePath}`);\n } catch (error: any) {\n this.logger.error(`Failed to commit changes: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Push changes from a worktree to remote\n */\n async pushChanges(worktreePath: string, remote = 'origin', branch?: string): Promise<void> {\n // Check if we can push before attempting\n const canPush = await this.canPushToRemote(remote);\n if (!canPush) {\n throw new Error(\n `Cannot push to remote '${remote}' - no valid authentication method found. Please set up SSH keys or store HTTPS credentials.`,\n );\n }\n\n try {\n const currentBranch = branch || this.execGit('branch --show-current', worktreePath);\n\n if (!currentBranch) {\n throw new Error('No branch to push (detached HEAD)');\n }\n\n // For worktree branches, always push with --set-upstream to ensure remote branch is created\n // This handles both new branches and existing ones gracefully\n try {\n this.logger.debug(`Pushing branch ${currentBranch} to ${remote}`);\n this.execGit(`push --set-upstream ${remote} ${currentBranch}`, worktreePath);\n } catch (pushError: any) {\n // If push fails, it might be because the branch already has an upstream\n // Try a regular push as fallback\n try {\n this.logger.debug(`Retrying push without --set-upstream for ${currentBranch}`);\n this.execGit(`push ${remote} ${currentBranch}`, worktreePath);\n } catch (fallbackError: any) {\n // Check for common push failure reasons\n const errorMessage = fallbackError.message || '';\n if (errorMessage.includes('permission') || errorMessage.includes('denied')) {\n this.logger.error(`Push failed: No permission to push to ${remote}/${currentBranch}`);\n } else if (errorMessage.includes('Could not read from remote repository')) {\n this.logger.error(`Push failed: Cannot access remote repository. Check your SSH keys or credentials.`);\n } else if (errorMessage.includes('does not appear to be a git repository')) {\n this.logger.error(`Push failed: Remote '${remote}' is not configured properly`);\n } else {\n this.logger.error(`Failed to push branch ${currentBranch}: ${errorMessage}`);\n }\n throw fallbackError;\n }\n }\n\n this.logger.success(`Changes pushed to ${remote}/${currentBranch}`);\n\n // Create a PR if gh CLI is available and we're not on the main branch\n await this.createPullRequestIfPossible(worktreePath, currentBranch);\n } catch (error: any) {\n this.logger.error(`Failed to push changes: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Commit and push changes in a worktree\n */\n async commitAndPush(\n worktreePath: string,\n commitMessage: string,\n remote = 'origin',\n branch?: string,\n skipVerify = false,\n ): Promise<void> {\n await this.commitChanges(worktreePath, commitMessage, true, skipVerify);\n await this.pushChanges(worktreePath, remote, branch);\n }\n\n /**\n * Remove a worktree\n */\n async removeWorktree(worktreePath: string, force = false): Promise<void> {\n try {\n const forceFlag = force ? '--force' : '';\n this.execGit(`worktree remove ${forceFlag} \"${worktreePath}\"`);\n\n // Remove from active worktrees map\n for (const [name, info] of this.activeWorktrees.entries()) {\n if (info.path === worktreePath) {\n this.activeWorktrees.delete(name);\n break;\n }\n }\n\n this.logger.success(`Worktree removed: ${worktreePath}`);\n } catch (error: any) {\n this.logger.error(`Failed to remove worktree: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Switch to a different worktree (changes working directory context)\n */\n switchToWorktree(worktreePath: string): GitWorktreeInfo {\n if (!existsSync(worktreePath)) {\n throw new Error(`Worktree path does not exist: ${worktreePath}`);\n }\n\n // Verify it's a valid worktree\n try {\n const commit = this.execGit('rev-parse HEAD', worktreePath);\n const branch = this.execGit('branch --show-current', worktreePath);\n\n const worktreeInfo: GitWorktreeInfo = {\n path: worktreePath,\n branch: branch || 'detached',\n commit,\n isActive: true,\n name: basename(worktreePath),\n };\n\n this.logger.info(`Switched to worktree: ${worktreePath} (${branch})`);\n return worktreeInfo;\n } catch (error: any) {\n this.logger.error(`Failed to switch to worktree: ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Get worktree info by path\n */\n getWorktreeInfo(worktreePath: string): GitWorktreeInfo | null {\n try {\n const commit = this.execGit('rev-parse HEAD', worktreePath);\n const branch = this.execGit('branch --show-current', worktreePath);\n\n return {\n path: worktreePath,\n branch: branch || 'detached',\n commit,\n isActive: false,\n name: basename(worktreePath),\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Clean up all managed worktrees with optional commit and push\n */\n async cleanup(commitAndPush = true, commitMessage = 'Agent work completed'): Promise<void> {\n this.logger.info('Cleaning up worktrees...');\n\n // Check push capability once if we need to push\n let canPushToRemote = false;\n if (commitAndPush) {\n canPushToRemote = await this.canPushToRemote();\n if (!canPushToRemote) {\n this.logger.warn('Cannot push to remote - will only commit changes locally');\n }\n }\n\n for (const [, info] of this.activeWorktrees.entries()) {\n try {\n if (commitAndPush) {\n try {\n if (canPushToRemote) {\n await this.commitAndPush(info.path, commitMessage, 'origin', undefined, true);\n this.logger.info(`Committed and pushed changes for worktree: ${info.path}`);\n } else {\n // Only commit locally if we can't push\n await this.commitChanges(info.path, commitMessage, true, true);\n this.logger.info(`Committed changes locally for worktree: ${info.path}`);\n }\n } catch (error) {\n this.logger.warn(`Failed to commit/push worktree ${info.path}: ${error}`);\n }\n }\n\n await this.removeWorktree(info.path, true);\n } catch (error) {\n this.logger.warn(`Failed to remove worktree ${info.path}: ${error}`);\n }\n }\n\n this.activeWorktrees.clear();\n this.logger.success('Worktree cleanup completed');\n }\n\n /**\n * Get the repository root path\n */\n getRepositoryPath(): string {\n return this.repositoryPath;\n }\n\n /**\n * Get all active worktrees managed by this service\n */\n getActiveWorktrees(): Map<string, GitWorktreeInfo> {\n return new Map(this.activeWorktrees);\n }\n\n /**\n * Check if git worktree is supported\n */\n isWorktreeSupported(): boolean {\n try {\n this.execGit('worktree --help');\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Check if push operations are possible without user interaction\n * Tests if we can push to the remote without password prompts\n */\n async canPushToRemote(remote = 'origin'): Promise<boolean> {\n if (this.canPush !== null) {\n return this.canPush;\n }\n\n try {\n // First check if remote exists\n const remoteUrl = this.execGit(`remote get-url ${remote}`);\n\n // If it's an SSH URL, check if SSH key authentication works\n if (remoteUrl.startsWith('git@') || remoteUrl.includes('ssh://')) {\n return (this.canPush = await this.testSshConnection(remoteUrl));\n }\n\n // If it's HTTPS, check if credentials are stored\n if (remoteUrl.startsWith('https://')) {\n return (this.canPush = await this.testHttpsCredentials(remote));\n }\n\n // Unknown protocol, assume no push capability\n this.logger.warn(`Unknown git remote protocol: ${remoteUrl}`);\n return (this.canPush = false);\n } catch (error) {\n this.logger.debug(`Cannot determine push capability: ${error}`);\n return (this.canPush = false);\n }\n }\n\n /**\n * Test SSH connection for git operations\n */\n private async testSshConnection(remoteUrl: string): Promise<boolean> {\n try {\n // Extract hostname from SSH URL (git@github.com:user/repo.git -> github.com)\n const hostname = remoteUrl.split('@')[1]?.split(':')[0] || remoteUrl.split('/')[2];\n\n if (!hostname) {\n return false;\n }\n\n // Test SSH connection with a short timeout\n execSync(`ssh -T -o ConnectTimeout=5 -o BatchMode=yes git@${hostname}`, {\n stdio: 'pipe',\n timeout: 10000,\n });\n\n return true;\n } catch (error: any) {\n // SSH test failed, but check if it's just the expected \"Hi username!\" rejection\n // GitHub, GitLab, etc. reject shell access but allow git operations\n if (error.status === 1 && error.stderr?.includes('successfully authenticated')) {\n return true;\n }\n\n this.logger.debug(`SSH test failed: ${error.message}`);\n return false;\n }\n }\n\n /**\n * Test HTTPS credentials for git operations\n */\n private async testHttpsCredentials(remote: string): Promise<boolean> {\n try {\n // Try to fetch from remote with a timeout to see if credentials work\n execSync(`git ls-remote --exit-code ${remote} HEAD`, {\n cwd: this.repositoryPath,\n stdio: 'pipe',\n timeout: 10000,\n });\n\n return true;\n } catch (error) {\n this.logger.debug(`HTTPS credentials test failed: ${error}`);\n return false;\n }\n }\n\n /**\n * Check if a git reference exists without throwing errors\n */\n private checkBranchExists(ref: string): boolean {\n try {\n execSync(`git show-ref --verify --quiet ${ref}`, {\n cwd: this.repositoryPath,\n stdio: 'pipe',\n });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Check if a branch is already checked out in another worktree\n */\n private isBranchCheckedOutInWorktree(branchName: string): boolean {\n try {\n const worktrees = this.listWorktrees();\n return worktrees.some((worktree) => worktree.branch === branchName && worktree.path !== this.repositoryPath);\n } catch {\n return false;\n }\n }\n\n /**\n * Generate a unique branch name for agent work\n */\n private generateUniqueBranchName(): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);\n const randomSuffix = Math.random().toString(36).substring(2, 8);\n return `agent-work-${timestamp}-${randomSuffix}`;\n }\n\n /**\n * Sanitize branch name for use as directory name\n */\n private sanitizeBranchName(branchName: string): string {\n return branchName\n .replace(/[^a-zA-Z0-9-_]/g, '-') // Replace invalid chars with dash\n .replace(/--+/g, '-') // Replace multiple dashes with single dash\n .replace(/^-|-$/g, '') // Remove leading/trailing dashes\n .toLowerCase();\n }\n\n /**\n * Check if GitHub CLI is available\n */\n private isGhCliAvailable(): boolean {\n try {\n execSync('gh --version', { stdio: 'pipe' });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get the default/main branch name\n */\n private getMainBranch(): string {\n try {\n // Try to get the default branch from git config\n const defaultBranch = this.execGit('config --get init.defaultBranch').trim();\n if (defaultBranch) {\n return defaultBranch;\n }\n } catch {\n // Ignore error and try other methods\n }\n\n try {\n // Try to get from remote HEAD\n const remoteHead = this.execGit('symbolic-ref refs/remotes/origin/HEAD').trim();\n if (remoteHead) {\n return remoteHead.replace('refs/remotes/origin/', '');\n }\n } catch {\n // Ignore error and use fallback\n }\n\n // Check common main branch names\n const commonMainBranches = ['main', 'master'];\n for (const branch of commonMainBranches) {\n if (this.checkBranchExists(`refs/heads/${branch}`) || this.checkBranchExists(`refs/remotes/origin/${branch}`)) {\n return branch;\n }\n }\n\n // Default to 'main' if nothing else works\n return 'main';\n }\n\n /**\n * Create a pull request using GitHub CLI if available\n */\n private async createPullRequestIfPossible(worktreePath: string, currentBranch: string): Promise<void> {\n // Check if gh CLI is available\n if (!this.isGhCliAvailable()) {\n this.logger.debug('GitHub CLI not available, skipping PR creation');\n return;\n }\n\n // Get the main branch\n const mainBranch = this.getMainBranch();\n\n // Don't create PR if we're already on the main branch\n if (currentBranch === mainBranch) {\n this.logger.debug(`Already on main branch (${mainBranch}), skipping PR creation`);\n return;\n }\n\n try {\n // Check if PR already exists for this branch\n const existingPR = execSync(`gh pr list --head \"${currentBranch}\" --json number`, {\n cwd: worktreePath,\n encoding: 'utf8',\n stdio: 'pipe',\n }).trim();\n\n const prs = JSON.parse(existingPR || '[]');\n if (prs.length > 0) {\n this.logger.info(`Pull request already exists for branch ${currentBranch}: #${prs[0].number}`);\n return;\n }\n\n // Create PR with a descriptive title and body\n // Extract task info from branch name if it follows pattern like \"agent-work-taskid-xxx\"\n let prTitle = `Agent work: ${currentBranch}`;\n if (currentBranch.includes('agent-work')) {\n prTitle = `🤖 ${currentBranch.replace(/-/g, ' ').replace('agent work', 'Agent Work:')}`;\n }\n\n const prBody = `## 🤖 Automated Changes by AI Agent\n\nThis pull request contains automated changes made by the Agiflow AI Agent.\n\n### Branch Information\n- **Source Branch:** \\`${currentBranch}\\`\n- **Target Branch:** \\`${mainBranch}\\`\n- **Created:** ${new Date().toISOString()}\n\n### Review Checklist\n- [ ] Code follows project conventions\n- [ ] Tests pass (if applicable)\n- [ ] No security vulnerabilities introduced\n- [ ] Documentation updated (if needed)\n\n### Notes\nPlease review the changes carefully before merging. The AI agent has attempted to follow best practices, but human review is essential.\n\n---\n*Generated by [Agiflow Agent](https://agiflow.io)*`;\n\n const prCommand = `gh pr create --base \"${mainBranch}\" --head \"${currentBranch}\" --title \"${prTitle}\" --body \"${prBody}\"`;\n\n const prUrl = execSync(prCommand, {\n cwd: worktreePath,\n encoding: 'utf8',\n stdio: 'pipe',\n }).trim();\n\n this.logger.success(`Pull request created: ${prUrl}`);\n } catch (error: any) {\n // Check if it's an authentication issue\n if (error.message?.includes('authentication') || error.message?.includes('gh auth login')) {\n this.logger.warn('GitHub CLI not authenticated. Run \"gh auth login\" to enable PR creation.');\n } else {\n this.logger.debug(`Could not create PR: ${error.message}`);\n }\n }\n }\n}\n","// Single agent instance manager\nimport { AGENT_TYPES, type DaemonStartAgentRequestEvent } from '@agimonai/universal-agent-events';\nimport { BaseAgent } from '../agents/base';\nimport { ClaudeAgent } from '../agents/claude';\nimport { ClaudeDockerAgent } from '../agents/claudeDocker';\nimport { GeminiAgent } from '../agents/gemini';\nimport { config } from '../config';\nimport type { AgentMessageData } from '../llms/messages';\nimport { AgentHttpService } from '../services/AgentHttpService';\nimport { CredentialsService } from '../services/CredentialsService';\nimport { type GitWorktreeInfo, GitWorktreeService } from '../services/GitWorktreeService';\nimport { RepoSetupService } from '../services/RepoSetupService';\nimport { TerminationService } from '../services/TerminationService';\nimport { Logger } from '../utils';\nimport { FileSystemUtils } from '../utils/fileSystem';\n\nexport class AgentWorker {\n private logger: Logger;\n private credentialsService: CredentialsService;\n private terminationService: TerminationService;\n private gitWorktreeService?: GitWorktreeService;\n private currentWorktree?: GitWorktreeInfo;\n private agentHttpService: AgentHttpService;\n instance!: BaseAgent | ClaudeDockerAgent;\n isTerminating: boolean = false;\n private onFullscreenChange?: (agentSessionId: string, isFullscreen: boolean) => void;\n\n constructor(\n logger?: Logger,\n terminationService?: TerminationService,\n onFullscreenChange?: (agentSessionId: string, isFullscreen: boolean) => void,\n ) {\n this.logger = logger ?? new Logger({ verbose: false });\n this.credentialsService = new CredentialsService();\n this.terminationService = terminationService ?? new TerminationService(this.logger);\n this.onFullscreenChange = onFullscreenChange;\n\n // Initialize AgentHttpService\n const apiUrl = config.VITE_INJECT_AGIFLOW_APP_ENDPOINT;\n if (!apiUrl) {\n throw new Error('VITE_INJECT_AGIFLOW_APP_ENDPOINT is required but not configured');\n }\n this.agentHttpService = new AgentHttpService({\n apiUrl,\n logger: this.logger,\n credentials: this.credentialsService,\n });\n\n // Listen for termination events\n this.setupTerminationHandlers();\n }\n\n handleInput(data: string) {\n this.instance.sendInputToAgent(data);\n }\n\n get isFullscreen(): boolean {\n return this.instance?.isFullscreen ?? false;\n }\n\n private setupTerminationHandlers(): void {\n if (this.isTerminating) return;\n // Listen for daemon shutdown to cleanly terminate agents\n this.terminationService.on('daemon:terminating', async () => {\n this.logger.info(`Daemon shutting down, terminating agent ${this.instance.getAgentInfo()?.agentSessionId}`);\n try {\n // Disconnect the agent - the PTY onExit will handle cleanup\n this.instance.disconnect();\n } catch (error) {\n this.logger.error(`Error terminating agent during daemon shutdown: ${error}`);\n }\n });\n\n // Listen for PTY natural termination to clear currentAgent reference\n this.terminationService.on('pty:terminated', (context) => {\n if (this.instance.getAgentInfo()?.agentSessionId === context.agentSessionId) {\n this.logger.info(`PTY terminated for agent ${context.agentSessionId}, clearing reference`);\n this.isTerminating = true;\n }\n });\n\n // Listen for agent cleanup event to clear currentAgent reference\n this.terminationService.on('agent:cleanup', (context) => {\n if (this.instance.getAgentInfo()?.agentSessionId === context.agentSessionId) {\n this.logger.info(`Agent cleanup for ${context.agentSessionId}, clearing reference`);\n this.isTerminating = true;\n }\n });\n\n // Listen for agent SIGINT event\n this.terminationService.on('agent:sigint', (context) => {\n if (this.instance.getAgentInfo()?.agentSessionId === context.agentSessionId) {\n this.logger.info(`Agent ${context.agentSessionId} received SIGINT, will be terminated via daemon`);\n // The daemon will call stopAgent, which will clear currentAgent\n }\n });\n }\n\n async terminateAgent(): Promise<boolean> {\n if (this.isTerminating) {\n this.logger.debug('Agent is already terminating, skipping duplicate termination');\n return true;\n }\n\n this.logger.info('Starting agent termination process');\n\n // Clear fullscreen mode when terminating\n this.instance.setFullscreen(false);\n this.logger.debug('Agent removed from fullscreen mode');\n\n try {\n this.instance.disconnect();\n this.logger.debug('Agent disconnected successfully');\n } catch (error) {\n this.logger.warn('Error disconnecting agent:', error as Error);\n }\n\n // Clean up worktrees if any were created\n this.logger.info('Checking for worktree cleanup...');\n await this.cleanupWorktrees();\n\n this.logger.info('Agent termination completed');\n return true;\n }\n\n async launchAgent(req: DaemonStartAgentRequestEvent): Promise<BaseAgent | ClaudeDockerAgent> {\n const { payload } = req;\n const { sessionId, agentType, agentSessionId } = payload;\n const creds = await this.credentialsService.getAgentCreds();\n\n this.logger.info(`Launching agent - Type: ${agentType}, Session: ${sessionId}, AgentSession: ${agentSessionId}`);\n\n // Initialize git worktree service based on working directory (only if not already initialized)\n if (!this.gitWorktreeService && payload.agentConfig?.worktree) {\n await this.initializeGitWorktreeService(req);\n }\n\n // Check if worktree is requested and create it\n const worktreeConfig = payload.agentConfig?.worktree;\n let workingDirectory = payload.agentConfig?.workingDirectory\n ? FileSystemUtils.getAbsolutePath(payload.agentConfig.workingDirectory)\n : undefined;\n\n if (worktreeConfig && this.gitWorktreeService) {\n let branch: string | undefined;\n let worktreeName: string | undefined;\n\n if (typeof worktreeConfig === 'boolean' && worktreeConfig) {\n // Use default branch and name\n } else if (typeof worktreeConfig === 'object') {\n branch = worktreeConfig.branch;\n worktreeName = worktreeConfig.name;\n }\n\n // Create the worktree\n const worktree = await this.gitWorktreeService.createWorktree({\n repositoryPath: this.gitWorktreeService.getRepositoryPath(),\n branch,\n worktreeName,\n logger: this.logger,\n });\n\n this.currentWorktree = worktree;\n workingDirectory = worktree.path;\n this.logger.success(`Created worktree for agent: ${worktree.path} (${worktree.branch})`);\n\n // Update task devInfo and send message about the worktree creation\n try {\n if (agentSessionId) {\n // Update task devInfo with worktree information\n const worktreeInfo = {\n name: worktree.name,\n branch: worktree.branch,\n path: worktree.path,\n createdAt: new Date().toISOString(),\n };\n\n // Update devInfo with worktree array (will be merged with existing worktrees in backend)\n const devInfo = {\n worktrees: [worktreeInfo],\n currentSession: agentSessionId,\n };\n await this.agentHttpService.updateTaskDevInfo(agentSessionId, devInfo);\n this.logger.debug('Updated task devInfo with worktree information');\n\n // Also add a comment for visibility\n const comment = `🌳 Git worktree created for agent session\\n- Location: \\`${worktree.path}\\`\\n- Branch: \\`${worktree.branch}\\`\\n- Name: ${worktree.name}`;\n await this.agentHttpService.createTaskComment(agentSessionId, comment);\n this.logger.debug('Added task comment about worktree creation');\n\n // Send a message to inform the user about worktree creation\n const messageData: AgentMessageData = {\n sessionId: agentSessionId,\n messageType: 'output',\n content: `Creating git worktree for isolated development:\\n• Branch: ${worktree.branch}\\n• Location: ${worktree.path}\\n• This provides a clean workspace for the agent to work without affecting your main branch.`,\n metadata: {\n eventType: 'worktree_created',\n worktreePath: worktree.path,\n worktreeBranch: worktree.branch,\n worktreeName: worktree.name,\n },\n };\n await this.agentHttpService.sendMessage(messageData);\n this.logger.debug('Sent message about worktree creation');\n }\n } catch (error) {\n this.logger.debug(`Failed to update task devInfo, add comment, or send message: ${error}`);\n // Don't fail the agent launch if devInfo update/comment/message fails\n }\n\n // Setup the worktree with environment files and dependencies\n await this.setupWorktree(worktree.path, this.gitWorktreeService.getRepositoryPath(), agentSessionId);\n }\n\n const isGemini = agentType === AGENT_TYPES.GEMINI_CLI;\n const isClaude = agentType === AGENT_TYPES.CLAUDE_CODE;\n if (!isGemini && !isClaude) {\n this.logger.error(`Unsupported agent type: ${agentType}`);\n throw new Error(`Unsupported agent type: ${agentType}`);\n }\n\n const commonOpts = {\n agentType,\n serverUrl: config.VITE_INJECT_AGIFLOW_APP_ENDPOINT,\n apiUrl: config.VITE_INJECT_AGIFLOW_APP_ENDPOINT, // Add HTTP API URL\n ...creds,\n logger: this.logger,\n credentialsService: this.credentialsService,\n terminationService: this.terminationService,\n onFullscreenChange: this.onFullscreenChange,\n standalone: false,\n } as const;\n\n // Check if Docker execution is requested for Claude agents\n const useDocker = payload.agentConfig?.docker === true;\n const isAutonomous = payload.agentConfig?.autonomous === true;\n\n let instance: BaseAgent | ClaudeDockerAgent | undefined;\n if (isGemini) {\n instance = new GeminiAgent(commonOpts);\n } else if (isClaude) {\n if (useDocker || isAutonomous) {\n this.logger.info('Docker execution requested for Claude agent');\n instance = new ClaudeDockerAgent({\n ...commonOpts,\n onBeforeTerminate: async () => {\n // Perform cleanup before Docker agent terminates\n this.logger.info('Docker agent cleanup callback triggered');\n\n // Clean up worktrees if any were created\n this.logger.info('Checking for worktree cleanup...');\n await this.cleanupWorktrees();\n\n this.logger.info('Docker agent cleanup callback completed');\n },\n });\n } else {\n instance = new ClaudeAgent(commonOpts);\n }\n }\n\n const agentTypeStr = isGemini ? 'Gemini' : useDocker ? 'Claude Docker' : 'Claude';\n this.logger.debug(`Created ${agentTypeStr} agent instance`);\n\n if (!instance) {\n throw new Error(`Sorry, the agent ${agentTypeStr} is not supported!`);\n }\n\n // Update working directory in the request if worktree was created\n if (workingDirectory && workingDirectory !== payload.agentConfig?.workingDirectory) {\n if (req.payload.agentConfig) {\n req.payload.agentConfig.workingDirectory = workingDirectory;\n }\n }\n\n // Pass the request to the agent\n await instance.launchAgent(req);\n this.instance = instance;\n\n // Set fullscreen mode by default for launched agents\n // This makes the agent \"active\" for stdin forwarding\n this.instance.setFullscreen(true);\n this.logger.debug(`Agent set to fullscreen mode for stdin handling`);\n\n this.logger.success(`Agent launched successfully - AgentSession: ${agentSessionId}`);\n return instance;\n }\n\n /**\n * Initialize git worktree service based on the working directory from the request\n */\n private async initializeGitWorktreeService(req: DaemonStartAgentRequestEvent): Promise<void> {\n try {\n const workingDirectory = req.payload.agentConfig?.workingDirectory\n ? FileSystemUtils.getAbsolutePath(req.payload.agentConfig.workingDirectory)\n : process.cwd();\n this.gitWorktreeService = new GitWorktreeService(workingDirectory, this.logger);\n this.logger.debug(`Git worktree service initialized for: ${workingDirectory}`);\n } catch (error) {\n this.logger.debug(`Git worktree service not available - not in a git repository: ${error}`);\n }\n }\n\n /**\n * Create a new git worktree for the agent to work in\n */\n /**\n * Create a new git worktree for the agent to work in\n */\n async createWorktree(branch?: string, worktreeName?: string): Promise<GitWorktreeInfo | null> {\n if (!this.gitWorktreeService) {\n this.logger.warn('Git worktree service not available');\n return null;\n }\n\n try {\n const worktree = await this.gitWorktreeService.createWorktree({\n repositoryPath: this.gitWorktreeService.getRepositoryPath(),\n branch,\n worktreeName,\n logger: this.logger,\n });\n\n this.currentWorktree = worktree;\n\n // Update the agent's working directory to the worktree path\n if (this.instance && this.instance.getAgentInfo()) {\n const agentInfo = this.instance.getAgentInfo()!;\n agentInfo.workingDir = worktree.path;\n this.logger.info(`Agent working directory updated to worktree: ${worktree.path}`);\n\n // Update task devInfo and send message about the worktree creation\n try {\n const agentSessionId = agentInfo.agentSessionId;\n if (agentSessionId) {\n // Update task devInfo with worktree information\n const worktreeInfo = {\n name: worktree.name,\n branch: worktree.branch,\n path: worktree.path,\n createdAt: new Date().toISOString(),\n };\n\n // Update devInfo with worktree array (will be merged with existing worktrees in backend)\n const devInfo = {\n worktrees: [worktreeInfo],\n currentSession: agentSessionId,\n };\n await this.agentHttpService.updateTaskDevInfo(agentSessionId, devInfo);\n this.logger.debug('Updated task devInfo with worktree information');\n\n // Also add a comment for visibility\n const comment = `🌳 Git worktree created\\n- Location: \\`${worktree.path}\\`\\n- Branch: \\`${worktree.branch}\\`\\n- Name: ${worktree.name}`;\n await this.agentHttpService.createTaskComment(agentSessionId, comment);\n this.logger.debug('Added task comment about worktree creation');\n\n // Send a message to inform the user about worktree creation\n const messageData: AgentMessageData = {\n sessionId: agentSessionId,\n messageType: 'output',\n content: `Git worktree created:\\n• Branch: ${worktree.branch}\\n• Location: ${worktree.path}\\n• The agent is now working in an isolated workspace.`,\n metadata: {\n eventType: 'worktree_created',\n worktreePath: worktree.path,\n worktreeBranch: worktree.branch,\n worktreeName: worktree.name,\n },\n };\n await this.agentHttpService.sendMessage(messageData);\n this.logger.debug('Sent message about worktree creation');\n }\n } catch (error) {\n this.logger.debug(`Failed to update task devInfo, add comment, or send message: ${error}`);\n // Don't fail the worktree creation if devInfo update/comment/message fails\n }\n }\n\n this.logger.success(`Created worktree: ${worktree.path} (${worktree.branch})`);\n\n // Setup the worktree with environment files and dependencies\n const sessionId = this.instance?.getAgentInfo()?.agentSessionId;\n await this.setupWorktree(worktree.path, this.gitWorktreeService.getRepositoryPath(), sessionId);\n\n return worktree;\n } catch (error) {\n this.logger.error(`Failed to create worktree: ${error}`);\n return null;\n }\n }\n\n /**\n * Setup a worktree with environment files and dependencies\n */\n private async setupWorktree(worktreePath: string, originalPath: string, agentSessionId?: string): Promise<void> {\n try {\n this.logger.info('Setting up worktree with environment files and dependencies...');\n\n // Send initial setup message if we have a session ID\n if (agentSessionId) {\n try {\n const setupStartMessage: AgentMessageData = {\n sessionId: agentSessionId,\n messageType: 'output',\n content: `🔧 Setting up development environment in the worktree...\\nCopying environment files...`,\n metadata: {\n eventType: 'worktree_setup_start',\n worktreePath,\n },\n };\n await this.agentHttpService.sendMessage(setupStartMessage);\n } catch (error) {\n this.logger.debug(`Failed to send setup start message: ${error}`);\n }\n }\n\n const repoSetupService = new RepoSetupService({\n targetDirectory: worktreePath,\n originalDirectory: originalPath,\n logger: this.logger,\n });\n\n const result = await repoSetupService.setup();\n\n // Build status message\n let statusMessage = '✅ Environment setup completed:\\n';\n let hasSuccess = false;\n\n // Log results\n if (result.envFilesCopied.length > 0) {\n const copiedCount = result.envFilesCopied.filter((f) => f.copied).length;\n this.logger.success(`Copied ${copiedCount} environment files to worktree`);\n statusMessage += `• Copied ${copiedCount} environment files\\n`;\n hasSuccess = true;\n }\n\n if (result.errors.length > 0) {\n this.logger.warn(`Worktree setup completed with ${result.errors.length} errors`);\n result.errors.forEach((error) => this.logger.debug(`Setup error: ${error}`));\n statusMessage += `• ⚠️ ${result.errors.length} setup warnings occurred\\n`;\n }\n\n // Send completion message if we have a session ID\n if (agentSessionId && hasSuccess) {\n try {\n const setupCompleteMessage: AgentMessageData = {\n sessionId: agentSessionId,\n messageType: 'output',\n content: statusMessage + 'The workspace is ready for development.',\n metadata: {\n eventType: 'worktree_setup_complete',\n worktreePath,\n envFilesCopied: result.envFilesCopied.filter((f) => f.copied).length,\n errorsCount: result.errors.length,\n },\n };\n await this.agentHttpService.sendMessage(setupCompleteMessage);\n } catch (error) {\n this.logger.debug(`Failed to send setup complete message: ${error}`);\n }\n }\n } catch (error) {\n this.logger.error(`Failed to setup worktree: ${error}`);\n\n // Send error message if we have a session ID\n if (agentSessionId) {\n try {\n const setupErrorMessage: AgentMessageData = {\n sessionId: agentSessionId,\n messageType: 'output',\n content: `⚠️ Worktree setup encountered issues: ${error}\\nThe workspace is created but may require manual setup.`,\n metadata: {\n eventType: 'worktree_setup_error',\n worktreePath,\n error: String(error),\n },\n };\n await this.agentHttpService.sendMessage(setupErrorMessage);\n } catch (msgError) {\n this.logger.debug(`Failed to send setup error message: ${msgError}`);\n }\n }\n // Don't throw - worktree creation succeeded, setup is optional\n }\n }\n\n /**\n * Switch to an existing worktree\n */\n switchToWorktree(worktreePath: string): GitWorktreeInfo | null {\n if (!this.gitWorktreeService) {\n this.logger.warn('Git worktree service not available');\n return null;\n }\n\n try {\n const worktree = this.gitWorktreeService.switchToWorktree(worktreePath);\n this.currentWorktree = worktree;\n\n // Update the agent's working directory to the worktree path\n if (this.instance && this.instance.getAgentInfo()) {\n const agentInfo = this.instance.getAgentInfo()!;\n agentInfo.workingDir = worktree.path;\n this.logger.info(`Agent working directory updated to worktree: ${worktree.path}`);\n }\n\n this.logger.success(`Switched to worktree: ${worktree.path} (${worktree.branch})`);\n return worktree;\n } catch (error) {\n this.logger.error(`Failed to switch to worktree: ${error}`);\n return null;\n }\n }\n\n /**\n * Get current worktree information\n */\n getCurrentWorktree(): GitWorktreeInfo | undefined {\n return this.currentWorktree;\n }\n\n /**\n * List all available worktrees\n */\n listWorktrees(): GitWorktreeInfo[] {\n if (!this.gitWorktreeService) {\n return [];\n }\n return this.gitWorktreeService.listWorktrees();\n }\n\n /**\n * Remove a specific worktree\n */\n async removeWorktree(worktreePath: string, force = false): Promise<boolean> {\n if (!this.gitWorktreeService) {\n this.logger.warn('Git worktree service not available');\n return false;\n }\n\n try {\n await this.gitWorktreeService.removeWorktree(worktreePath, force);\n\n // Clear current worktree if it was the one removed\n if (this.currentWorktree?.path === worktreePath) {\n this.currentWorktree = undefined;\n }\n\n return true;\n } catch (error) {\n this.logger.error(`Failed to remove worktree: ${error}`);\n return false;\n }\n }\n\n /**\n * Commit changes in the current worktree\n */\n async commitWorktreeChanges(message: string, addAll = true): Promise<boolean> {\n if (!this.gitWorktreeService || !this.currentWorktree) {\n this.logger.warn('No active worktree to commit changes');\n return false;\n }\n\n try {\n await this.gitWorktreeService.commitChanges(this.currentWorktree.path, message, addAll);\n return true;\n } catch (error) {\n this.logger.error(`Failed to commit worktree changes: ${error}`);\n return false;\n }\n }\n\n /**\n * Push changes from the current worktree\n */\n async pushWorktreeChanges(remote = 'origin', branch?: string): Promise<boolean> {\n if (!this.gitWorktreeService || !this.currentWorktree) {\n this.logger.warn('No active worktree to push changes');\n return false;\n }\n\n try {\n await this.gitWorktreeService.pushChanges(this.currentWorktree.path, remote, branch);\n return true;\n } catch (error) {\n this.logger.error(`Failed to push worktree changes: ${error}`);\n return false;\n }\n }\n\n /**\n * Commit and push changes in the current worktree\n */\n async commitAndPushWorktreeChanges(commitMessage: string, remote = 'origin', branch?: string): Promise<boolean> {\n if (!this.gitWorktreeService || !this.currentWorktree) {\n this.logger.warn('No active worktree to commit and push changes');\n return false;\n }\n\n try {\n await this.gitWorktreeService.commitAndPush(this.currentWorktree.path, commitMessage, remote, branch);\n return true;\n } catch (error) {\n this.logger.error(`Failed to commit and push worktree changes: ${error}`);\n return false;\n }\n }\n\n /**\n * Clean up all worktrees created by this agent\n */\n private async cleanupWorktrees(commitAndPush = true, commitMessage = 'Agent work completed'): Promise<void> {\n this.logger.info(\n `cleanupWorktrees called - gitWorktreeService exists: ${!!this.gitWorktreeService}, currentWorktree: ${!!this.currentWorktree}`,\n );\n\n if (!this.gitWorktreeService) {\n this.logger.info('No gitWorktreeService available, skipping worktree cleanup');\n return;\n }\n\n if (!this.currentWorktree) {\n this.logger.info('No active worktree to clean up');\n return;\n }\n\n try {\n this.logger.info(`Cleaning up worktree at: ${this.currentWorktree.path}`);\n await this.gitWorktreeService.cleanup(commitAndPush, commitMessage);\n this.currentWorktree = undefined;\n this.logger.success('Worktrees cleaned up successfully');\n } catch (error) {\n this.logger.warn(`Error cleaning up worktrees: ${error}`);\n }\n }\n\n /**\n * Check if git worktree functionality is available\n */\n isWorktreeSupported(): boolean {\n return this.gitWorktreeService?.isWorktreeSupported() ?? false;\n }\n\n /**\n * Get the git worktree service instance\n */\n getGitWorktreeService(): GitWorktreeService | undefined {\n return this.gitWorktreeService;\n }\n\n /**\n * Get the agent HTTP service instance\n */\n getAgentHttpService(): AgentHttpService {\n return this.agentHttpService;\n }\n}\n","import { DaemonStartAgentRequestEvent } from '@agimonai/universal-agent-events';\nimport { Logger } from '../utils';\nimport { KeyedSemaphore } from '../utils/semaphore';\nimport { AgentWorker } from '../workers/agent';\nimport { CredentialsService } from './CredentialsService';\n\ninterface AgentsManagerProps {\n logger: Logger;\n credentials?: CredentialsService;\n}\nexport class AgentsManager {\n private agents: Map<string, AgentWorker> = new Map(); // key: agentSessionId\n private agentLaunchSemaphore: KeyedSemaphore<string>;\n private logger: Logger;\n private credentials: CredentialsService;\n\n constructor(options: AgentsManagerProps) {\n this.logger = options.logger;\n this.agentLaunchSemaphore = new KeyedSemaphore<string>(1);\n this.credentials = options.credentials ?? new CredentialsService();\n }\n\n listAgentIds() {\n return Array.from(this.agents.keys());\n }\n\n getAgent(agentSessionId: string) {\n return this.agents.get(agentSessionId);\n }\n\n getActiveAgent() {\n const agentWorker = Array.from(this.agents.values()).find((agent) => agent.isFullscreen);\n return agentWorker;\n }\n\n /**\n * Handle fullscreen change - ensure only one agent is fullscreen at a time\n */\n private handleFullscreenChange = (changedAgentSessionId: string, isFullscreen: boolean) => {\n if (isFullscreen) {\n // When an agent becomes fullscreen, make all other agents not fullscreen (silently to prevent recursion)\n for (const [agentSessionId, agent] of this.agents.entries()) {\n if (agentSessionId !== changedAgentSessionId && agent.isFullscreen) {\n agent.instance.setFullscreen(false, true); // silent = true to prevent callback recursion\n this.logger.debug(`Agent ${agentSessionId} removed from fullscreen mode`);\n }\n }\n this.logger.debug(`Agent ${changedAgentSessionId} is now in fullscreen mode`);\n }\n };\n\n async stopAgent(agentSessionId: string) {\n const agent = this.getAgent(agentSessionId);\n if (agent) {\n agent?.terminateAgent();\n this.agents.delete(agentSessionId);\n return true;\n }\n return false;\n }\n\n async startAgent(startAgentRequest: DaemonStartAgentRequestEvent, onError: any) {\n const agentSessionId = startAgentRequest.payload.agentSessionId;\n if (this.agentLaunchSemaphore.isLocked(agentSessionId)) {\n this.logger.warn(`Agent launch already in progress for session: ${agentSessionId}`);\n onError(\n startAgentRequest.payload.sessionId,\n 'AGENT_ALREADY_LAUNCHING',\n `Agent with session ${agentSessionId} is already being launched`,\n );\n return;\n }\n\n // Use semaphore to ensure exclusive access for this agentSessionId\n await this.agentLaunchSemaphore.runExclusive(agentSessionId, async () => {\n // Check if agent already exists\n const existingAgent = this.getAgent(agentSessionId);\n if (existingAgent) {\n this.logger.info(`Agent already exists for session: ${agentSessionId}`);\n return;\n }\n\n this.logger.info('Launching agent:', startAgentRequest.payload.agentType);\n\n const apiKey = await this.credentials.getApiKey();\n const orgId = await this.credentials.getOrganizationId();\n if (!apiKey || !orgId) throw new Error('Missing credentials to launch agent');\n\n const agentWorker = new AgentWorker(this.logger, undefined, this.handleFullscreenChange);\n // Launch agent via worker\n await agentWorker.launchAgent(startAgentRequest);\n this.agents.set(startAgentRequest.payload.agentSessionId, agentWorker);\n\n // Wait for PTY to initialize before enabling stdin forwarding\n this.logger.debug('Waiting for agent PTY to initialize...');\n await new Promise((resolve) => setTimeout(resolve, 1000)); // Give PTY time to boot up\n this.logger.debug('Agent PTY should now be ready for stdin forwarding');\n\n this.logger.success(`Agent launched successfully: ${startAgentRequest.payload.agentSessionId}`);\n });\n }\n}\n","import { AGENT_TYPES } from '@agimonai/universal-agent-events';\nimport { execSync } from 'child_process';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport { Logger } from '../utils/logger';\n\nexport interface AgentInfo {\n name: string;\n executable: string;\n isInstalled: boolean;\n version?: string;\n path?: string;\n hostAuthed?: boolean;\n dockerAuthed?: boolean;\n}\n\nexport interface DetectionResult {\n availableAgents: AgentInfo[];\n installedCount: number;\n}\n\nexport class AgentDetectionService {\n private logger: Logger;\n\n constructor(logger?: Logger) {\n this.logger = logger ?? new Logger({ verbose: false });\n }\n\n /**\n * Detect all available agent CLI tools\n */\n async detectAgents(): Promise<DetectionResult> {\n const agents = [\n { name: AGENT_TYPES.CLAUDE_CODE, executable: 'claude' },\n { name: AGENT_TYPES.GEMINI_CLI, executable: 'gemini' },\n ];\n\n const availableAgents: AgentInfo[] = [];\n\n for (const agent of agents) {\n const agentInfo = await this.detectAgent(agent.name, agent.executable);\n availableAgents.push(agentInfo);\n }\n\n const installedCount = availableAgents.filter((agent) => agent.isInstalled).length;\n\n this.logger.info(`🔍 Agent detection complete: ${installedCount}/${availableAgents.length} agents installed`);\n\n return {\n availableAgents,\n installedCount,\n };\n }\n\n /**\n * Detect a specific agent CLI tool\n */\n async detectAgent(name: string, executable: string): Promise<AgentInfo> {\n let agentInfo: AgentInfo = {\n name,\n executable,\n isInstalled: false,\n };\n\n try {\n // Try to get the version to confirm installation\n const versionOutput = this.executeCommand(`${executable} --version`);\n\n if (versionOutput) {\n // Try to get the path\n const pathOutput = this.executeCommand(`which ${executable}`);\n\n this.logger.info(`✅ Found ${name}: ${versionOutput.trim()}`);\n\n agentInfo = {\n name,\n executable,\n isInstalled: true,\n version: versionOutput.trim(),\n path: pathOutput?.trim(),\n };\n }\n } catch (error) {\n // Try alternative detection methods\n try {\n // Check if command exists without version flag\n this.executeCommand(`${executable} --help`);\n\n this.logger.info(`✅ Found ${name} (version unknown)`);\n\n agentInfo = {\n name,\n executable,\n isInstalled: true,\n version: 'unknown',\n };\n } catch {\n // Agent not found\n this.logger.info(`❌ ${name} not found`);\n }\n }\n\n // Check authentication status for installed agents\n if (agentInfo.isInstalled) {\n agentInfo.hostAuthed = this.checkHostAuth(name);\n agentInfo.dockerAuthed = this.checkDockerAuth(name);\n\n this.logger.info(`🔐 ${name} auth status: host=${agentInfo.hostAuthed}, docker=${agentInfo.dockerAuthed}`);\n }\n\n return agentInfo;\n }\n\n /**\n * Check if a specific agent is installed\n */\n async isAgentInstalled(name: string, executable: string): Promise<boolean> {\n const agentInfo = await this.detectAgent(name, executable);\n return agentInfo.isInstalled;\n }\n\n /**\n * Get installed agents only\n */\n async getInstalledAgents(): Promise<AgentInfo[]> {\n const result = await this.detectAgents();\n return result.availableAgents.filter((agent) => agent.isInstalled);\n }\n\n /**\n * Get agent types for API registration\n */\n async getAgentTypesForRegistration(): Promise<\n Array<{\n agentType: string;\n hostEnabled: boolean;\n dockerEnabled: boolean;\n hostAuthed: boolean;\n dockerAuthed: boolean;\n }>\n > {\n const installedAgents = await this.getInstalledAgents();\n\n return installedAgents.map((agent) => ({\n agentType: agent.name,\n hostEnabled: agent.hostAuthed ?? false,\n dockerEnabled: agent.dockerAuthed ?? false,\n hostAuthed: agent.hostAuthed ?? false,\n dockerAuthed: agent.dockerAuthed ?? false,\n }));\n }\n\n /**\n * Execute a command safely and return output\n */\n private executeCommand(command: string): string | null {\n try {\n const output = execSync(command, {\n encoding: 'utf8',\n stdio: 'pipe',\n timeout: 5000, // 5 second timeout\n });\n return output;\n } catch (error) {\n // Command failed or not found\n return null;\n }\n }\n\n /**\n * Check if agent is authenticated for host execution\n * Based on ~/.claude existence (platform-specific paths)\n */\n private checkHostAuth(agentName: string): boolean {\n if (agentName !== AGENT_TYPES.CLAUDE_CODE) {\n // Only Claude Code authentication is currently supported\n return false;\n }\n\n const homeDir = os.homedir();\n const isMacOS = os.platform() === 'darwin';\n\n try {\n if (isMacOS) {\n // macOS: Check for .claude_tmp.json or .claude_tmp directory\n const claudeTmpJsonPath = path.join(homeDir, '.claude_tmp.json');\n const claudeTmpDirPath = path.join(homeDir, '.claude_tmp');\n\n return fs.existsSync(claudeTmpJsonPath) || fs.existsSync(claudeTmpDirPath);\n } else {\n // Linux: Check for .claude.json or .claude directory\n const claudeJsonPath = path.join(homeDir, '.claude.json');\n const claudeDirPath = path.join(homeDir, '.claude');\n\n return fs.existsSync(claudeJsonPath) || fs.existsSync(claudeDirPath);\n }\n } catch (error) {\n this.logger.debug(`Error checking host auth for ${agentName}:`, error as Error);\n return false;\n }\n }\n\n /**\n * Check if agent is authenticated for Docker execution\n * Based on Docker availability and credential existence\n */\n private checkDockerAuth(agentName: string): boolean {\n if (agentName !== AGENT_TYPES.CLAUDE_CODE) {\n // Only Claude Code Docker authentication is currently supported\n return false;\n }\n\n // Check if Docker is available\n if (!this.isDockerAvailableSync()) {\n return false;\n }\n\n const homeDir = os.homedir();\n const isMacOS = os.platform() === 'darwin';\n\n try {\n if (isMacOS) {\n // macOS: Check if Claude tmp credentials exist\n const claudeTmpJsonPath = path.join(homeDir, '.claude_tmp.json');\n const claudeTmpDirPath = path.join(homeDir, '.claude_tmp');\n\n return fs.existsSync(claudeTmpJsonPath) || fs.existsSync(claudeTmpDirPath);\n } else {\n // Linux: Check if Claude credentials exist\n const claudeJsonPath = path.join(homeDir, '.claude.json');\n const claudeDirPath = path.join(homeDir, '.claude');\n\n return fs.existsSync(claudeJsonPath) || fs.existsSync(claudeDirPath);\n }\n } catch (error) {\n this.logger.debug(`Error checking Docker auth for ${agentName}:`, error as Error);\n return false;\n }\n }\n\n /**\n * Check if Docker is available synchronously\n */\n private isDockerAvailableSync(): boolean {\n try {\n const output = this.executeCommand('docker --version');\n return !!output;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Check if Docker is available for agent execution\n */\n async isDockerAvailable(): Promise<boolean> {\n try {\n const output = this.executeCommand('docker --version');\n if (output) {\n this.logger.info(`🐳 Docker available: ${output.trim()}`);\n return true;\n }\n } catch (error) {\n this.logger.info('🐳 Docker not available');\n }\n return false;\n }\n\n /**\n * Get comprehensive system capabilities\n */\n async getSystemCapabilities(): Promise<{\n hostExecution: boolean;\n dockerExecution: boolean;\n installedAgents: AgentInfo[];\n agentTypesForRegistration: Array<{ agentType: string; hostEnabled: boolean; dockerEnabled: boolean }>;\n }> {\n const [installedAgents, dockerAvailable] = await Promise.all([this.getInstalledAgents(), this.isDockerAvailable()]);\n\n const agentTypesForRegistration = installedAgents.map((agent) => ({\n agentType: agent.name,\n hostEnabled: true,\n dockerEnabled: dockerAvailable,\n }));\n\n return {\n hostExecution: installedAgents.length > 0,\n dockerExecution: dockerAvailable,\n installedAgents,\n agentTypesForRegistration,\n };\n }\n}\n","import type { DaemonStatus } from '@agimonai/universal-agent-events';\nimport { DAEMON_STATUS } from '@agimonai/universal-agent-events';\nimport { Logger } from '../utils/logger';\nimport { getSystemInfo } from '../utils/platform';\nimport { AgentDetectionService } from './AgentDetectionService';\nimport { CredentialsService } from './CredentialsService';\nimport { DeviceCodeAuthService } from './DeviceCodeAuthService';\n\n// Use global fetch if available, otherwise we'll need to handle this at runtime\ndeclare const fetch: typeof globalThis.fetch;\n\nexport interface DaemonHttpOptions {\n apiUrl: string;\n deviceGuid: string;\n organizationId?: string;\n authToken?: string;\n authService?: DeviceCodeAuthService;\n logger?: Logger;\n credentials?: CredentialsService;\n agentDetection?: AgentDetectionService;\n}\n\nexport interface DaemonRegistration {\n id: string;\n deviceGuid: string;\n organizationId: string;\n status: DaemonStatus;\n hostname?: string;\n platform?: string;\n path?: string;\n currentSessionId?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface DaemonRegistrationResponse {\n id: string;\n deviceGuid: string;\n organizationId: string;\n status: DaemonStatus;\n hostname?: string;\n platform?: string;\n path?: string;\n currentSessionId?: string;\n createdAt: string;\n updatedAt: string;\n device?: {\n id: string;\n };\n}\n\nexport class DaemonHttpService {\n private options: DaemonHttpOptions;\n private authService?: DeviceCodeAuthService;\n private databaseDeviceId: string | null = null;\n private credentials: CredentialsService;\n private logger: Logger;\n private agentDetection: AgentDetectionService;\n\n constructor(options: DaemonHttpOptions) {\n this.options = options;\n this.authService = options.authService;\n this.credentials = options.credentials ?? new CredentialsService();\n this.logger = options.logger ?? new Logger({ verbose: false });\n this.agentDetection = options.agentDetection ?? new AgentDetectionService(this.logger);\n }\n\n /**\n * Set the database device ID for tracking\n */\n setDatabaseDeviceId(deviceId: string): void {\n this.databaseDeviceId = deviceId;\n }\n\n /**\n * Get the database device ID\n */\n getDatabaseDeviceId(): string | null {\n return this.databaseDeviceId;\n }\n\n /**\n * Get authentication headers for API requests\n */\n private async getAuthHeaders(): Promise<Record<string, string>> {\n // Prefer stored credentials first\n let storedKey = await this.credentials.getApiKey();\n let orgId = await this.credentials.getOrganizationId();\n if ((!storedKey || !orgId) && this.authService) {\n const apiKeyToken = await this.authService.getValidApiKey();\n storedKey = apiKeyToken.api_key;\n orgId = apiKeyToken.organization_id;\n await this.credentials.setApiKey({ apiKey: storedKey, organizationId: orgId, expiresAt: apiKeyToken.expires_at });\n }\n if (storedKey && orgId) {\n this.options.organizationId = orgId;\n return { 'Content-Type': 'application/json', 'x-api-key': storedKey };\n }\n // Fallback to bearer token path\n const authToken = this.options.authToken;\n if (!authToken) throw new Error('Authentication token is required for daemon registration');\n if (!this.options.organizationId) throw new Error('Organization ID is required for daemon registration');\n return { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}` };\n }\n\n /**\n * Make HTTP request with automatic token refresh on 401 errors\n */\n private async makeAuthenticatedRequest(url: string, options: RequestInit, retryOnAuth = true): Promise<Response> {\n const response = await fetch(url, options);\n\n // Handle 401 Invalid API key error with retry\n if (response.status === 401 && retryOnAuth && this.authService) {\n const errorText = await response.text();\n if (errorText.includes('Invalid API key')) {\n this.logger.info('🔑 API key expired or invalid, clearing tokens and retrying authentication...');\n\n // Clear the invalid tokens\n await this.authService.clearTokens();\n try {\n await this.credentials.clear();\n } catch {\n /* ignore */\n }\n\n // Retry authentication with fresh tokens\n this.logger.info('🔄 Retrying authentication...');\n\n // Get new headers and retry the request\n const newHeaders = await this.getAuthHeaders();\n const retryOptions = {\n ...options,\n headers: { ...options.headers, ...newHeaders },\n };\n\n return await fetch(url, retryOptions);\n }\n }\n\n // Handle rate limit (429) without clearing credentials\n if (response.status === 429) {\n this.logger.warn('🚫 Rate limit exceeded, keeping credentials but not retrying');\n // Don't clear credentials for rate limits - just return the response\n return response;\n }\n\n return response;\n }\n\n /**\n * Register daemon with HTTP API\n */\n async registerDaemon(): Promise<DaemonRegistration> {\n const { deviceGuid } = this.options;\n\n // Try to load existing database device ID first\n if (this.authService && !this.databaseDeviceId) {\n const storedDeviceId = await this.authService.getDeviceId();\n if (storedDeviceId) {\n this.databaseDeviceId = storedDeviceId;\n this.logger.info(`📋 Loaded existing device ID from storage: ${this.databaseDeviceId}`);\n }\n }\n\n if (this.authService) {\n this.logger.info('🔐 Authenticating via OAuth flow...');\n }\n\n const headers = await this.getAuthHeaders();\n const organizationId = this.options.organizationId!;\n\n const systemInfo = getSystemInfo();\n const workingDirectory = process.cwd();\n\n // Detect available agent types\n this.logger.info('🔍 Detecting available agent types...');\n const agentTypes = await this.agentDetection.getAgentTypesForRegistration();\n\n if (agentTypes.length > 0) {\n this.logger.info(`✅ Found ${agentTypes.length} agent type(s): ${agentTypes.map((a) => a.agentType).join(', ')}`);\n } else {\n this.logger.warn('⚠️ No agent types detected - daemon will register without agent capabilities');\n }\n\n const registrationData = {\n deviceGuid: deviceGuid!,\n hostname: systemInfo.hostname,\n platform: systemInfo.platform,\n workingDirectory,\n agentTypes: agentTypes.length > 0 ? agentTypes : undefined,\n };\n\n this.logger.info('📝 Registering daemon with API...');\n\n try {\n const response = await this.makeAuthenticatedRequest(\n `${this.options.apiUrl}/api/v1/organizations/${organizationId}/daemons`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(registrationData),\n },\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Registration failed: ${response.status} ${errorText}`);\n }\n\n const registrationResponse: DaemonRegistrationResponse = await response.json();\n\n // Store the database device ID for WebSocket connection\n if (registrationResponse.device?.id) {\n this.databaseDeviceId = registrationResponse.device.id;\n } else if (registrationResponse.deviceGuid) {\n // Fallback to deviceGuid field if device object is not included\n this.databaseDeviceId = registrationResponse.deviceGuid;\n }\n\n // Persist the device ID with the API key\n if (this.databaseDeviceId) {\n if (this.authService) await this.authService.updateDeviceId(this.databaseDeviceId);\n try {\n await this.credentials.setDeviceId(this.databaseDeviceId);\n } catch {\n /* ignore */\n }\n }\n\n this.logger.success(`Daemon registered successfully: ${registrationResponse.id}`);\n this.logger.info(` Device ID (database): ${this.databaseDeviceId}`);\n\n return registrationResponse;\n } catch (error) {\n throw new Error(`Failed to register daemon: ${error instanceof Error ? error.message : error}`);\n }\n }\n\n /**\n * Send heartbeat to update daemon's last activity timestamp\n */\n async sendHeartbeat(daemonRegistration: DaemonRegistration): Promise<void> {\n if (!daemonRegistration) {\n this.logger.warn('⚠️ No daemon registration available for heartbeat');\n return;\n }\n\n try {\n const headers = await this.getAuthHeaders();\n const organizationId = this.options.organizationId;\n\n if (!organizationId) {\n this.logger.warn('⚠️ Organization ID not available for heartbeat');\n return;\n }\n\n const heartbeatData = {\n lastHeartbeat: new Date().toISOString(),\n status: DAEMON_STATUS.IDLE, // Keep daemon as idle/available\n };\n\n const response = await this.makeAuthenticatedRequest(\n `${this.options.apiUrl}/api/v1/organizations/${organizationId}/daemons/${daemonRegistration.id}`,\n {\n method: 'PATCH',\n headers,\n body: JSON.stringify(heartbeatData),\n },\n true, // Allow retry on auth errors for heartbeat to handle token refresh\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'Unknown error');\n this.logger.warn(`⚠️ Failed to send heartbeat: ${response.status} ${errorText}`);\n }\n } catch (error) {\n // Don't throw here as heartbeat is non-critical\n this.logger.warn('⚠️ Failed to send heartbeat:', error as Error);\n }\n }\n\n /**\n * Unregister daemon from HTTP API\n */\n async unregisterDaemon(daemonRegistration: DaemonRegistration): Promise<void> {\n if (!daemonRegistration) {\n return;\n }\n\n try {\n const headers = await this.getAuthHeaders();\n const organizationId = this.options.organizationId;\n\n if (!organizationId) {\n this.logger.warn('⚠️ Organization ID not available for unregistration');\n return;\n }\n\n this.logger.info('📝 Unregistering daemon from API...');\n\n const response = await this.makeAuthenticatedRequest(\n `${this.options.apiUrl}/api/v1/organizations/${organizationId}/daemons/${daemonRegistration.id}`,\n {\n method: 'DELETE',\n headers,\n },\n false, // Don't retry on auth errors for cleanup operations\n );\n\n if (response.ok) {\n this.logger.success('Daemon unregistered successfully');\n } else {\n const errorText = await response.text().catch(() => 'Unknown error');\n this.logger.warn(`⚠️ Failed to unregister daemon: ${response.status} ${errorText}`);\n }\n } catch (error) {\n // Don't throw here as this is cleanup\n this.logger.warn('⚠️ Failed to unregister daemon:', error as Error);\n }\n }\n}\n","import {\n AGENT_STATUS,\n COMMANDS,\n DAEMON_EVENT_TYPES,\n DAEMON_STATUS,\n DaemonErrorResponseEventSchema,\n DaemonListAgentSessionsRequestEventSchema,\n DaemonListAgentSessionsResponseEventSchema,\n DaemonStartAgentRequestEventSchema,\n DaemonStatusRequestEventSchema,\n DaemonStatusResponseEventSchema,\n DaemonStopAgentRequestEventSchema,\n DaemonStopAgentResponseEventSchema,\n DaemonTerminateRequestEventSchema,\n DaemonTerminateResponseEventSchema,\n} from '@agimonai/universal-agent-events';\nimport WebSocket from 'ws';\nimport { ServerMessage, SessionInfo } from '../types/websocket';\nimport { Logger } from '../utils';\nimport { AgentsManager } from './AgentsManager';\nimport { CredentialsService } from './CredentialsService';\nimport { type DaemonRegistration } from './DaemonHttpService';\nimport { DeviceCodeAuthService } from './DeviceCodeAuthService';\n\n// Minimal interface for session management\ninterface ISessionManager {\n registerWorker(params: {\n sessionId: string;\n agentSessionId: string;\n agentType?: string;\n daemonId?: string;\n pid?: number;\n }): any;\n getAllSessions(): SessionInfo[];\n terminateSession(sessionId: string): Promise<boolean>;\n stopAgent?(agentSessionId: string): Promise<boolean>;\n}\n\nexport interface DaemonWsOptions {\n serverUrl: string;\n deviceGuid: string;\n organizationId: string;\n authToken?: string;\n verbose?: boolean;\n reconnectInterval?: number;\n authService?: DeviceCodeAuthService;\n databaseDeviceId?: string;\n sessionManager: ISessionManager;\n logger?: Logger;\n credentials?: CredentialsService;\n agentsManager: AgentsManager;\n onTerminate?: (isWebSocketInitiated?: boolean) => Promise<void>;\n}\n\nexport interface DaemonWsCallbacks {\n onMessage?: (message: any) => Promise<void>;\n onConnect?: () => void;\n onDisconnect?: (code: number, reason: string) => void;\n onError?: (error: Error) => void;\n}\n\nexport class DaemonWsService {\n private ws: WebSocket | null = null;\n private options: DaemonWsOptions;\n private callbacks: DaemonWsCallbacks;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private isConnected = false;\n private shouldReconnect = true;\n private sessionManager: ISessionManager;\n private credentials: CredentialsService;\n private logger: Logger;\n private agentsManager: AgentsManager;\n\n constructor(options: DaemonWsOptions, callbacks: DaemonWsCallbacks = {}) {\n this.options = { reconnectInterval: 5000, ...options };\n this.callbacks = callbacks;\n this.sessionManager = options.sessionManager;\n this.logger = options.logger ?? new Logger({ verbose: options.verbose || false });\n this.credentials = options.credentials ?? new CredentialsService();\n this.agentsManager = options.agentsManager;\n }\n\n /**\n * Connect to WebSocket server\n */\n async connect(daemonRegistration: DaemonRegistration): Promise<void> {\n return this.connectToDaemonChannel(daemonRegistration);\n }\n\n /**\n * Disconnect from WebSocket server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n\n this.isConnected = false;\n }\n\n /**\n * Check if WebSocket is connected\n */\n isWebSocketConnected(): boolean {\n return this.isConnected;\n }\n\n /**\n * Send message through WebSocket\n */\n sendMessage(message: any): void {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(message));\n } else {\n this.logger.warn('Cannot send message - WebSocket not connected');\n }\n }\n\n /**\n * Send error message through WebSocket\n */\n sendError(sessionId: string, code: string, message: string, details?: any): void {\n const errorMessage = DaemonErrorResponseEventSchema.parse({\n payload: {\n sessionId,\n data: message,\n error: {\n code,\n message,\n details: details instanceof Error ? details.message : details,\n },\n },\n });\n\n this.sendMessage(errorMessage);\n }\n\n /**\n * Connect daemon to its dedicated subscription WebSocket channel.\n * The backend proxies /daemons/:daemonId/ws -> durable object instance.\n */\n private async connectToDaemonChannel(daemonRegistration: DaemonRegistration): Promise<void> {\n return new Promise(async (resolve, reject) => {\n const { authToken, deviceGuid } = this.options;\n\n if (!daemonRegistration) {\n reject(new Error('Daemon must be registered before connecting to daemon channel'));\n return;\n }\n\n // Load / refresh credentials\n let storedApiKey = await this.credentials.getApiKey();\n let storedOrgId = await this.credentials.getOrganizationId();\n if ((!storedApiKey || !storedOrgId) && this.options.authService) {\n try {\n const api = await this.options.authService.getValidApiKey();\n storedApiKey = api.api_key;\n storedOrgId = api.organization_id;\n await this.credentials.setApiKey({\n apiKey: storedApiKey,\n organizationId: storedOrgId,\n deviceId: api.device_id,\n });\n } catch (e) {\n this.logger.warn('Unable to refresh credentials:', (e as Error).message);\n }\n }\n if (!storedOrgId) storedOrgId = this.options.organizationId;\n if (!storedApiKey && authToken) storedApiKey = authToken;\n const organizationId = storedOrgId || this.options.organizationId;\n if (!organizationId) {\n reject(new Error('Organization ID missing for daemon WebSocket connection'));\n return;\n }\n\n // Construct WebSocket URL for daemon subscription endpoint\n const wsUrl = new URL(this.options.serverUrl!);\n // Convert HTTP protocol to WebSocket protocol\n if (wsUrl.protocol === 'http:') {\n wsUrl.protocol = 'ws:';\n } else if (wsUrl.protocol === 'https:') {\n wsUrl.protocol = 'wss:';\n }\n // Use daemon registration ID in the URL path\n const daemonId = daemonRegistration.id;\n wsUrl.pathname = `/api/v1/organizations/${organizationId}/daemons/${daemonId}/ws`;\n wsUrl.searchParams.set('clientType', 'daemon');\n\n // Build device-authenticated headers\n const headers = await this.credentials.buildDeviceAuthHeaders(deviceGuid);\n\n if (!headers['x-api-key']) {\n reject(new Error('No API key available for WebSocket connection'));\n return;\n }\n\n this.logger.info(`Connecting to daemon WebSocket: ${wsUrl.toString()}`);\n\n this.ws = new WebSocket(wsUrl.toString(), { headers });\n\n this.ws.on('open', () => {\n this.isConnected = true;\n this.logger.info('Daemon WebSocket connection established');\n\n // Send daemon status response event using proper schema\n const statusEvent = DaemonStatusResponseEventSchema.parse({\n payload: {\n sessionId: deviceGuid!,\n data: 'Daemon ready',\n status: DAEMON_STATUS.IDLE,\n },\n });\n this.sendMessage(statusEvent);\n\n // Call onConnect callback\n if (this.callbacks.onConnect) {\n this.callbacks.onConnect();\n }\n\n resolve();\n });\n\n this.ws.on('message', (data) => {\n try {\n const rawMessage = data.toString();\n const message: ServerMessage = JSON.parse(rawMessage);\n this.handleServerMessage(message);\n } catch (error) {\n this.logger.error('Failed to parse server message:', error as Error);\n this.logger.error(`Raw data: ${data.toString()}`);\n }\n });\n\n this.ws.on('close', (code, reason) => {\n this.isConnected = false;\n this.logger.info(`Daemon WebSocket disconnected (${code}): ${reason}`);\n\n // Call onDisconnect callback\n if (this.callbacks.onDisconnect) {\n this.callbacks.onDisconnect(code, reason.toString());\n }\n\n if (this.shouldReconnect) {\n this.scheduleReconnect(daemonRegistration);\n }\n });\n\n this.ws.on('error', (error) => {\n this.logger.error('WebSocket error:', error as Error);\n\n // Call onError callback\n if (this.callbacks.onError) {\n this.callbacks.onError(error);\n }\n\n if (!this.isConnected) {\n reject(error);\n }\n });\n\n // Connection timeout\n setTimeout(() => {\n if (!this.isConnected) reject(new Error('WebSocket connection timeout'));\n }, 10000);\n });\n }\n\n /**\n * Schedule reconnection attempt\n */\n private scheduleReconnect(daemonRegistration: DaemonRegistration): void {\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n }\n\n this.reconnectTimer = setTimeout(async () => {\n if (!this.shouldReconnect) return;\n\n try {\n this.logger.info('Attempting to reconnect...');\n await this.connect(daemonRegistration);\n } catch (error) {\n this.logger.warn('Reconnection failed, will retry...');\n this.scheduleReconnect(daemonRegistration);\n }\n }, this.options.reconnectInterval);\n }\n\n /**\n * Handle messages from the remote server\n */\n private async handleServerMessage(message: any): Promise<void> {\n try {\n // Handle new standardized agent message format\n if (message.eventType) {\n // TODO: Validate the message using proper agent schema when available\n // const validatedMessage = AgentEventSchema.parse(message);\n\n // Check for daemon events with separate eventType and command fields\n if (message.eventType === DAEMON_EVENT_TYPES.STATUS && message.command === COMMANDS.REQUEST) {\n await this.handleStatusRequest(message);\n } else if (message.eventType === DAEMON_EVENT_TYPES.START_AGENT && message.command === COMMANDS.REQUEST) {\n await this.handleLaunchAgent(message);\n } else if (message.eventType === DAEMON_EVENT_TYPES.STOP_AGENT && message.command === COMMANDS.REQUEST) {\n await this.handleStopAgent(message);\n } else if (message.eventType === DAEMON_EVENT_TYPES.TERMINATE && message.command === COMMANDS.REQUEST) {\n await this.handleTerminateDaemon(message);\n } else if (message.eventType === DAEMON_EVENT_TYPES.LIST && message.command === COMMANDS.REQUEST) {\n await this.handleListAgentSessions(message);\n } else if (message.eventType?.startsWith('agent-')) {\n // Log agent messages for debugging but don't process them\n // These should be handled by the agent session WebSocket, not the daemon WebSocket\n this.logger.debug(\n `Received agent message on daemon WebSocket (ignoring): ${message.eventType}-${message.command || 'unknown'}`,\n );\n } else {\n this.logger.warn(`Unknown daemon message: ${message.eventType}-${message.command || 'unknown'}`);\n }\n return;\n }\n\n // Call custom message callback if provided\n if (this.callbacks.onMessage) {\n await this.callbacks.onMessage(message);\n }\n } catch (error) {\n this.logger.error('Failed to process server message:', error as Error);\n this.sendError(message.payload?.sessionId || '', 'COMMAND_ERROR', 'Failed to process server command', error);\n }\n }\n\n /**\n * Handle status request from server\n */\n private async handleStatusRequest(message: any): Promise<void> {\n try {\n // Parse and validate the message using the daemon schema\n const statusRequest = DaemonStatusRequestEventSchema.parse(message);\n\n // Send status response\n const statusResponse = DaemonStatusResponseEventSchema.parse({\n eventType: DAEMON_EVENT_TYPES.STATUS,\n command: COMMANDS.RESPONSE,\n payload: {\n sessionId: statusRequest.payload.sessionId,\n timestamp: Date.now(),\n data: 'Daemon is running',\n status: DAEMON_STATUS.IDLE,\n },\n });\n\n this.sendMessage(statusResponse);\n } catch (error) {\n this.logger.error('Failed to handle daemon status request:', error as Error);\n this.sendError(\n message.payload?.sessionId || '',\n 'STATUS_REQUEST_FAILED',\n 'Failed to handle status request',\n error,\n );\n }\n }\n\n /**\n * Handle launch-agent command\n */\n private async handleLaunchAgent(message: any): Promise<void> {\n try {\n const startAgentRequest = DaemonStartAgentRequestEventSchema.parse(message);\n const agentSessionId = startAgentRequest.payload.agentSessionId;\n\n const agent = this.agentsManager.getAgent(agentSessionId);\n if (agent) return;\n\n this.agentsManager.startAgent(startAgentRequest, (err: any) => {\n this.logger.warn(`Agent launch already in progress for session: ${agentSessionId}`);\n (this.sendError as any)(err as any);\n });\n } catch (error) {\n this.logger.error('Failed to launch agent:', error as Error);\n this.sendError(message.payload?.sessionId || '', 'LAUNCH_AGENT_FAILED', 'Failed to launch agent', error);\n }\n }\n\n /**\n * Handle stop agent request from server\n */\n private async handleStopAgent(message: any): Promise<void> {\n try {\n // Parse and validate the message using the daemon schema\n const stopAgentRequest = DaemonStopAgentRequestEventSchema.parse(message);\n const agentSessionId = stopAgentRequest.payload.agentSessionId;\n const stopped = await this.agentsManager.stopAgent(agentSessionId);\n\n // Send stop agent response\n const stopAgentResponse = DaemonStopAgentResponseEventSchema.parse({\n eventType: DAEMON_EVENT_TYPES.STOP_AGENT,\n command: COMMANDS.RESPONSE,\n payload: {\n sessionId: stopAgentRequest.payload.sessionId,\n timestamp: Date.now(),\n data: stopped ? 'Agent stopped successfully' : 'Agent not found',\n agentSessionId,\n status: stopped ? 'stopped' : 'not_found',\n message: stopped ? `Agent ${agentSessionId} has been stopped` : `Agent ${agentSessionId} was not found`,\n },\n });\n\n this.sendMessage(stopAgentResponse);\n\n if (stopped) {\n this.logger.success(`Agent stopped successfully: ${agentSessionId}`);\n } else {\n this.logger.warn(`Agent not found: ${agentSessionId}`);\n }\n } catch (error) {\n this.logger.error('Failed to stop agent:', error as Error);\n this.sendError(message.payload?.sessionId || '', 'STOP_AGENT_FAILED', 'Failed to stop agent', error);\n }\n }\n\n /**\n * Handle daemon terminate request\n */\n private async handleTerminateDaemon(message: any): Promise<void> {\n try {\n // Parse and validate the message using the daemon schema\n const terminateRequest = DaemonTerminateRequestEventSchema.parse(message);\n this.logger.info('Received daemon terminate request');\n\n // Send terminate response first (if WebSocket is still connected)\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n const terminateResponse = DaemonTerminateResponseEventSchema.parse({\n payload: {\n sessionId: terminateRequest.payload.sessionId,\n data: 'Daemon terminating gracefully',\n },\n });\n this.sendMessage(terminateResponse);\n this.logger.info('Daemon terminate response sent');\n } else {\n this.logger.warn('WebSocket not connected, cannot send terminate response');\n }\n\n // Call the onTerminate callback if provided for graceful shutdown\n if (this.options.onTerminate) {\n this.logger.info('Initiating graceful daemon shutdown...');\n // Give time for the response to be sent, then trigger graceful shutdown\n setTimeout(async () => {\n try {\n await this.options.onTerminate!(true); // Pass true to indicate WebSocket-initiated shutdown\n\n // After graceful shutdown completes, disconnect the WebSocket\n this.logger.info('Graceful shutdown complete, disconnecting WebSocket...');\n this.disconnect();\n } catch (error) {\n this.logger.error('Error during graceful shutdown:', error as Error);\n // Force exit if graceful shutdown fails\n process.exit(1);\n }\n }, 500);\n } else {\n // Fallback to the old behavior if no onTerminate callback is provided\n this.logger.warn('No onTerminate callback provided, using fallback shutdown');\n\n // Terminate all active sessions\n const sessions = this.sessionManager.getAllSessions();\n for (const session of sessions) {\n if (session.status === AGENT_STATUS.IDLE) {\n await this.sessionManager.terminateSession(session.id);\n }\n }\n\n // Disconnect the WebSocket and stop the daemon\n setTimeout(() => {\n this.disconnect();\n this.logger.info('Daemon shutting down...');\n process.exit(0);\n }, 1000);\n }\n } catch (error) {\n this.logger.error('Failed to handle daemon terminate request:', error as Error);\n this.sendError(message.payload?.sessionId || '', 'TERMINATE_DAEMON_FAILED', 'Failed to terminate daemon', error);\n }\n }\n\n /**\n * Handle list agent sessions request from server\n */\n private async handleListAgentSessions(message: any): Promise<void> {\n try {\n // Parse and validate the message using the daemon schema\n const listRequest = DaemonListAgentSessionsRequestEventSchema.parse(message);\n\n // Get all sessions from the session manager\n const sessions = this.sessionManager.getAllSessions();\n\n // Send list response using proper schema\n const listResponse = DaemonListAgentSessionsResponseEventSchema.parse({\n payload: {\n sessionId: listRequest.payload.sessionId,\n data: 'Agent sessions list',\n sessions,\n },\n });\n this.sendMessage(listResponse);\n } catch (error) {\n this.logger.error('Failed to handle list agent sessions request:', error as Error);\n this.sendError(message.payload?.sessionId || '', 'LIST_SESSIONS_FAILED', 'Failed to list agent sessions', error);\n }\n }\n\n /**\n * Get session manager instance\n */\n getSessionManager(): ISessionManager {\n return this.sessionManager;\n }\n}\n","import * as os from 'node:os';\nimport * as path from 'node:path';\nimport { AgentsManager } from '../services/AgentsManager';\nimport { DaemonHttpService, type DaemonRegistration } from '../services/DaemonHttpService';\nimport { DaemonWsService } from '../services/DaemonWsService';\nimport { type AuthOptions, DeviceCodeAuthService } from '../services/DeviceCodeAuthService';\nimport { StdinForwarding } from '../services/StdinForwarding';\nimport { TerminationService } from '../services/TerminationService';\nimport { createHeartbeat, generateDeviceId, Logger, webSocketToHttp } from '../utils';\n\nexport interface DaemonOptions {\n serverUrl: string;\n authToken?: string;\n verbose?: boolean;\n reconnectInterval?: number;\n deviceGuid?: string;\n apiUrl?: string;\n organizationId?: string;\n stableDeviceId?: boolean;\n options: AuthOptions;\n logFile?: string;\n logDir?: string;\n}\n\nexport class DaemonWorker {\n private terminationService: TerminationService;\n private options: DaemonOptions;\n private daemonRegistration: DaemonRegistration | null = null;\n private authService: DeviceCodeAuthService;\n private httpService: DaemonHttpService;\n private wsService: DaemonWsService;\n private isShuttingDown = false;\n private heartbeat: ReturnType<typeof createHeartbeat>;\n private logger: Logger;\n private agentsManager: AgentsManager;\n private stdinForwarding!: StdinForwarding;\n\n constructor(options: DaemonOptions) {\n this.options = {\n reconnectInterval: 5000,\n stableDeviceId: true,\n ...options,\n apiUrl: options.apiUrl || webSocketToHttp(options.serverUrl),\n };\n this.options.deviceGuid = options.deviceGuid || generateDeviceId(this.options.stableDeviceId !== false);\n\n // Configure logger with file transport if specified\n this.logger = new Logger({\n verbose: this.options.verbose || false,\n logFile: this.options.logFile,\n logDir: this.options.logDir || path.join(os.tmpdir(), 'agiflow-agents', 'daemon', `session-${process.pid}`),\n maxFiles: 7, // Keep 7 days of logs\n maxFileSize: '10m', // Rotate at 10MB\n });\n\n // Log startup info\n const logPath = this.logger.getLogFilePath();\n if (logPath) {\n this.logger.info(`Logging to file: ${logPath}`);\n }\n\n this.agentsManager = new AgentsManager({ logger: this.logger });\n\n // Initialize stdin forwarding service\n this.logger.debug('Setting up StdinForwarding service...');\n this.stdinForwarding = new StdinForwarding({\n logger: this.logger,\n onData: this.onData.bind(this),\n onExit: this.onExit.bind(this),\n });\n this.logger.debug('StdinForwarding service initialized');\n\n // Initialize termination service\n this.terminationService = new TerminationService(this.logger);\n this.terminationService.registerCallbacks({\n onPtyTerminated: async (context) => {\n await this.agentsManager.stopAgent(context.agentSessionId);\n },\n onAgentTerminated: async (context) => {\n // Clean up agent resources\n this.logger.info(`Agent ${context.agentSessionId} terminated, cleaning up`);\n await this.agentsManager.stopAgent(context.agentSessionId);\n },\n onDaemonTerminating: async () => {\n // Prepare for daemon shutdown\n this.logger.info('Daemon is terminating, preparing cleanup');\n },\n onAgentSigint: async (context) => {\n // Handle agent SIGINT (Ctrl+C) - stop only the agent, not the daemon\n this.logger.info(`Agent ${context.agentSessionId} received SIGINT, stopping agent via daemon`);\n await this.agentsManager.stopAgent(context.agentSessionId);\n },\n });\n\n this.authService = new DeviceCodeAuthService({\n ...options.options,\n logger: this.logger,\n });\n this.httpService = new DaemonHttpService({\n apiUrl: this.options.apiUrl!,\n deviceGuid: this.options.deviceGuid!,\n organizationId: this.options.organizationId,\n authToken: this.options.authToken,\n authService: this.authService,\n logger: this.logger,\n });\n this.wsService = new DaemonWsService({\n serverUrl: this.options.serverUrl,\n deviceGuid: this.options.deviceGuid!,\n organizationId: this.options.organizationId!,\n authToken: this.options.authToken,\n verbose: this.options.verbose,\n reconnectInterval: this.options.reconnectInterval,\n authService: this.authService,\n databaseDeviceId: this.httpService.getDatabaseDeviceId() || undefined,\n sessionManager: this as any, // DaemonWorker now implements session management\n logger: this.logger,\n agentsManager: this.agentsManager,\n onTerminate: (isWebSocketInitiated) => this.stop(isWebSocketInitiated), // Pass the stop method for graceful shutdown\n });\n\n // Initialize heartbeat\n this.heartbeat = createHeartbeat(\n async () => {\n if (this.daemonRegistration && !this.isShuttingDown) {\n this.logger.debug('Heartbeat...');\n await this.httpService.sendHeartbeat(this.daemonRegistration);\n }\n },\n 300000, // 5 minutes\n this.logger,\n );\n }\n\n async onExit(data: string) {\n this.logger.debug(`Daemon received exit signal: ${JSON.stringify(data)}`);\n const agentWorker = this.agentsManager.getActiveAgent();\n if (agentWorker) {\n this.logger.info(`Stopping agent due to exit signal: ${agentWorker.instance.getAgentInfo()?.agentSessionId}`);\n await this.agentsManager.stopAgent(agentWorker.instance.getAgentInfo()?.agentSessionId || '');\n } else {\n this.logger.info('No active agent, stopping daemon gracefully');\n await this.stop();\n }\n }\n\n onData(data: string) {\n try {\n this.logger.debug('=== DAEMON ONDATA CALLED ===');\n this.logger.debug(`Daemon received stdin data: ${JSON.stringify(data)} (length: ${data.length})`);\n\n const agentWorker = this.agentsManager.getActiveAgent();\n if (agentWorker) {\n const agentInfo = agentWorker.instance.getAgentInfo();\n this.logger.debug(`Found active agent: ${agentInfo?.agentSessionId}`);\n this.logger.debug(`About to call agentWorker.handleInput...`);\n\n agentWorker.handleInput(data);\n\n this.logger.debug(`agentWorker.handleInput completed successfully`);\n } else {\n this.logger.warn('No active agent to handle stdin data');\n\n // When there's no active agent, we still need to handle Ctrl+C for graceful exit\n // But we let the StdinForwarding service manage the double-press logic\n // For the first Ctrl+C, we just acknowledge it (so user knows it's registered)\n // The StdinForwarding service will handle the second Ctrl+C and call onExit\n if (data === '\\u0003') {\n this.logger.info('Ctrl+C received (no active agent). Press Ctrl+C again to exit daemon.');\n }\n // For all other input when there's no active agent, we just ignore it\n }\n } catch (error) {\n this.logger.error('Error in daemon onData:', error as any);\n // Don't propagate the error, just log it\n }\n }\n\n async start(): Promise<void> {\n const { serverUrl } = this.options;\n this.logger.info('Starting Daemon...');\n this.logger.debug('API URL:', this.options.apiUrl);\n this.logger.debug('WebSocket URL:', serverUrl);\n\n try {\n this.daemonRegistration = await this.httpService.registerDaemon();\n let apiKeyToUse: string | undefined;\n if (this.authService) {\n const apiKey = await this.authService.getValidApiKey();\n apiKeyToUse = apiKey.api_key;\n this.options.organizationId = apiKey.organization_id;\n } else apiKeyToUse = this.options.authToken;\n if (!apiKeyToUse) throw new Error('No API key available for SessionManager');\n await this.wsService.connect(this.daemonRegistration);\n this.heartbeat.start();\n\n this.logger.success('Daemon connected');\n this.logger.info('Daemon ID:', this.daemonRegistration?.id);\n } catch (e) {\n this.logger.error('Failed to start daemon:', e as Error);\n throw e;\n }\n }\n\n async stop(isWebSocketInitiated = false): Promise<void> {\n if (this.isShuttingDown) {\n this.logger.debug('Already shutting down, skipping duplicate stop call');\n return;\n }\n this.isShuttingDown = true;\n\n // Set a hard timeout to force exit if cleanup hangs\n const forceExitTimeout = setTimeout(() => {\n this.logger.error('Force exit after cleanup timeout (10s)');\n process.exit(1);\n }, 10000); // Increased to 10 seconds for proper cleanup\n\n try {\n this.logger.info('Beginning graceful daemon shutdown...');\n\n // Stop heartbeat first to prevent new operations\n this.logger.info('Stopping heartbeat...');\n this.heartbeat.stop();\n\n // Stop all active agents gracefully\n const agentSessionIds = this.agentsManager.listAgentIds();\n if (agentSessionIds.length > 0) {\n this.logger.info(`Terminating ${agentSessionIds.length} active agent(s)...`);\n await this.terminationService.shutdownDaemon(agentSessionIds);\n\n // Wait for agents to properly terminate\n await this.terminationService.waitForActiveTerminations();\n this.logger.info('All agents terminated successfully');\n } else {\n this.logger.info('No active agents to terminate');\n }\n\n // Unregister daemon from the backend BEFORE disconnecting WebSocket\n // This ensures we can still communicate with the backend\n try {\n if (this.daemonRegistration && this.httpService) {\n this.logger.info('Unregistering daemon from backend...');\n await this.httpService.unregisterDaemon(this.daemonRegistration);\n this.logger.info('Daemon unregistered successfully');\n }\n } catch (e) {\n // Don't fail shutdown if unregistration fails\n this.logger.warn('Failed to unregister daemon (non-fatal):', e as Error);\n }\n\n // If shutdown was NOT initiated by WebSocket, disconnect it now\n // If it WAS initiated by WebSocket, let the WebSocket handler manage its own lifecycle\n if (!isWebSocketInitiated) {\n this.logger.info('Disconnecting WebSocket...');\n this.wsService.disconnect();\n } else {\n this.logger.info('WebSocket-initiated shutdown, WebSocket will handle its own disconnect');\n }\n\n // Clean up termination service\n this.logger.info('Cleaning up termination service...');\n this.terminationService.cleanup();\n\n // Restore stdio handler to terminal\n this.logger.info('Restoring stdio handler to terminal...');\n this.stdinForwarding.restore();\n\n this.logger.success('✅ Daemon stopped gracefully');\n\n // Clear the force exit timeout since we completed successfully\n clearTimeout(forceExitTimeout);\n\n // Exit the process cleanly\n process.exit(0);\n } catch (error) {\n this.logger.error('❌ Error during daemon shutdown:', error as Error);\n\n // Clear the force exit timeout before exiting with error\n clearTimeout(forceExitTimeout);\n\n // Exit with error code\n process.exit(1);\n }\n }\n\n getStats() {\n return {\n daemonId: this.daemonRegistration?.id,\n deviceGuid: this.daemonRegistration?.deviceGuid,\n };\n }\n\n /**\n * Get all active sessions - required for sessionManager interface\n */\n getAllSessions() {\n const agentIds = this.agentsManager.listAgentIds();\n return agentIds.map((id) => ({\n id,\n status: 'IDLE' as const, // Active agents are considered IDLE (not STOPPED)\n }));\n }\n\n /**\n * Terminate a specific session - required for sessionManager interface\n */\n async terminateSession(sessionId: string): Promise<void> {\n this.logger.info(`Terminating session: ${sessionId}`);\n await this.agentsManager.stopAgent(sessionId);\n }\n}\n","import { Command } from 'commander';\nimport { config } from '../config';\nimport { DeviceCodeAuthService } from '../services/DeviceCodeAuthService';\n// Updated to use worker implementation\nimport { DaemonWorker } from '../workers/daemon';\nimport { BaseCommand } from './baseCommand';\n\ninterface ConnectOptions {\n serverUrl?: string;\n apiUrl?: string;\n verbose?: boolean;\n reconnectInterval?: string;\n uniqueInstance?: boolean;\n}\n\nexport class ConnectCommand extends BaseCommand {\n register(program: Command): void {\n program\n .command('connect')\n .description('Connect Agiflow daemon to receive commands from remote server')\n .option('-u, --server-url <url>', 'WebSocket server URL to connect to')\n .option('--api-url <url>', 'HTTP API base URL for daemon registration')\n .option('-v, --verbose', 'Enable verbose logging')\n .option('--reconnect-interval <ms>', 'Reconnection interval in milliseconds', '5000')\n .option('--unique-instance', 'Create unique daemon instance (default: reuse by working directory)')\n .action(async (options) => {\n try {\n await this.execute(options);\n } catch (error) {\n this.handleError(error);\n }\n });\n }\n\n private async execute(options: ConnectOptions): Promise<void> {\n // Use options or environment defaults\n const serverUrl = options.serverUrl || config.VITE_INJECT_AGIFLOW_APP_ENDPOINT;\n const apiUrl = options.apiUrl || config.VITE_INJECT_AGIFLOW_APP_ENDPOINT;\n\n // Check if URLs are provided\n if (!serverUrl) {\n this.error(\n 'Server URL is required. Provide via --server-url or VITE_INJECT_AGIFLOW_APP_ENDPOINT environment variable.',\n );\n process.exit(1);\n }\n\n if (!apiUrl) {\n this.error(\n 'API URL is required. Provide via --api-url or VITE_INJECT_AGIFLOW_APP_ENDPOINT environment variable.',\n );\n process.exit(1);\n }\n\n // Validate WebSocket URL\n try {\n new URL(serverUrl);\n } catch (error) {\n this.error('Invalid server URL. Must be a valid WebSocket URL (ws:// or wss://).');\n process.exit(1);\n }\n\n // Validate API URL\n try {\n new URL(apiUrl);\n } catch (error) {\n this.error('Invalid API URL. Must be a valid HTTP URL.');\n process.exit(1);\n }\n\n const reconnectInterval = options.reconnectInterval ? parseInt(options.reconnectInterval, 10) : 5000;\n\n if (isNaN(reconnectInterval) || reconnectInterval < 1000) {\n this.error('Invalid reconnect interval. Must be at least 1000ms.');\n process.exit(1);\n }\n\n // Use device code authentication service\n const deviceCodeAuth = new DeviceCodeAuthService({\n clientId: 'agiflow-cli-daemon',\n baseUrl: apiUrl,\n verbose: options.verbose,\n });\n\n // Get API key through device code flow\n let apiKey;\n try {\n if (options.verbose) {\n console.log('🔐 Authenticating...');\n }\n apiKey = await deviceCodeAuth.getValidApiKey();\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes('cancelled by user')) {\n this.info('\\nAuthentication cancelled');\n process.exit(0);\n } else {\n this.error(`Authentication failed: ${errorMessage}`);\n process.exit(1);\n }\n }\n\n const daemon = new DaemonWorker({\n serverUrl,\n apiUrl,\n authToken: apiKey.api_key,\n organizationId: apiKey.organization_id,\n verbose: options.verbose,\n reconnectInterval,\n stableDeviceId: !options.uniqueInstance, // Invert the flag\n options: {\n clientId: 'agiflow-cli-daemon',\n baseUrl: apiUrl,\n verbose: options.verbose,\n },\n });\n\n // Set up signal handlers for graceful shutdown\n const handleShutdown = async (signal: string) => {\n console.log(`\\n📡 Received ${signal}, initiating graceful shutdown...`);\n try {\n await daemon.stop();\n } catch (error) {\n this.error(`Error during shutdown: ${error}`);\n process.exit(1);\n }\n };\n\n // Register signal handlers\n process.on('SIGINT', () => handleShutdown('SIGINT'));\n process.on('SIGTERM', () => handleShutdown('SIGTERM'));\n process.on('SIGHUP', () => handleShutdown('SIGHUP'));\n\n try {\n await daemon.start();\n\n const stats = daemon.getStats();\n this.success('Agiflow Daemon connected successfully');\n this.info(`🆔 Daemon ID: ${stats.daemonId}`);\n this.info(`💻 Device GUID: ${stats.deviceGuid}`);\n this.info('Press Ctrl+C to disconnect\\n');\n\n // The daemon keeps itself running via WebSocket connections and timers\n // DO NOT call process.stdin.resume() as it blocks SIGINT\n } catch (error) {\n this.error(`Failed to connect daemon: ${error}`);\n process.exit(1);\n }\n }\n}\n","import { Command } from 'commander';\nimport { FileSystemUtils } from '../utils';\nimport { BaseCommand } from './baseCommand';\n\ninterface LogoutOptions {\n verbose?: boolean;\n removeAll?: boolean;\n}\n\nexport class LogoutCommand extends BaseCommand {\n register(program: Command): void {\n program\n .command('logout')\n .description('Log out and clean up stored credentials')\n .option('-v, --verbose', 'Enable verbose logging')\n .option('--remove-all', 'Remove entire .agiflow directory (default: remove only credential files)')\n .action(async (options) => {\n try {\n await this.execute(options);\n } catch (error) {\n this.handleError(error);\n }\n });\n }\n\n private async execute(options: LogoutOptions): Promise<void> {\n if (options.verbose) {\n console.log('🔐 Logging out and cleaning up credentials...');\n }\n\n try {\n // Check if .agiflow directory exists\n const agiflowDirExists = await FileSystemUtils.exists(FileSystemUtils.AGIFLOW_DIR);\n\n if (!agiflowDirExists) {\n this.info('No stored credentials found. You are already logged out.');\n return;\n }\n\n if (options.removeAll) {\n // Remove entire .agiflow directory\n await FileSystemUtils.remove(FileSystemUtils.AGIFLOW_DIR);\n if (options.verbose) {\n this.info(`Removed entire directory: ${FileSystemUtils.AGIFLOW_DIR}`);\n }\n this.success('Successfully logged out and removed all Agiflow configuration');\n } else {\n // Remove specific credential files\n const credentialFiles = ['api-key.json', 'credentials.json'];\n\n let removedFiles = 0;\n\n for (const file of credentialFiles) {\n const filePath = require('path').join(FileSystemUtils.AGIFLOW_DIR, file);\n const exists = await FileSystemUtils.exists(filePath);\n\n if (exists) {\n await FileSystemUtils.remove(filePath);\n removedFiles++;\n if (options.verbose) {\n this.info(`Removed: ${file}`);\n }\n }\n }\n\n if (removedFiles === 0) {\n this.info('No credential files found. You are already logged out.');\n } else {\n this.success(`Successfully logged out and removed ${removedFiles} credential file(s)`);\n }\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.error(`Failed to clean up credentials: ${errorMessage}`);\n process.exit(1);\n }\n }\n}\n","/**\n * Router Command Implementation\n *\n * DESIGN PATTERNS:\n * - Command Pattern: Encapsulate command logic\n * - Interactive CLI: Use prompts for user input\n * - Async/Await: Handle I/O operations properly\n *\n * CODING STANDARDS:\n * - Extend BaseCommand\n * - Use logger for output\n * - Use prompts for user input\n * - Handle errors gracefully\n *\n * AVOID:\n * - Blocking synchronous operations\n * - Unvalidated user input\n */\n\nimport { select } from '@inquirer/prompts';\nimport { Command } from 'commander';\nimport { type SessionModelSettings, SessionSettingsManager } from '../utils/sessionSettings.js';\nimport { BaseCommand } from './baseCommand.js';\n\ninterface RouterOption {\n name: string;\n value: SessionModelSettings | null;\n description?: string;\n}\n\nexport class RouterCommand extends BaseCommand {\n register(program: Command): void {\n program\n .command('router')\n .description('Manage LLM routing configuration for active sessions')\n .option('-v, --verbose', 'Enable verbose logging')\n .option('--clear', 'Clear all session routing configurations')\n .action(async (options) => {\n try {\n await this.execute(options);\n } catch (error) {\n this.handleError(error);\n }\n });\n }\n\n private async execute(options: { verbose?: boolean; clear?: boolean }): Promise<void> {\n try {\n // Handle --clear flag\n if (options.clear) {\n await SessionSettingsManager.clearAllSessions();\n this.success('All session routing configurations have been cleared.');\n return;\n }\n\n // Get all sessions\n const sessions = await SessionSettingsManager.getAllSessions();\n const sessionIds = Object.keys(sessions);\n\n if (sessionIds.length === 0) {\n this.warn('No active sessions found.');\n this.info('Start a Claude agent first using: agiflow claude');\n return;\n }\n\n // Prompt user to select a session\n const sessionChoices = sessionIds.map((sessionId) => {\n const settings = sessions[sessionId];\n const displayName = settings?.alias || sessionId;\n const currentRouting =\n settings?.provider && settings?.model\n ? `${settings.provider}/${settings.model}${settings.reasoningEffort ? ` (${settings.reasoningEffort})` : ''}`\n : 'default';\n return {\n name: `${displayName} [${currentRouting}]`,\n value: sessionId,\n description: `Current routing: ${currentRouting}`,\n };\n });\n\n const selectedSessionId = await select({\n message: 'Select a session to configure routing:',\n choices: sessionChoices,\n });\n\n if (options.verbose) {\n this.info(`Selected session: ${selectedSessionId}`);\n }\n\n // Define routing options\n const routingOptions: RouterOption[] = [\n {\n name: 'Default (Claude)',\n value: null,\n description: 'Use default Claude routing (no LLM proxy)',\n },\n {\n name: 'GPT-5 (Reasoning: High)',\n value: {\n provider: 'chatgpt',\n model: 'gpt-5',\n reasoningEffort: 'high',\n },\n description: 'Route to GPT-5 with high reasoning effort',\n },\n {\n name: 'GPT-5 (Reasoning: Medium)',\n value: {\n provider: 'chatgpt',\n model: 'gpt-5',\n reasoningEffort: 'medium',\n },\n description: 'Route to GPT-5 with medium reasoning effort',\n },\n {\n name: 'GPT-5 (Reasoning: Low)',\n value: {\n provider: 'chatgpt',\n model: 'gpt-5',\n reasoningEffort: 'low',\n },\n description: 'Route to GPT-5 with low reasoning effort',\n },\n {\n name: 'GPT-5 (Reasoning: Minimal)',\n value: {\n provider: 'chatgpt',\n model: 'gpt-5',\n reasoningEffort: 'minimal',\n },\n description: 'Route to GPT-5 with minimal reasoning effort',\n },\n {\n name: 'GPT-5 Codex (Reasoning: High)',\n value: {\n provider: 'chatgpt',\n model: 'gpt-5-codex',\n reasoningEffort: 'high',\n },\n description: 'Route to GPT-5 Codex with high reasoning effort',\n },\n {\n name: 'GPT-5 Codex (Reasoning: Medium)',\n value: {\n provider: 'chatgpt',\n model: 'gpt-5-codex',\n reasoningEffort: 'medium',\n },\n description: 'Route to GPT-5 Codex with medium reasoning effort',\n },\n {\n name: 'GPT-5 Codex (Reasoning: Low)',\n value: {\n provider: 'chatgpt',\n model: 'gpt-5-codex',\n reasoningEffort: 'low',\n },\n description: 'Route to GPT-5 Codex with low reasoning effort',\n },\n ];\n\n // Prompt user to select routing option\n const selectedOption = await select({\n message: 'Select LLM routing configuration:',\n choices: routingOptions.map((option) => ({\n name: option.name,\n value: option.value,\n description: option.description,\n })),\n });\n\n // Update session settings\n const currentSettings = sessions[selectedSessionId];\n const displayName = currentSettings?.alias || selectedSessionId;\n\n if (selectedOption === null) {\n // Clear routing fields but keep session entry with alias\n const emptySettings: SessionModelSettings = {\n ...(currentSettings?.alias && { alias: currentSettings.alias }),\n };\n await SessionSettingsManager.setSessionSettings(selectedSessionId, emptySettings);\n this.success(`Routing cleared for session \"${displayName}\". Using default Claude.`);\n } else {\n // Preserve the alias when updating settings\n const updatedSettings = {\n ...selectedOption,\n alias: currentSettings?.alias,\n };\n await SessionSettingsManager.setSessionSettings(selectedSessionId, updatedSettings);\n this.success(\n `Routing configured for session \"${displayName}\": ${selectedOption.provider}/${selectedOption.model}${selectedOption.reasoningEffort ? ` (${selectedOption.reasoningEffort})` : ''}`,\n );\n }\n\n this.info('Note: Restart the agent for changes to take effect.');\n } catch (error) {\n if (error instanceof Error && error.message.includes('User force closed')) {\n this.info('Operation cancelled by user');\n return;\n }\n throw error;\n }\n }\n}\n","#!/usr/bin/env node\n\n/**\n * Unified CLI entry point.\n * Keep logic simple: parse first arg as command, delegate to command class.\n * Additional commands can be added by extending the commands map.\n */\n\nimport { Command } from 'commander';\nimport dotenv from 'dotenv';\nimport { ClaudeCommand, ConnectCommand, LogoutCommand, RouterCommand } from './commands';\n\n// Load environment variables from .env file at startup\ndotenv.config();\n\nasync function main(): Promise<void> {\n const program = new Command();\n program\n .name('agiflow')\n .description('@agiflowai/agent-cli')\n .option('-v, --verbose', 'enable verbose logging')\n .option('--debug', 'enable debug mode');\n\n // Register commands\n const claude = new ClaudeCommand();\n if ('register' in claude && typeof (claude as any).register === 'function') {\n (claude as any).register(program);\n } else {\n program\n .command('claude')\n .description('Launch Claude Code agent')\n .action(async () => {\n await (claude as any).run?.([]);\n });\n }\n\n const connect = new ConnectCommand();\n if ('register' in connect && typeof (connect as any).register === 'function') {\n (connect as any).register(program);\n } else {\n program\n .command('connect')\n .description('Connect agent')\n .action(async () => {\n await (connect as any).run?.([]);\n });\n }\n\n const logout = new LogoutCommand();\n if ('register' in logout && typeof (logout as any).register === 'function') {\n (logout as any).register(program);\n } else {\n program\n .command('logout')\n .description('Logout and clean up credentials')\n .action(async () => {\n await (logout as any).run?.([]);\n });\n }\n\n const router = new RouterCommand();\n if ('register' in router && typeof (router as any).register === 'function') {\n (router as any).register(program);\n } else {\n program\n .command('router')\n .description('Manage Agiflow routing configuration')\n .action(async () => {\n await (router as any).run?.([]);\n });\n }\n\n try {\n await program.parseAsync(process.argv);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error('[cli] error', (e as Error).message);\n if (program.opts().debug && e instanceof Error) {\n // eslint-disable-next-line no-console\n console.error(e.stack);\n }\n process.exit(1);\n }\n}\n\nmain();\n"],"names":["CommanderError","exitCode","code","message","InvalidArgumentError","error","require$$0","Argument","name","description","value","previous","fn","values","arg","humanReadableArgName","nameOutput","argument","Help","cmd","visibleCommands","helpCommand","b","a","getSortKey","option","visibleOptions","helpOption","removeShort","removeLong","globalOptions","ancestorCmd","args","helper","max","command","cmdName","ancestorCmdNames","extraInfo","choice","extraDescripton","termWidth","helpWidth","itemIndentWidth","itemSeparatorWidth","formatItem","term","fullText","formatList","textArray","output","commandDescription","argumentList","optionList","globalOptionList","commandList","str","width","indent","minColumnWidth","indents","manualIndent","columnWidth","leadingStr","columnText","indentString","breaks","regex","lines","line","i","help","Option","flags","optionFlags","splitOptionFlags","names","impliedOptionValues","newImplied","mandatory","hide","camelcase","DualOptions","options","key","optionKey","preset","negativeValue","word","shortFlag","longFlag","flagParts","maxDistance","editDistance","d","j","cost","suggestSimilar","candidates","searchingOptions","candidate","similar","bestDistance","minSimilarity","distance","length","suggestSimilar_1","EventEmitter","childProcess","require$$1","path","require$$2","fs","require$$3","process","require$$4","require$$5","require$$6","require$$7","require$$8","require$$9","Command","write","sourceCommand","result","nameAndArgs","actionOptsOrExecDesc","execOpts","desc","opts","configuration","displayHelp","displaySuggestion","defaultValue","detail","previousArgument","enableOrNameAndArgs","helpName","helpArgs","helpDescription","deprecatedDescription","event","listener","allowedValues","err","expectedArgsCount","actionArgs","target","invalidArgumentMessage","matchingOption","matchingFlag","knownBy","alreadyUsed","existingCmd","newCmd","oname","positiveLongFlag","handleOptionValue","val","invalidValueMessage","valueSource","oldValue","config","def","m","parseArg","combine","allowUnknown","allowExcess","positional","passThrough","storeAsProperties","source","argv","parseOptions","execArgv","userArgs","subcommand","launchWithNode","sourceExt","findFile","baseDir","baseName","localBin","foundExt","ext","executableFile","executableDir","resolvedScriptPath","localFile","legacyName","proc","incrementNodeInspectorPort","signal","exitCallback","executableDirMessage","executableMissing","wrappedError","commandName","operands","unknown","subCommand","promiseChain","subcommandName","myParseArg","parsedValue","processedArgs","declaredArg","index","processed","v","promise","hooks","hookedCommand","callback","hookDetail","hook","parsed","checkForUnknownOptions","commandEvent","anOption","definedNonDefaultOptions","conflictingAndDefined","defined","dest","maybeOption","activeVariadicOption","len","combinedOptions","errorOptions","dualHelper","hasCustomOptionValue","impliedKey","conflictingOption","findBestOptionFromValue","optionValue","negativeOption","positiveOption","getErrorMessage","bestOption","flag","suggestion","candidateFlags","moreFlags","receivedArgs","expected","s","unknownName","candidateNames","versionOption","argsDescription","alias","matchingCommand","aliases","filename","contextOptions","context","deprecatedCallback","helpInformation","position","text","helpEvent","helpStr","debugOption","debugHost","debugPort","match","commander","program","createCommand","createArgument","createOption","InvalidOptionArgumentError","os","crypto","version","TIPS","_getRandomTip","parseBoolean","supportsAnsi","dim","LINE","parse","src","obj","maybeQuote","_parseVault","vaultPath","_vaultPath","DotenvModule","keys","_dotenvKey","decrypted","attrs","_instructions","_warn","_debug","_log","dotenvKey","uri","environment","environmentKey","ciphertext","possibleVaultPath","filepath","_resolveHome","envPath","_configVault","debug","quiet","processEnv","configDotenv","dotenvPath","encoding","optionPaths","lastError","parsedAll","e","populated","keysCount","shortPaths","filePath","relative","decrypt","encrypted","keyStr","nonce","authTag","aesgcm","isRange","invalidKeyLength","decryptionFailed","populate","override","mainModule","ANSI_BACKGROUND_OFFSET","wrapAnsi16","offset","wrapAnsi256","wrapAnsi16m","red","green","blue","styles","foregroundColorNames","backgroundColorNames","assembleStyles","codes","groupName","group","styleName","style","hex","matches","colorString","character","integer","remainder","ansiStyles","level","brand","colorSupport","supportsColor","stringReplaceAll","string","substring","replacer","substringLength","endIndex","returnValue","stringEncaseCRLFWithFirstIndex","prefix","postfix","gotCR","stdoutColor","stderrColor","GENERATOR","STYLER","IS_EMPTY","levelMapping","applyOptions","object","colorLevel","chalkFactory","chalk","strings","createChalk","builder","createBuilder","createStyler","getModelAnsi","model","type","arguments_","usedModels","styler","bgModel","proto","open","close","parent","openAll","closeAll","self","_styler","_isEmpty","applyStyle","lfIndex","copyProperty","to","from","property","ignoreNonConfigurable","toDescriptor","fromDescriptor","canCopyProperty","changePrototype","fromPrototype","wrappedToString","withName","fromBody","toStringDescriptor","toStringName","changeToString","newToString","writable","enumerable","configurable","mimicFunction","calledFunctions","onetime","function_","callCount","functionName","signals","processOk","kExitEmitter","global","ObjectDefineProperty","Emitter","ev","list","ret","SignalExitBase","signalExitWrap","handler","cb","SignalExitFallback","SignalExit","#hupSig","#emitter","#process","#originalProcessEmit","#originalProcessReallyExit","#sigListeners","#loaded","sig","listeners","count","p","#processEmit","#processReallyExit","og","onExit","terminal","restoreCursor","isHidden","cliCursor","writableStream","force","spinners","spinnersList","randomIndex","spinnerName","cliSpinners","logSymbols","ansiRegex","onlyFirst","pattern","stripAnsi","isAmbiguous","x","isFullWidth","isWide","validate","codePoint","eastAsianWidth","ambiguousAsWide","emojiRegex","segmenter","defaultIgnorableCodePointRegex","stringWidth","ambiguousIsNarrow","countAnsiEscapeCodes","eastAsianWidthOptions","isInteractive","stream","isUnicodeSupported","env","TERM","TERM_PROGRAM","ASCII_ETX_CODE","StdinDiscarder","#activeCount","#realStart","#realStop","#handleInput","chunk","stdinDiscarder","Ora","#linesToClear","#isDiscardingStdin","#lineCount","#frameIndex","#lastSpinnerFrameTime","#options","#spinner","#stream","#id","#initialInterval","#isEnabled","#isSilent","#indent","#text","#prefixText","#suffixText","newValue","#updateLineCount","spinner","#getFullPrefixText","prefixText","#getFullSuffixText","suffixText","columns","fullPrefixText","fullSuffixText","now","frames","frame","symbolText","textToWrite","ora","BaseCommand","AGENT_EVENT_TYPES","AGENT_TYPES","AGENT_STATUS","OUTPUT_STREAMS","DAEMON_EVENT_TYPES","DAEMON_STATUS","COMMANDS","BaseAgentSessionEventSchema","z.object","z.string","z.number","AgentStatusSchema","z.enum","AgentTypeSchema","OutputStreamSchema","AgentSessionStatusRequestEventSchema","z.literal","z.boolean","AgentSessionResizeRequestEventSchema","z.coerce.number","AgentSessionDirectControlRequestEventSchema","z.record","z.any","AgentSessionStatusResponseEventSchema","AgentSessionMessageInputRequestEventSchema","z.coerce.string","z.array","AgentSessionMessageInputResponseEventSchema","AgentSessionMessageOutputRequestEventSchema","AgentSessionMessageOutputResponseEventSchema","z.unknown","AgentSessionMessageOutputPermissionRequestedEventSchema","AgentSessionMessageStdinRequestEventSchema","AgentSessionMessageStdoutResponseEventSchema","AgentSessionMessageOutputStartedEventSchema","AgentSessionMessageOutputEndedEventSchema","AgentSessionMessageDeletedEventSchema","AgentSessionErrorRequestEventSchema","AgentSessionErrorResponseEventSchema","AgentSessionStatusAckEventSchema","AgentSessionMessageInputAckEventSchema","AgentSessionMessageOutputAckEventSchema","AgentSessionMessageDeletedAckEventSchema","AgentSessionErrorAckEventSchema","z.union","BaseDaemonEventSchema","DaemonStatusSchema","DaemonStatusRequestEventSchema","DaemonStatusResponseEventSchema","DaemonErrorRequestEventSchema","DaemonErrorResponseEventSchema","DaemonTerminateRequestEventSchema","DaemonTerminateResponseEventSchema","DaemonListAgentSessionsRequestEventSchema","DaemonListAgentSessionsResponseEventSchema","DaemonStartAgentRequestEventSchema","DaemonStartAgentResponseEventSchema","DaemonStartAgentAckEventSchema","DaemonStopAgentRequestEventSchema","DaemonStopAgentResponseEventSchema","DaemonStopAgentAckEventSchema","DaemonTerminateAckEventSchema","DaemonListAgentSessionsAckEventSchema","ConfigSchema","z","dotenv","getServerUrl","forceDocker","getWebSocketUrl","httpUrl","url","generateDeviceId","stable","workDir","safeHost","dir","hash","getSystemInfo","httpToWebSocket","webSocketToHttp","wsUrl","defaultPort","createHeartbeat","interval","logger","timer","log","start","stop","AgentWsService","callbacks","defaultReconnectInterval","SubEnvManager","CredentialsService","Logger","sessionId","WebSocket","resolve","reject","headers","data","rawMessage","reason","payload","wsState","baseInterval","backoffMultiplier","reconnectDelay","errorMessage","deviceId","statusEvent","validatedEvent","PtyRunnerService","agentSessionId","ulid","workingDir","agentEnv","ENV_KEYS","ptyProcess","pty","session","exitInfo","input","cols","rows","RepoSetupService","existsSync","f","envFiles","foundFiles","originalPath","relativePath","targetPath","join","targetDir","dirname","mkdir","copyFile","directory","depth","entries","readdir","entry","fullPath","subDirFiles","dirName","packageManager","packageJsonPath","installCommand","execSync","installError","indicator","userProvidedHooks","defaultHooks","setupResult","buildError","StdinForwarding","onData","c","TerminationService","existing","terminationPromise","timeout","timeoutPromise","_","terminatedContext","agentSessionIds","terminationPromises","BaseAgent","wsOptions","wsCallbacks","serverUrl","effectiveApiUrl","AgentHttpService","currentStatus","statusMessage","content","preCommand","timeSinceLastSent","remainingTime","truncatedData","bufferedData","enabled","silent","wasFullscreen","info","existingEnv","networkLogPath","sameDirJs","sameDirTs","parentDirJs","parentDirTs","nodeOptions","hooksToExecute","failedHooks","messageId","spawn","hookResult","child","stdout","stderr","errorDetails","detailedError","status","updateError","firstFailure","comment","failure","details","request","agentConfig","workingDirectory","originalDirectory","copiedCount","userHooks","ClaudeAgent","claudePath","fileType","cleaned","isSimple","r","config1","config2","args1","args2","projectMcpPath","agentMcps","projectConfigContent","projectConfig","agentMcpServers","item","mergedServers","removedServers","serverName","serverConfig","hasDuplicateName","hasDuplicateCommand","agentServer","fileName","rawMcps","mcpServers","subagents","projectAgentsDir","projectAgents","file","agent","agentName","userAgentsDir","userAgents","sa","major","possiblePostToolUsePaths","postToolUseHookPath","candidatePath","possiblePreToolUsePaths","preToolUseHookPath","possibleNotificationPaths","notificationHookPath","possibleSessionStartPaths","sessionStartHookPath","settings","fsPromises","settingsPath","settingsDir","hookPath","possibleDistPaths","ourHook","h","hookCommand","provider","reasoningEffort","agiflowDir","sessionsFile","sessions","FileSystemUtils","xtermEnabled","llmConfig","sessionAlias","detectedArgs","mcpConfigPath","projectMcpConfigPath","mergedProjectMcpConfigPath","mcpConfigFiles","originalSigintHandlers","sigintHandler","ptySession","agentInfo","claudeArgs","conversationSessionId","DockerRunnerService","docker","dockerImage","dockerArgs","fullCommand","dockerProcess","containerId","dataStr","port","apiKey","orgId","agentType","credentialsDir","volume","mountStr","encodedConfig","BaseDockerAgent","ClaudeDockerAgent","dockerOptions","dockerSession","dockerHttpUrl","dockerWsUrl","processedMcpConfig","agentConfigForContainer","_payload","volumes","homeDir","claudeTmpJsonPath","claudeTmpDirPath","claudeJsonPath","claudeDirPath","_input","ClaudeCommand","allowedProviders","normalizedProvider","apiUrl","organizationId","randomUUID","generateSessionAlias","timestamp","credentialsService","terminationService","claudeAgent","decodedConfig","parsedConfig","launchRequest","handleShutdown","execAsync","promisify","exec","AgentProfiles","homedir","projectClaudePath","searchPaths","searchPath","maxDepth","foundPath","agentsDir","frontmatterStart","frontmatterEnd","frontmatterLines","frontmatter","colonIndex","prompt","agentFiles","profiles","profile","query","lowerQuery","DeviceCodeAuthService","apiKeyToken","deviceCodeResponse","errorText","deviceData","verificationUrl","verificationToken","exchangeResp","errText","tokenData","expiresAt","confirm","response","successCount","errorCount","Semaphore","permits","KeyedSemaphore","semaphore","GeminiAgent","extensionConfigPath","projectExtensionConfigPath","cleanedBuffer","out","raw","seen","o","optionsData","selectComponent","createSelectComponent","toolInput","createToolInvocationInput","gitRepoRoot","geminiExtensionsDir","extensionData","startDir","currentDir","root","gitDir","gitignorePath","gitignoreContent","newContent","GitWorktreeService","repositoryPath","currentPath","rootPath","iterations","maxIterations","parentPath","cwd","gitError","worktrees","branch","commit","basename","worktreeName","gitRoot","repoName","finalBranch","sanitizedBranch","worktreeDirName","worktreeName_final","parentDir","worktreesDir","worktreePath","gitCommand","localBranchExists","remoteBranchExists","currentBranch","worktreeInfo","pushError","addAll","skipVerify","cleanError","skipVerifyFlag","remote","fallbackError","commitMessage","forceFlag","commitAndPush","canPushToRemote","remoteUrl","hostname","ref","branchName","worktree","randomSuffix","defaultBranch","remoteHead","commonMainBranches","mainBranch","existingPR","prs","prTitle","prBody","prCommand","prUrl","AgentWorker","onFullscreenChange","req","creds","worktreeConfig","devInfo","messageData","isGemini","isClaude","commonOpts","useDocker","isAutonomous","instance","agentTypeStr","setupStartMessage","hasSuccess","setupCompleteMessage","setupErrorMessage","msgError","AgentsManager","changedAgentSessionId","isFullscreen","startAgentRequest","onError","agentWorker","AgentDetectionService","agents","availableAgents","installedCount","executable","versionOutput","pathOutput","isMacOS","installedAgents","dockerAvailable","agentTypesForRegistration","DaemonHttpService","storedKey","authToken","retryOnAuth","newHeaders","retryOptions","deviceGuid","storedDeviceId","systemInfo","agentTypes","registrationData","registrationResponse","daemonRegistration","heartbeatData","DaemonWsService","storedApiKey","storedOrgId","api","daemonId","statusRequest","statusResponse","stopAgentRequest","stopped","stopAgentResponse","terminateRequest","terminateResponse","listRequest","listResponse","DaemonWorker","logPath","isWebSocketInitiated","apiKeyToUse","forceExitTimeout","id","ConnectCommand","reconnectInterval","deviceCodeAuth","daemon","stats","LogoutCommand","credentialFiles","removedFiles","RouterCommand","SessionSettingsManager","sessionIds","sessionChoices","displayName","currentRouting","selectedSessionId","select","routingOptions","selectedOption","currentSettings","emptySettings","updatedSettings","main","claude","connect","logout","router"],"mappings":"60CAGA,MAAMA,UAAuB,KAAM,CAOjC,YAAYC,EAAUC,EAAMC,EAAS,CACnC,MAAMA,CAAO,EAEb,MAAM,kBAAkB,KAAM,KAAK,WAAW,EAC9C,KAAK,KAAO,KAAK,YAAY,KAC7B,KAAK,KAAOD,EACZ,KAAK,SAAWD,EAChB,KAAK,YAAc,MACvB,CACA,CAKA,MAAMG,UAA6BJ,CAAe,CAKhD,YAAYG,EAAS,CACnB,MAAM,EAAG,4BAA6BA,CAAO,EAE7C,MAAM,kBAAkB,KAAM,KAAK,WAAW,EAC9C,KAAK,KAAO,KAAK,YAAY,IACjC,CACA,CAEA,OAAAE,GAAA,eAAyBL,EACzBK,GAAA,qBAA+BD,+CCtC/B,KAAM,CAAE,qBAAAA,CAAoB,EAAKE,GAAA,EAEjC,MAAMC,CAAS,CAUb,YAAYC,EAAMC,EAAa,CAQ7B,OAPA,KAAK,YAAcA,GAAe,GAClC,KAAK,SAAW,GAChB,KAAK,SAAW,OAChB,KAAK,aAAe,OACpB,KAAK,wBAA0B,OAC/B,KAAK,WAAa,OAEVD,EAAK,CAAC,EAAC,CACb,IAAK,IACH,KAAK,SAAW,GAChB,KAAK,MAAQA,EAAK,MAAM,EAAG,EAAE,EAC7B,MACF,IAAK,IACH,KAAK,SAAW,GAChB,KAAK,MAAQA,EAAK,MAAM,EAAG,EAAE,EAC7B,MACF,QACE,KAAK,SAAW,GAChB,KAAK,MAAQA,EACb,KACR,CAEQ,KAAK,MAAM,OAAS,GAAK,KAAK,MAAM,MAAM,EAAE,IAAM,QACpD,KAAK,SAAW,GAChB,KAAK,MAAQ,KAAK,MAAM,MAAM,EAAG,EAAE,EAEzC,CAQE,MAAO,CACL,OAAO,KAAK,KAChB,CAME,aAAaE,EAAOC,EAAU,CAC5B,OAAIA,IAAa,KAAK,cAAgB,CAAC,MA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