UNPKG

@botpress/adk-cli

Version:

Command-line interface for the Botpress Agent Development Kit (ADK)

3,939 lines 161 kB
#!/usr/bin/env bun
// @bun
import {
  fatalWith
} from "./chunk-5mfrmhhc.js";
import {
  ADK_LOGO_LINE1,
  ADK_LOGO_LINE2
} from "./chunk-9e2nksab.js";
import {
  bold,
  box,
  fg,
  getActiveTheme,
  renderToString,
  t,
  text
} from "./chunk-m2h26j5f.js";
import"./chunk-8gqzjqmb.js";
import {
  checkNodeVersion
} from "./chunk-5ky86nkb.js";
import {
  INTERNAL_UI_SERVER_ARG
} from "./chunk-sgj6770p.js";
import {
  preflightRuntimeVersionCheck
} from "./chunk-ty7sdgd4.js";
import"./chunk-nbasj5jm.js";
import {
  findAgentRoot,
  findAgentRootOrFail
} from "./chunk-kk3h6qaj.js";
import {
  createCliLogger,
  source_default
} from "./chunk-gzwt1qdr.js";
import {
  CLI_VERSION
} from "./chunk-nxy2ya5r.js";
import {
  sanitizeErrorMessage
} from "./chunk-wzj4dc7n.js";
import"./chunk-p0hjqn4r.js";
import"./chunk-np5wcwfv.js";
import"./chunk-dq2xpa24.js";
import"./chunk-6w0knnta.js";
import"./chunk-40x04ckt.js";
import"./chunk-t76d8fxx.js";
import"./chunk-nh2akp42.js";
import"./chunk-0fdvzjbh.js";
import"./chunk-2a5b6azq.js";
import"./chunk-vay209b5.js";
import"./chunk-3xrpxgq4.js";
import"./chunk-rfm3jr1m.js";
import"./chunk-w346ejn9.js";
import"./chunk-knvm2anf.js";
import"./chunk-65h5trb5.js";
import"./chunk-s2akeqpw.js";
import"./chunk-6771vrjp.js";
import"./chunk-g8mm42v1.js";
import"./chunk-50hzjdck.js";
import"./chunk-nn2jb0x0.js";
import"./chunk-v8xvth6j.js";
import"./chunk-kkk13rcb.js";
import"./chunk-ytpp1kam.js";
import"./chunk-na956zz3.js";
import"./chunk-f4bw8q7c.js";
import"./chunk-0v8vgrns.js";
import"./chunk-54qt5g7m.js";
import {
  __commonJS,
  __require,
  __toESM
} from "./chunk-dhs2bg35.js";

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/error.js
var require_error = __commonJS((exports) => {
  class CommanderError extends Error {
    constructor(exitCode, code, message) {
      super(message);
      Error.captureStackTrace(this, this.constructor);
      this.name = this.constructor.name;
      this.code = code;
      this.exitCode = exitCode;
      this.nestedError = undefined;
    }
  }

  class InvalidArgumentError extends CommanderError {
    constructor(message) {
      super(1, "commander.invalidArgument", message);
      Error.captureStackTrace(this, this.constructor);
      this.name = this.constructor.name;
    }
  }
  exports.CommanderError = CommanderError;
  exports.InvalidArgumentError = InvalidArgumentError;
});

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/argument.js
var require_argument = __commonJS((exports) => {
  var { InvalidArgumentError } = require_error();

  class Argument {
    constructor(name, description) {
      this.description = description || "";
      this.variadic = false;
      this.parseArg = undefined;
      this.defaultValue = undefined;
      this.defaultValueDescription = undefined;
      this.argChoices = undefined;
      switch (name[0]) {
        case "<":
          this.required = true;
          this._name = name.slice(1, -1);
          break;
        case "[":
          this.required = false;
          this._name = name.slice(1, -1);
          break;
        default:
          this.required = true;
          this._name = name;
          break;
      }
      if (this._name.endsWith("...")) {
        this.variadic = true;
        this._name = this._name.slice(0, -3);
      }
    }
    name() {
      return this._name;
    }
    _collectValue(value, previous) {
      if (previous === this.defaultValue || !Array.isArray(previous)) {
        return [value];
      }
      previous.push(value);
      return previous;
    }
    default(value, description) {
      this.defaultValue = value;
      this.defaultValueDescription = description;
      return this;
    }
    argParser(fn) {
      this.parseArg = fn;
      return this;
    }
    choices(values) {
      this.argChoices = values.slice();
      this.parseArg = (arg, previous) => {
        if (!this.argChoices.includes(arg)) {
          throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
        }
        if (this.variadic) {
          return this._collectValue(arg, previous);
        }
        return arg;
      };
      return this;
    }
    argRequired() {
      this.required = true;
      return this;
    }
    argOptional() {
      this.required = false;
      return this;
    }
  }
  function humanReadableArgName(arg) {
    const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
    return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
  }
  exports.Argument = Argument;
  exports.humanReadableArgName = humanReadableArgName;
});

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/help.js
var require_help = __commonJS((exports) => {
  var { humanReadableArgName } = require_argument();

  class Help {
    constructor() {
      this.helpWidth = undefined;
      this.minWidthToWrap = 40;
      this.sortSubcommands = false;
      this.sortOptions = false;
      this.showGlobalOptions = false;
    }
    prepareContext(contextOptions) {
      this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
    }
    visibleCommands(cmd) {
      const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
      const helpCommand = cmd._getHelpCommand();
      if (helpCommand && !helpCommand._hidden) {
        visibleCommands.push(helpCommand);
      }
      if (this.sortSubcommands) {
        visibleCommands.sort((a, b) => {
          return a.name().localeCompare(b.name());
        });
      }
      return visibleCommands;
    }
    compareOptions(a, b) {
      const getSortKey = (option) => {
        return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
      };
      return getSortKey(a).localeCompare(getSortKey(b));
    }
    visibleOptions(cmd) {
      const visibleOptions = cmd.options.filter((option) => !option.hidden);
      const helpOption = cmd._getHelpOption();
      if (helpOption && !helpOption.hidden) {
        const removeShort = helpOption.short && cmd._findOption(helpOption.short);
        const removeLong = helpOption.long && cmd._findOption(helpOption.long);
        if (!removeShort && !removeLong) {
          visibleOptions.push(helpOption);
        } else if (helpOption.long && !removeLong) {
          visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
        } else if (helpOption.short && !removeShort) {
          visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
        }
      }
      if (this.sortOptions) {
        visibleOptions.sort(this.compareOptions);
      }
      return visibleOptions;
    }
    visibleGlobalOptions(cmd) {
      if (!this.showGlobalOptions)
        return [];
      const globalOptions = [];
      for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
        const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
        globalOptions.push(...visibleOptions);
      }
      if (this.sortOptions) {
        globalOptions.sort(this.compareOptions);
      }
      return globalOptions;
    }
    visibleArguments(cmd) {
      if (cmd._argsDescription) {
        cmd.registeredArguments.forEach((argument) => {
          argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
        });
      }
      if (cmd.registeredArguments.find((argument) => argument.description)) {
        return cmd.registeredArguments;
      }
      return [];
    }
    subcommandTerm(cmd) {
      const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
      return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
    }
    optionTerm(option) {
      return option.flags;
    }
    argumentTerm(argument) {
      return argument.name();
    }
    longestSubcommandTermLength(cmd, helper) {
      return helper.visibleCommands(cmd).reduce((max, command) => {
        return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
      }, 0);
    }
    longestOptionTermLength(cmd, helper) {
      return helper.visibleOptions(cmd).reduce((max, option) => {
        return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
      }, 0);
    }
    longestGlobalOptionTermLength(cmd, helper) {
      return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
        return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
      }, 0);
    }
    longestArgumentTermLength(cmd, helper) {
      return helper.visibleArguments(cmd).reduce((max, argument) => {
        return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
      }, 0);
    }
    commandUsage(cmd) {
      let cmdName = cmd._name;
      if (cmd._aliases[0]) {
        cmdName = cmdName + "|" + cmd._aliases[0];
      }
      let ancestorCmdNames = "";
      for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
        ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
      }
      return ancestorCmdNames + cmdName + " " + cmd.usage();
    }
    commandDescription(cmd) {
      return cmd.description();
    }
    subcommandDescription(cmd) {
      return cmd.summary() || cmd.description();
    }
    optionDescription(option) {
      const extraInfo = [];
      if (option.argChoices) {
        extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
      }
      if (option.defaultValue !== undefined) {
        const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
        if (showDefault) {
          extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
        }
      }
      if (option.presetArg !== undefined && option.optional) {
        extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
      }
      if (option.envVar !== undefined) {
        extraInfo.push(`env: ${option.envVar}`);
      }
      if (extraInfo.length > 0) {
        const extraDescription = `(${extraInfo.join(", ")})`;
        if (option.description) {
          return `${option.description} ${extraDescription}`;
        }
        return extraDescription;
      }
      return option.description;
    }
    argumentDescription(argument) {
      const extraInfo = [];
      if (argument.argChoices) {
        extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
      }
      if (argument.defaultValue !== undefined) {
        extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
      }
      if (extraInfo.length > 0) {
        const extraDescription = `(${extraInfo.join(", ")})`;
        if (argument.description) {
          return `${argument.description} ${extraDescription}`;
        }
        return extraDescription;
      }
      return argument.description;
    }
    formatItemList(heading, items, helper) {
      if (items.length === 0)
        return [];
      return [helper.styleTitle(heading), ...items, ""];
    }
    groupItems(unsortedItems, visibleItems, getGroup) {
      const result = new Map;
      unsortedItems.forEach((item) => {
        const group = getGroup(item);
        if (!result.has(group))
          result.set(group, []);
      });
      visibleItems.forEach((item) => {
        const group = getGroup(item);
        if (!result.has(group)) {
          result.set(group, []);
        }
        result.get(group).push(item);
      });
      return result;
    }
    formatHelp(cmd, helper) {
      const termWidth = helper.padWidth(cmd, helper);
      const helpWidth = helper.helpWidth ?? 80;
      function callFormatItem(term, description) {
        return helper.formatItem(term, termWidth, description, helper);
      }
      let output = [
        `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
        ""
      ];
      const commandDescription = helper.commandDescription(cmd);
      if (commandDescription.length > 0) {
        output = output.concat([
          helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
          ""
        ]);
      }
      const argumentList = helper.visibleArguments(cmd).map((argument) => {
        return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
      });
      output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
      const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
      optionGroups.forEach((options, group) => {
        const optionList = options.map((option) => {
          return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
        });
        output = output.concat(this.formatItemList(group, optionList, helper));
      });
      if (helper.showGlobalOptions) {
        const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
          return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
        });
        output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
      }
      const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
      commandGroups.forEach((commands, group) => {
        const commandList = commands.map((sub) => {
          return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
        });
        output = output.concat(this.formatItemList(group, commandList, helper));
      });
      return output.join(`
`);
    }
    displayWidth(str) {
      return stripColor(str).length;
    }
    styleTitle(str) {
      return str;
    }
    styleUsage(str) {
      return str.split(" ").map((word) => {
        if (word === "[options]")
          return this.styleOptionText(word);
        if (word === "[command]")
          return this.styleSubcommandText(word);
        if (word[0] === "[" || word[0] === "<")
          return this.styleArgumentText(word);
        return this.styleCommandText(word);
      }).join(" ");
    }
    styleCommandDescription(str) {
      return this.styleDescriptionText(str);
    }
    styleOptionDescription(str) {
      return this.styleDescriptionText(str);
    }
    styleSubcommandDescription(str) {
      return this.styleDescriptionText(str);
    }
    styleArgumentDescription(str) {
      return this.styleDescriptionText(str);
    }
    styleDescriptionText(str) {
      return str;
    }
    styleOptionTerm(str) {
      return this.styleOptionText(str);
    }
    styleSubcommandTerm(str) {
      return str.split(" ").map((word) => {
        if (word === "[options]")
          return this.styleOptionText(word);
        if (word[0] === "[" || word[0] === "<")
          return this.styleArgumentText(word);
        return this.styleSubcommandText(word);
      }).join(" ");
    }
    styleArgumentTerm(str) {
      return this.styleArgumentText(str);
    }
    styleOptionText(str) {
      return str;
    }
    styleArgumentText(str) {
      return str;
    }
    styleSubcommandText(str) {
      return str;
    }
    styleCommandText(str) {
      return str;
    }
    padWidth(cmd, helper) {
      return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
    }
    preformatted(str) {
      return /\n[^\S\r\n]/.test(str);
    }
    formatItem(term, termWidth, description, helper) {
      const itemIndent = 2;
      const itemIndentStr = " ".repeat(itemIndent);
      if (!description)
        return itemIndentStr + term;
      const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
      const spacerWidth = 2;
      const helpWidth = this.helpWidth ?? 80;
      const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
      let formattedDescription;
      if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
        formattedDescription = description;
      } else {
        const wrappedDescription = helper.boxWrap(description, remainingWidth);
        formattedDescription = wrappedDescription.replace(/\n/g, `
` + " ".repeat(termWidth + spacerWidth));
      }
      return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
${itemIndentStr}`);
    }
    boxWrap(str, width) {
      if (width < this.minWidthToWrap)
        return str;
      const rawLines = str.split(/\r\n|\n/);
      const chunkPattern = /[\s]*[^\s]+/g;
      const wrappedLines = [];
      rawLines.forEach((line) => {
        const chunks = line.match(chunkPattern);
        if (chunks === null) {
          wrappedLines.push("");
          return;
        }
        let sumChunks = [chunks.shift()];
        let sumWidth = this.displayWidth(sumChunks[0]);
        chunks.forEach((chunk) => {
          const visibleWidth = this.displayWidth(chunk);
          if (sumWidth + visibleWidth <= width) {
            sumChunks.push(chunk);
            sumWidth += visibleWidth;
            return;
          }
          wrappedLines.push(sumChunks.join(""));
          const nextChunk = chunk.trimStart();
          sumChunks = [nextChunk];
          sumWidth = this.displayWidth(nextChunk);
        });
        wrappedLines.push(sumChunks.join(""));
      });
      return wrappedLines.join(`
`);
    }
  }
  function stripColor(str) {
    const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
    return str.replace(sgrPattern, "");
  }
  exports.Help = Help;
  exports.stripColor = stripColor;
});

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/option.js
var require_option = __commonJS((exports) => {
  var { InvalidArgumentError } = require_error();

  class Option {
    constructor(flags, description) {
      this.flags = flags;
      this.description = description || "";
      this.required = flags.includes("<");
      this.optional = flags.includes("[");
      this.variadic = /\w\.\.\.[>\]]$/.test(flags);
      this.mandatory = false;
      const optionFlags = splitOptionFlags(flags);
      this.short = optionFlags.shortFlag;
      this.long = optionFlags.longFlag;
      this.negate = false;
      if (this.long) {
        this.negate = this.long.startsWith("--no-");
      }
      this.defaultValue = undefined;
      this.defaultValueDescription = undefined;
      this.presetArg = undefined;
      this.envVar = undefined;
      this.parseArg = undefined;
      this.hidden = false;
      this.argChoices = undefined;
      this.conflictsWith = [];
      this.implied = undefined;
      this.helpGroupHeading = undefined;
    }
    default(value, description) {
      this.defaultValue = value;
      this.defaultValueDescription = description;
      return this;
    }
    preset(arg) {
      this.presetArg = arg;
      return this;
    }
    conflicts(names) {
      this.conflictsWith = this.conflictsWith.concat(names);
      return this;
    }
    implies(impliedOptionValues) {
      let newImplied = impliedOptionValues;
      if (typeof impliedOptionValues === "string") {
        newImplied = { [impliedOptionValues]: true };
      }
      this.implied = Object.assign(this.implied || {}, newImplied);
      return this;
    }
    env(name) {
      this.envVar = name;
      return this;
    }
    argParser(fn) {
      this.parseArg = fn;
      return this;
    }
    makeOptionMandatory(mandatory = true) {
      this.mandatory = !!mandatory;
      return this;
    }
    hideHelp(hide = true) {
      this.hidden = !!hide;
      return this;
    }
    _collectValue(value, previous) {
      if (previous === this.defaultValue || !Array.isArray(previous)) {
        return [value];
      }
      previous.push(value);
      return previous;
    }
    choices(values) {
      this.argChoices = values.slice();
      this.parseArg = (arg, previous) => {
        if (!this.argChoices.includes(arg)) {
          throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
        }
        if (this.variadic) {
          return this._collectValue(arg, previous);
        }
        return arg;
      };
      return this;
    }
    name() {
      if (this.long) {
        return this.long.replace(/^--/, "");
      }
      return this.short.replace(/^-/, "");
    }
    attributeName() {
      if (this.negate) {
        return camelcase(this.name().replace(/^no-/, ""));
      }
      return camelcase(this.name());
    }
    helpGroup(heading) {
      this.helpGroupHeading = heading;
      return this;
    }
    is(arg) {
      return this.short === arg || this.long === arg;
    }
    isBoolean() {
      return !this.required && !this.optional && !this.negate;
    }
  }

  class DualOptions {
    constructor(options) {
      this.positiveOptions = new Map;
      this.negativeOptions = new Map;
      this.dualOptions = new Set;
      options.forEach((option) => {
        if (option.negate) {
          this.negativeOptions.set(option.attributeName(), option);
        } else {
          this.positiveOptions.set(option.attributeName(), option);
        }
      });
      this.negativeOptions.forEach((value, key) => {
        if (this.positiveOptions.has(key)) {
          this.dualOptions.add(key);
        }
      });
    }
    valueFromOption(value, option) {
      const optionKey = option.attributeName();
      if (!this.dualOptions.has(optionKey))
        return true;
      const preset = this.negativeOptions.get(optionKey).presetArg;
      const negativeValue = preset !== undefined ? preset : false;
      return option.negate === (negativeValue === value);
    }
  }
  function camelcase(str) {
    return str.split("-").reduce((str2, word) => {
      return str2 + word[0].toUpperCase() + word.slice(1);
    });
  }
  function splitOptionFlags(flags) {
    let shortFlag;
    let longFlag;
    const shortFlagExp = /^-[^-]$/;
    const longFlagExp = /^--[^-]/;
    const flagParts = flags.split(/[ |,]+/).concat("guard");
    if (shortFlagExp.test(flagParts[0]))
      shortFlag = flagParts.shift();
    if (longFlagExp.test(flagParts[0]))
      longFlag = flagParts.shift();
    if (!shortFlag && shortFlagExp.test(flagParts[0]))
      shortFlag = flagParts.shift();
    if (!shortFlag && longFlagExp.test(flagParts[0])) {
      shortFlag = longFlag;
      longFlag = flagParts.shift();
    }
    if (flagParts[0].startsWith("-")) {
      const unsupportedFlag = flagParts[0];
      const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
      if (/^-[^-][^-]/.test(unsupportedFlag))
        throw new Error(`${baseError}
- a short flag is a single dash and a single character
  - either use a single dash and a single character (for a short flag)
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
      if (shortFlagExp.test(unsupportedFlag))
        throw new Error(`${baseError}
- too many short flags`);
      if (longFlagExp.test(unsupportedFlag))
        throw new Error(`${baseError}
- too many long flags`);
      throw new Error(`${baseError}
- unrecognised flag format`);
    }
    if (shortFlag === undefined && longFlag === undefined)
      throw new Error(`option creation failed due to no flags found in '${flags}'.`);
    return { shortFlag, longFlag };
  }
  exports.Option = Option;
  exports.DualOptions = DualOptions;
});

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js
var require_suggestSimilar = __commonJS((exports) => {
  var maxDistance = 3;
  function editDistance(a, b) {
    if (Math.abs(a.length - b.length) > maxDistance)
      return Math.max(a.length, b.length);
    const d = [];
    for (let i = 0;i <= a.length; i++) {
      d[i] = [i];
    }
    for (let j = 0;j <= b.length; j++) {
      d[0][j] = j;
    }
    for (let j = 1;j <= b.length; j++) {
      for (let i = 1;i <= a.length; i++) {
        let cost = 1;
        if (a[i - 1] === b[j - 1]) {
          cost = 0;
        } else {
          cost = 1;
        }
        d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
        if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
          d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
        }
      }
    }
    return d[a.length][b.length];
  }
  function suggestSimilar(word, candidates) {
    if (!candidates || candidates.length === 0)
      return "";
    candidates = Array.from(new Set(candidates));
    const searchingOptions = word.startsWith("--");
    if (searchingOptions) {
      word = word.slice(2);
      candidates = candidates.map((candidate) => candidate.slice(2));
    }
    let similar = [];
    let bestDistance = maxDistance;
    const minSimilarity = 0.4;
    candidates.forEach((candidate) => {
      if (candidate.length <= 1)
        return;
      const distance = editDistance(word, candidate);
      const length = Math.max(word.length, candidate.length);
      const similarity = (length - distance) / length;
      if (similarity > minSimilarity) {
        if (distance < bestDistance) {
          bestDistance = distance;
          similar = [candidate];
        } else if (distance === bestDistance) {
          similar.push(candidate);
        }
      }
    });
    similar.sort((a, b) => a.localeCompare(b));
    if (searchingOptions) {
      similar = similar.map((candidate) => `--${candidate}`);
    }
    if (similar.length > 1) {
      return `
(Did you mean one of ${similar.join(", ")}?)`;
    }
    if (similar.length === 1) {
      return `
(Did you mean ${similar[0]}?)`;
    }
    return "";
  }
  exports.suggestSimilar = suggestSimilar;
});

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/command.js
var require_command = __commonJS((exports) => {
  var EventEmitter = __require("events").EventEmitter;
  var childProcess = __require("child_process");
  var path = __require("path");
  var fs = __require("fs");
  var process2 = __require("process");
  var { Argument, humanReadableArgName } = require_argument();
  var { CommanderError } = require_error();
  var { Help, stripColor } = require_help();
  var { Option, DualOptions } = require_option();
  var { suggestSimilar } = require_suggestSimilar();

  class Command extends EventEmitter {
    constructor(name) {
      super();
      this.commands = [];
      this.options = [];
      this.parent = null;
      this._allowUnknownOption = false;
      this._allowExcessArguments = false;
      this.registeredArguments = [];
      this._args = this.registeredArguments;
      this.args = [];
      this.rawArgs = [];
      this.processedArgs = [];
      this._scriptPath = null;
      this._name = name || "";
      this._optionValues = {};
      this._optionValueSources = {};
      this._storeOptionsAsProperties = false;
      this._actionHandler = null;
      this._executableHandler = false;
      this._executableFile = null;
      this._executableDir = null;
      this._defaultCommandName = null;
      this._exitCallback = null;
      this._aliases = [];
      this._combineFlagAndOptionalValue = true;
      this._description = "";
      this._summary = "";
      this._argsDescription = undefined;
      this._enablePositionalOptions = false;
      this._passThroughOptions = false;
      this._lifeCycleHooks = {};
      this._showHelpAfterError = false;
      this._showSuggestionAfterError = true;
      this._savedState = null;
      this._outputConfiguration = {
        writeOut: (str) => process2.stdout.write(str),
        writeErr: (str) => process2.stderr.write(str),
        outputError: (str, write) => write(str),
        getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
        getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
        getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
        getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
        stripColor: (str) => stripColor(str)
      };
      this._hidden = false;
      this._helpOption = undefined;
      this._addImplicitHelpCommand = undefined;
      this._helpCommand = undefined;
      this._helpConfiguration = {};
      this._helpGroupHeading = undefined;
      this._defaultCommandGroup = undefined;
      this._defaultOptionGroup = undefined;
    }
    copyInheritedSettings(sourceCommand) {
      this._outputConfiguration = sourceCommand._outputConfiguration;
      this._helpOption = sourceCommand._helpOption;
      this._helpCommand = sourceCommand._helpCommand;
      this._helpConfiguration = sourceCommand._helpConfiguration;
      this._exitCallback = sourceCommand._exitCallback;
      this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
      this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
      this._allowExcessArguments = sourceCommand._allowExcessArguments;
      this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
      this._showHelpAfterError = sourceCommand._showHelpAfterError;
      this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
      return this;
    }
    _getCommandAndAncestors() {
      const result = [];
      for (let command = this;command; command = command.parent) {
        result.push(command);
      }
      return result;
    }
    command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
      let desc = actionOptsOrExecDesc;
      let opts = execOpts;
      if (typeof desc === "object" && desc !== null) {
        opts = desc;
        desc = null;
      }
      opts = opts || {};
      const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
      const cmd = this.createCommand(name);
      if (desc) {
        cmd.description(desc);
        cmd._executableHandler = true;
      }
      if (opts.isDefault)
        this._defaultCommandName = cmd._name;
      cmd._hidden = !!(opts.noHelp || opts.hidden);
      cmd._executableFile = opts.executableFile || null;
      if (args)
        cmd.arguments(args);
      this._registerCommand(cmd);
      cmd.parent = this;
      cmd.copyInheritedSettings(this);
      if (desc)
        return this;
      return cmd;
    }
    createCommand(name) {
      return new Command(name);
    }
    createHelp() {
      return Object.assign(new Help, this.configureHelp());
    }
    configureHelp(configuration) {
      if (configuration === undefined)
        return this._helpConfiguration;
      this._helpConfiguration = configuration;
      return this;
    }
    configureOutput(configuration) {
      if (configuration === undefined)
        return this._outputConfiguration;
      this._outputConfiguration = {
        ...this._outputConfiguration,
        ...configuration
      };
      return this;
    }
    showHelpAfterError(displayHelp = true) {
      if (typeof displayHelp !== "string")
        displayHelp = !!displayHelp;
      this._showHelpAfterError = displayHelp;
      return this;
    }
    showSuggestionAfterError(displaySuggestion = true) {
      this._showSuggestionAfterError = !!displaySuggestion;
      return this;
    }
    addCommand(cmd, opts) {
      if (!cmd._name) {
        throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
      }
      opts = opts || {};
      if (opts.isDefault)
        this._defaultCommandName = cmd._name;
      if (opts.noHelp || opts.hidden)
        cmd._hidden = true;
      this._registerCommand(cmd);
      cmd.parent = this;
      cmd._checkForBrokenPassThrough();
      return this;
    }
    createArgument(name, description) {
      return new Argument(name, description);
    }
    argument(name, description, parseArg, defaultValue) {
      const argument = this.createArgument(name, description);
      if (typeof parseArg === "function") {
        argument.default(defaultValue).argParser(parseArg);
      } else {
        argument.default(parseArg);
      }
      this.addArgument(argument);
      return this;
    }
    arguments(names) {
      names.trim().split(/ +/).forEach((detail) => {
        this.argument(detail);
      });
      return this;
    }
    addArgument(argument) {
      const previousArgument = this.registeredArguments.slice(-1)[0];
      if (previousArgument?.variadic) {
        throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
      }
      if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
        throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
      }
      this.registeredArguments.push(argument);
      return this;
    }
    helpCommand(enableOrNameAndArgs, description) {
      if (typeof enableOrNameAndArgs === "boolean") {
        this._addImplicitHelpCommand = enableOrNameAndArgs;
        if (enableOrNameAndArgs && this._defaultCommandGroup) {
          this._initCommandGroup(this._getHelpCommand());
        }
        return this;
      }
      const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
      const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
      const helpDescription = description ?? "display help for command";
      const helpCommand = this.createCommand(helpName);
      helpCommand.helpOption(false);
      if (helpArgs)
        helpCommand.arguments(helpArgs);
      if (helpDescription)
        helpCommand.description(helpDescription);
      this._addImplicitHelpCommand = true;
      this._helpCommand = helpCommand;
      if (enableOrNameAndArgs || description)
        this._initCommandGroup(helpCommand);
      return this;
    }
    addHelpCommand(helpCommand, deprecatedDescription) {
      if (typeof helpCommand !== "object") {
        this.helpCommand(helpCommand, deprecatedDescription);
        return this;
      }
      this._addImplicitHelpCommand = true;
      this._helpCommand = helpCommand;
      this._initCommandGroup(helpCommand);
      return this;
    }
    _getHelpCommand() {
      const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
      if (hasImplicitHelpCommand) {
        if (this._helpCommand === undefined) {
          this.helpCommand(undefined, undefined);
        }
        return this._helpCommand;
      }
      return null;
    }
    hook(event, listener) {
      const allowedValues = ["preSubcommand", "preAction", "postAction"];
      if (!allowedValues.includes(event)) {
        throw new Error(`Unexpected value for event passed to hook : '${event}'.
Expecting one of '${allowedValues.join("', '")}'`);
      }
      if (this._lifeCycleHooks[event]) {
        this._lifeCycleHooks[event].push(listener);
      } else {
        this._lifeCycleHooks[event] = [listener];
      }
      return this;
    }
    exitOverride(fn) {
      if (fn) {
        this._exitCallback = fn;
      } else {
        this._exitCallback = (err) => {
          if (err.code !== "commander.executeSubCommandAsync") {
            throw err;
          }
        };
      }
      return this;
    }
    _exit(exitCode, code, message) {
      if (this._exitCallback) {
        this._exitCallback(new CommanderError(exitCode, code, message));
      }
      process2.exit(exitCode);
    }
    action(fn) {
      const listener = (args) => {
        const expectedArgsCount = this.registeredArguments.length;
        const actionArgs = args.slice(0, expectedArgsCount);
        if (this._storeOptionsAsProperties) {
          actionArgs[expectedArgsCount] = this;
        } else {
          actionArgs[expectedArgsCount] = this.opts();
        }
        actionArgs.push(this);
        return fn.apply(this, actionArgs);
      };
      this._actionHandler = listener;
      return this;
    }
    createOption(flags, description) {
      return new Option(flags, description);
    }
    _callParseArg(target, value, previous, invalidArgumentMessage) {
      try {
        return target.parseArg(value, previous);
      } catch (err) {
        if (err.code === "commander.invalidArgument") {
          const message = `${invalidArgumentMessage} ${err.message}`;
          this.error(message, { exitCode: err.exitCode, code: err.code });
        }
        throw err;
      }
    }
    _registerOption(option) {
      const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
      if (matchingOption) {
        const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
        throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
-  already used by option '${matchingOption.flags}'`);
      }
      this._initOptionGroup(option);
      this.options.push(option);
    }
    _registerCommand(command) {
      const knownBy = (cmd) => {
        return [cmd.name()].concat(cmd.aliases());
      };
      const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
      if (alreadyUsed) {
        const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
        const newCmd = knownBy(command).join("|");
        throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
      }
      this._initCommandGroup(command);
      this.commands.push(command);
    }
    addOption(option) {
      this._registerOption(option);
      const oname = option.name();
      const name = option.attributeName();
      if (option.negate) {
        const positiveLongFlag = option.long.replace(/^--no-/, "--");
        if (!this._findOption(positiveLongFlag)) {
          this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
        }
      } else if (option.defaultValue !== undefined) {
        this.setOptionValueWithSource(name, option.defaultValue, "default");
      }
      const handleOptionValue = (val, invalidValueMessage, valueSource) => {
        if (val == null && option.presetArg !== undefined) {
          val = option.presetArg;
        }
        const oldValue = this.getOptionValue(name);
        if (val !== null && option.parseArg) {
          val = this._callParseArg(option, val, oldValue, invalidValueMessage);
        } else if (val !== null && option.variadic) {
          val = option._collectValue(val, oldValue);
        }
        if (val == null) {
          if (option.negate) {
            val = false;
          } else if (option.isBoolean() || option.optional) {
            val = true;
          } else {
            val = "";
          }
        }
        this.setOptionValueWithSource(name, val, valueSource);
      };
      this.on("option:" + oname, (val) => {
        const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
        handleOptionValue(val, invalidValueMessage, "cli");
      });
      if (option.envVar) {
        this.on("optionEnv:" + oname, (val) => {
          const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
          handleOptionValue(val, invalidValueMessage, "env");
        });
      }
      return this;
    }
    _optionEx(config, flags, description, fn, defaultValue) {
      if (typeof flags === "object" && flags instanceof Option) {
        throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
      }
      const option = this.createOption(flags, description);
      option.makeOptionMandatory(!!config.mandatory);
      if (typeof fn === "function") {
        option.default(defaultValue).argParser(fn);
      } else if (fn instanceof RegExp) {
        const regex = fn;
        fn = (val, def) => {
          const m = regex.exec(val);
          return m ? m[0] : def;
        };
        option.default(defaultValue).argParser(fn);
      } else {
        option.default(fn);
      }
      return this.addOption(option);
    }
    option(flags, description, parseArg, defaultValue) {
      return this._optionEx({}, flags, description, parseArg, defaultValue);
    }
    requiredOption(flags, description, parseArg, defaultValue) {
      return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
    }
    combineFlagAndOptionalValue(combine = true) {
      this._combineFlagAndOptionalValue = !!combine;
      return this;
    }
    allowUnknownOption(allowUnknown = true) {
      this._allowUnknownOption = !!allowUnknown;
      return this;
    }
    allowExcessArguments(allowExcess = true) {
      this._allowExcessArguments = !!allowExcess;
      return this;
    }
    enablePositionalOptions(positional = true) {
      this._enablePositionalOptions = !!positional;
      return this;
    }
    passThroughOptions(passThrough = true) {
      this._passThroughOptions = !!passThrough;
      this._checkForBrokenPassThrough();
      return this;
    }
    _checkForBrokenPassThrough() {
      if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
        throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
      }
    }
    storeOptionsAsProperties(storeAsProperties = true) {
      if (this.options.length) {
        throw new Error("call .storeOptionsAsProperties() before adding options");
      }
      if (Object.keys(this._optionValues).length) {
        throw new Error("call .storeOptionsAsProperties() before setting option values");
      }
      this._storeOptionsAsProperties = !!storeAsProperties;
      return this;
    }
    getOptionValue(key) {
      if (this._storeOptionsAsProperties) {
        return this[key];
      }
      return this._optionValues[key];
    }
    setOptionValue(key, value) {
      return this.setOptionValueWithSource(key, value, undefined);
    }
    setOptionValueWithSource(key, value, source) {
      if (this._storeOptionsAsProperties) {
        this[key] = value;
      } else {
        this._optionValues[key] = value;
      }
      this._optionValueSources[key] = source;
      return this;
    }
    getOptionValueSource(key) {
      return this._optionValueSources[key];
    }
    getOptionValueSourceWithGlobals(key) {
      let source;
      this._getCommandAndAncestors().forEach((cmd) => {
        if (cmd.getOptionValueSource(key) !== undefined) {
          source = cmd.getOptionValueSource(key);
        }
      });
      return source;
    }
    _prepareUserArgs(argv, parseOptions) {
      if (argv !== undefined && !Array.isArray(argv)) {
        throw new Error("first parameter to parse must be array or undefined");
      }
      parseOptions = parseOptions || {};
      if (argv === undefined && parseOptions.from === undefined) {
        if (process2.versions?.electron) {
          parseOptions.from = "electron";
        }
        const execArgv = process2.execArgv ?? [];
        if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
          parseOptions.from = "eval";
        }
      }
      if (argv === undefined) {
        argv = process2.argv;
      }
      this.rawArgs = argv.slice();
      let userArgs;
      switch (parseOptions.from) {
        case undefined:
        case "node":
          this._scriptPath = argv[1];
          userArgs = argv.slice(2);
          break;
        case "electron":
          if (process2.defaultApp) {
            this._scriptPath = argv[1];
            userArgs = argv.slice(2);
          } else {
            userArgs = argv.slice(1);
          }
          break;
        case "user":
          userArgs = argv.slice(0);
          break;
        case "eval":
          userArgs = argv.slice(1);
          break;
        default:
          throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
      }
      if (!this._name && this._scriptPath)
        this.nameFromFilename(this._scriptPath);
      this._name = this._name || "program";
      return userArgs;
    }
    parse(argv, parseOptions) {
      this._prepareForParse();
      const userArgs = this._prepareUserArgs(argv, parseOptions);
      this._parseCommand([], userArgs);
      return this;
    }
    async parseAsync(argv, parseOptions) {
      this._prepareForParse();
      const userArgs = this._prepareUserArgs(argv, parseOptions);
      await this._parseCommand([], userArgs);
      return this;
    }
    _prepareForParse() {
      if (this._savedState === null) {
        this.saveStateBeforeParse();
      } else {
        this.restoreStateBeforeParse();
      }
    }
    saveStateBeforeParse() {
      this._savedState = {
        _name: this._name,
        _optionValues: { ...this._optionValues },
        _optionValueSources: { ...this._optionValueSources }
      };
    }
    restoreStateBeforeParse() {
      if (this._storeOptionsAsProperties)
        throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
- either make a new Command for each call to parse, or stop storing options as properties`);
      this._name = this._savedState._name;
      this._scriptPath = null;
      this.rawArgs = [];
      this._optionValues = { ...this._savedState._optionValues };
      this._optionValueSources = { ...this._savedState._optionValueSources };
      this.args = [];
      this.processedArgs = [];
    }
    _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
      if (fs.existsSync(executableFile))
        return;
      const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
      const executableMissing = `'${executableFile}' does not exist
 - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
 - ${executableDirMessage}`;
      throw new Error(executableMissing);
    }
    _executeSubCommand(subcommand, args) {
      args = args.slice();
      let launchWithNode = false;
      const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
      function findFile(baseDir, baseName) {
        const localBin = path.resolve(baseDir, baseName);
        if (fs.existsSync(localBin))
          return localBin;
        if (sourceExt.includes(path.extname(baseName)))
          return;
        const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
        if (foundExt)
          return `${localBin}${foundExt}`;
        return;
      }
      this._checkForMissingMandatoryOptions();
      this._checkForConflictingOptions();
      let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
      let executableDir = this._executableDir || "";
      if (this._scriptPath) {
        let resolvedScriptPath;
        try {
          resolvedScriptPath = fs.realpathSync(this._scriptPath);
        } catch {
          resolvedScriptPath = this._scriptPath;
        }
        executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
      }
      if (executableDir) {
        let localFile = findFile(executableDir, executableFile);
        if (!localFile && !subcommand._executableFile && this._scriptPath) {
          const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
          if (legacyName !== this._name) {
            localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
          }
        }
        executableFile = localFile || executableFile;
      }
      launchWithNode = sourceExt.includes(path.extname(executableFile));
      let proc;
      if (process2.platform !== "win32") {
        if (launchWithNode) {
          args.unshift(executableFile);
          args = incrementNodeInspectorPort(process2.execArgv).concat(args);
          proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
        } else {
          proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
        }
      } else {
        this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
        args.unshift(executableFile);
        args = incrementNodeInspectorPort(process2.execArgv).concat(args);
        proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
      }
      if (!proc.killed) {
        const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
        signals.forEach((signal) => {
          process2.on(signal, () => {
            if (proc.killed === false && proc.exitCode === null) {
              proc.kill(signal);
            }
          });
        });
      }
      const exitCallback = this._exitCallback;
      proc.on("close", (code) => {
        code = code ?? 1;
        if (!exitCallback) {
          process2.exit(code);
        } else {
          exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
        }
      });
      proc.on("error", (err) => {
        if (err.code === "ENOENT") {
          this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
        } else if (err.code === "EACCES") {
          throw new Error(`'${executableFile}' not executable`);
        }
        if (!exitCallback) {
          process2.exit(1);
        } else {
          const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
          wrappedError.nestedError = err;
          exitCallback(wrappedError);
        }
      });
      this.runningCommand = proc;
    }
    _dispatchSubcommand(commandName, operands, unknown) {
      const subCommand = this._findCommand(commandName);
      if (!subCommand)
        this.help({ error: true });
      subCommand._prepareForParse();
      let promiseChain;
      promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
      promiseChain = this._chainOrCall(promiseChain, () => {
        if (subCommand._executableHandler) {
          this._executeSubCommand(subCommand, operands.concat(unknown));
        } else {
          return subCommand._parseCommand(operands, unknown);
        }
      });
      return promiseChain;
    }
    _dispatchHelpCommand(subcommandName) {
      if (!subcommandName) {
        this.help();
      }
      const subCommand = this._findCommand(subcommandName);
      if (subCommand && !subCommand._executableHandler) {
        subCommand.help();
      }
      return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
    }
    _checkNumberOfArguments() {
      this.registeredArguments.forEach((arg, i) => {
        if (arg.required && this.args[i] == null) {
          this.missingArgument(arg.name());
        }
      });
      if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
        return;
      }
      if (this.args.length > this.registeredArguments.length) {
        this._excessArguments(this.args);
      }
    }
    _processArguments() {
      const myParseArg = (argument, value, previous) => {
        let parsedValue = value;
        if (value !== null && argument.parseArg) {
          const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
          parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
        }
        return parsedValue;
      };
      this._checkNumberOfArguments();
      const processedArgs = [];
      this.registeredArguments.forEach((declaredArg, index) => {
        let value = declaredArg.defaultValue;
        if (declaredArg.variadic) {
          if (index < this.args.length) {
            value = this.args.slice(index);
            if (declaredArg.parseArg) {
              value = value.reduce((processed, v) => {
                return myParseArg(declaredArg, v, processed);
              }, declaredArg.defaultValue);
            }
          } else if (value === undefined) {
            value = [];
          }
        } else if (index < this.args.length) {
          value = this.args[index];
          if (declaredArg.parseArg) {
            value = myParseArg(declaredArg, value, declaredArg.defaultValue);
          }
        }
        processedArgs[index] = value;
      });
      this.processedArgs = processedArgs;
    }
    _chainOrCall(promise, fn) {
      if (promise?.then && typeof promise.then === "function") {
        return promise.then(() => fn());
      }
      return fn();
    }
    _chainOrCallHooks(promise, event) {
      let result = promise;
      const hooks = [];
      this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
        hookedCommand._lifeCycleHooks[event].forEach((callback) => {
          hooks.push({ hookedCommand, callback });
        });
      });
      if (event === "postAction") {
        hooks.reverse();
      }
      hooks.forEach((hookDetail) => {
        result = this._chainOrCall(result, () => {
          return hookDetail.callback(hookDetail.hookedCommand, this);
        });
      });
      return result;
    }
    _chainOrCallSubCommandHook(promise, subCommand, event) {
      let result = promise;
      if (this._lifeCycleHooks[event] !== undefined) {
        this._lifeCycleHooks[event].forEach((hook) => {
          result = this._chainOrCall(result, () => {
            return hook(this, subCommand);
          });
        });
      }
      return result;
    }
    _parseCommand(operands, unknown) {
      const parsed = this.parseOptions(unknown);
      this._parseOptionsEnv();
      this._parseOptionsImplied();
      operands = operands.concat(parsed.operands);
      unknown = parsed.unknown;
      this.args = operands.concat(unknown);
      if (operands && this._findCommand(operands[0])) {
        return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
      }
      if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
        return this._dispatchHelpCommand(operands[1]);
      }
      if (this._defaultCommandName) {
        this._outputHelpIfRequested(unknown);
        return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
      }
      if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
        this.help({ error: true });
      }
      this._outputHelpIfRequested(parsed.unknown);
      this._checkForMissingMandatoryOptions();
      this._checkForConflictingOptions();
      const checkForUnknownOptions = () => {
        if (parsed.unknown.length > 0) {
          this.unknownOption(parsed.unknown[0]);
        }
      };
      const commandEvent = `command:${this.name()}`;
      if (this._actionHandler) {
        checkForUnknownOptions();
        this._processArguments();
        let promiseChain;
        promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
        promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
        if (this.parent) {
          promiseChain = this._chainOrCall(promiseChain, () => {
            this.parent.emit(commandEvent, operands, unknown);
          });
        }
        promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
        return promiseChain;
      }
      if (this.parent?.listenerCount(commandEvent)) {
        checkForUnknownOptions();
        this._processArguments();
        this.parent.emit(commandEvent, operands, unknown);
      } else if (operands.length) {
        if (this._findCommand("*")) {
          return this._dispatchSubcommand("*", operands, unknown);
        }
        if (this.listenerCount("command:*")) {
          this.emit("command:*", operands, unknown);
        } else if (this.commands.length) {
          this.unknownCommand();
        } else {
          checkForUnknownOptions();
          this._processArguments();
        }
      } else if (this.commands.length) {
        checkForUnknownOptions();
        this.help({ error: true });
      } else {
        checkForUnknownOptions();
        this._processArguments();
      }
    }
    _findCommand(name) {
      if (!name)
        return;
      return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
    }
    _findOption(arg) {
      return this.options.find((option) => option.is(arg));
    }
    _checkForMissingMandatoryOptions() {
      this._getCommandAndAncestors().forEach((cmd) => {
        cmd.options.forEach((anOption) => {
          if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
            cmd.missingMandatoryOptionValue(anOption);
          }
        });
      });
    }
    _checkForConflictingLocalOptions() {
      const definedNonDefaultOptions = this.options.filter((option) => {
        const optionKey = option.attributeName();
        if (this.getOptionValue(optionKey) === undefined) {
          return false;
        }
        return this.getOptionValueSource(optionKey) !== "default";
      });
      const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
      optionsWithConflicting.forEach((option) => {
        const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
        if (conflictingAndDefined) {
          this._conflictingOption(option, conflictingAndDefined);
        }
      });
    }
    _checkForConflictingOptions() {
      this._getCommandAndAncestors().forEach((cmd) => {
        cmd._checkForConflictingLocalOptions();
      });
    }
    parseOptions(args) {
      const operands = [];
      const unknown = [];
      let dest = operands;
      function maybeOption(arg) {
        return arg.length > 1 && arg[0] === "-";
      }
      const negativeNumberArg = (arg) => {
        if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
          return false;
        return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
      };
      let activeVariadicOption = null;
      let activeGroup = null;
      let i = 0;
      while (i < args.length || activeGroup) {
        const arg = activeGroup ?? args[i++];
        activeGroup = null;
        if (arg === "--") {
          if (dest === unknown)
            dest.push(arg);
          dest.push(...args.slice(i));
          break;
        }
        if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
          this.emit(`option:${activeVariadicOption.name()}`, arg);
          continue;
        }
        activeVariadicOption = null;
        if (maybeOption(arg)) {
          const option = this._findOption(arg);
          if (option) {
            if (option.required) {
              const value = args[i++];
              if (value === undefined)
                this.optionMissingArgument(option);
              this.emit(`option:${option.name()}`, value);
            } else if (option.optional) {
              let value = null;
              if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
                value = args[i++];
              }
              this.emit(`option:${option.name()}`, value);
            } else {
              this.emit(`option:${option.name()}`);
            }
            activeVariadicOption = option.variadic ? option : null;
            continue;
          }
        }
        if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
          const option = this._findOption(`-${arg[1]}`);
          if (option) {
            if (option.required || option.optional && this._combineFlagAndOptionalValue) {
              this.emit(`option:${option.name()}`, arg.slice(2));
            } else {
              this.emit(`option:${option.name()}`);
              activeGroup = `-${arg.slice(2)}`;
            }
            continue;
          }
        }
        if (/^--[^=]+=/.test(arg)) {
          const index = arg.indexOf("=");
          const option = this._findOption(arg.slice(0, index));
          if (option && (option.required || option.optional)) {
            this.emit(`option:${option.name()}`, arg.slice(index + 1));
            continue;
          }
        }
        if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
          dest = unknown;
        }
        if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
          if (this._findCommand(arg)) {
            operands.push(arg);
            unknown.push(...args.slice(i));
            break;
          } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
            operands.push(arg, ...args.slice(i));
            break;
          } else if (this._defaultCommandName) {
            unknown.push(arg, ...args.slice(i));
            break;
          }
        }
        if (this._passThroughOptions) {
          dest.push(arg, ...args.slice(i));
          break;
        }
        dest.push(arg);
      }
      return { operands, unknown };
    }
    opts() {
      if (this._storeOptionsAsProperties) {
        const result = {};
        const len = this.options.length;
        for (let i = 0;i < len; i++) {
          const key = this.options[i].attributeName();
          result[key] = key === this._versionOptionName ? this._version : this[key];
        }
        return result;
      }
      return this._optionValues;
    }
    optsWithGlobals() {
      return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
    }
    error(message, errorOptions) {
      this._outputConfiguration.outputError(`${message}
`, this._outputConfiguration.writeErr);
      if (typeof this._showHelpAfterError === "string") {
        this._outputConfiguration.writeErr(`${this._showHelpAfterError}
`);
      } else if (this._showHelpAfterError) {
        this._outputConfiguration.writeErr(`
`);
        this.outputHelp({ error: true });
      }
      const config = errorOptions || {};
      const exitCode = config.exitCode || 1;
      const code = config.code || "commander.error";
      this._exit(exitCode, code, message);
    }
    _parseOptionsEnv() {
      this.options.forEach((option) => {
        if (option.envVar && option.envVar in process2.env) {
          const optionKey = option.attributeName();
          if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
            if (option.required || option.optional) {
              this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
            } else {
              this.emit(`optionEnv:${option.name()}`);
            }
          }
        }
      });
    }
    _parseOptionsImplied() {
      const dualHelper = new DualOptions(this.options);
      const hasCustomOptionValue = (optionKey) => {
        return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
      };
      this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
        Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
          this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
        });
      });
    }
    missingArgument(name) {
      const message = `error: missing required argument '${name}'`;
      this.error(message, { code: "commander.missingArgument" });
    }
    optionMissingArgument(option) {
      const message = `error: option '${option.flags}' argument missing`;
      this.error(message, { code: "commander.optionMissingArgument" });
    }
    missingMandatoryOptionValue(option) {
      const message = `error: required option '${option.flags}' not specified`;
      this.error(message, { code: "commander.missingMandatoryOptionValue" });
    }
    _conflictingOption(option, conflictingOption) {
      const findBestOptionFromValue = (option2) => {
        const optionKey = option2.attributeName();
        const optionValue = this.getOptionValue(optionKey);
        const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
        const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
        if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
          return negativeOption;
        }
        return positiveOption || option2;
      };
      const getErrorMessage = (option2) => {
        const bestOption = findBestOptionFromValue(option2);
        const optionKey = bestOption.attributeName();
        const source = this.getOptionValueSource(optionKey);
        if (source === "env") {
          return `environment variable '${bestOption.envVar}'`;
        }
        return `option '${bestOption.flags}'`;
      };
      const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
      this.error(message, { code: "commander.conflictingOption" });
    }
    unknownOption(flag) {
      if (this._allowUnknownOption)
        return;
      let suggestion = "";
      if (flag.startsWith("--") && this._showSuggestionAfterError) {
        let candidateFlags = [];
        let command = this;
        do {
          const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
          candidateFlags = candidateFlags.concat(moreFlags);
          command = command.parent;
        } while (command && !command._enablePositionalOptions);
        suggestion = suggestSimilar(flag, candidateFlags);
      }
      const message = `error: unknown option '${flag}'${suggestion}`;
      this.error(message, { code: "commander.unknownOption" });
    }
    _excessArguments(receivedArgs) {
      if (this._allowExcessArguments)
        return;
      const expected = this.registeredArguments.length;
      const s = expected === 1 ? "" : "s";
      const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
      const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
      this.error(message, { code: "commander.excessArguments" });
    }
    unknownCommand() {
      const unknownName = this.args[0];
      let suggestion = "";
      if (this._showSuggestionAfterError) {
        const candidateNames = [];
        this.createHelp().visibleCommands(this).forEach((command) => {
          candidateNames.push(command.name());
          if (command.alias())
            candidateNames.push(command.alias());
        });
        suggestion = suggestSimilar(unknownName, candidateNames);
      }
      const message = `error: unknown command '${unknownName}'${suggestion}`;
      this.error(message, { code: "commander.unknownCommand" });
    }
    version(str, flags, description) {
      if (str === undefined)
        return this._version;
      this._version = str;
      flags = flags || "-V, --version";
      description = description || "output the version number";
      const versionOption = this.createOption(flags, description);
      this._versionOptionName = versionOption.attributeName();
      this._registerOption(versionOption);
      this.on("option:" + versionOption.name(), () => {
        this._outputConfiguration.writeOut(`${str}
`);
        this._exit(0, "commander.version", str);
      });
      return this;
    }
    description(str, argsDescription) {
      if (str === undefined && argsDescription === undefined)
        return this._description;
      this._description = str;
      if (argsDescription) {
        this._argsDescription = argsDescription;
      }
      return this;
    }
    summary(str) {
      if (str === undefined)
        return this._summary;
      this._summary = str;
      return this;
    }
    alias(alias) {
      if (alias === undefined)
        return this._aliases[0];
      let command = this;
      if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
        command = this.commands[this.commands.length - 1];
      }
      if (alias === command._name)
        throw new Error("Command alias can't be the same as its name");
      const matchingCommand = this.parent?._findCommand(alias);
      if (matchingCommand) {
        const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
        throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
      }
      command._aliases.push(alias);
      return this;
    }
    aliases(aliases) {
      if (aliases === undefined)
        return this._aliases;
      aliases.forEach((alias) => this.alias(alias));
      return this;
    }
    usage(str) {
      if (str === undefined) {
        if (this._usage)
          return this._usage;
        const args = this.registeredArguments.map((arg) => {
          return humanReadableArgName(arg);
        });
        return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
      }
      this._usage = str;
      return this;
    }
    name(str) {
      if (str === undefined)
        return this._name;
      this._name = str;
      return this;
    }
    helpGroup(heading) {
      if (heading === undefined)
        return this._helpGroupHeading ?? "";
      this._helpGroupHeading = heading;
      return this;
    }
    commandsGroup(heading) {
      if (heading === undefined)
        return this._defaultCommandGroup ?? "";
      this._defaultCommandGroup = heading;
      return this;
    }
    optionsGroup(heading) {
      if (heading === undefined)
        return this._defaultOptionGroup ?? "";
      this._defaultOptionGroup = heading;
      return this;
    }
    _initOptionGroup(option) {
      if (this._defaultOptionGroup && !option.helpGroupHeading)
        option.helpGroup(this._defaultOptionGroup);
    }
    _initCommandGroup(cmd) {
      if (this._defaultCommandGroup && !cmd.helpGroup())
        cmd.helpGroup(this._defaultCommandGroup);
    }
    nameFromFilename(filename) {
      this._name = path.basename(filename, path.extname(filename));
      return this;
    }
    executableDir(path2) {
      if (path2 === undefined)
        return this._executableDir;
      this._executableDir = path2;
      return this;
    }
    helpInformation(contextOptions) {
      const helper = this.createHelp();
      const context = this._getOutputContext(contextOptions);
      helper.prepareContext({
        error: context.error,
        helpWidth: context.helpWidth,
        outputHasColors: context.hasColors
      });
      const text2 = helper.formatHelp(this, helper);
      if (context.hasColors)
        return text2;
      return this._outputConfiguration.stripColor(text2);
    }
    _getOutputContext(contextOptions) {
      contextOptions = contextOptions || {};
      const error = !!contextOptions.error;
      let baseWrite;
      let hasColors;
      let helpWidth;
      if (error) {
        baseWrite = (str) => this._outputConfiguration.writeErr(str);
        hasColors = this._outputConfiguration.getErrHasColors();
        helpWidth = this._outputConfiguration.getErrHelpWidth();
      } else {
        baseWrite = (str) => this._outputConfiguration.writeOut(str);
        hasColors = this._outputConfiguration.getOutHasColors();
        helpWidth = this._outputConfiguration.getOutHelpWidth();
      }
      const write = (str) => {
        if (!hasColors)
          str = this._outputConfiguration.stripColor(str);
        return baseWrite(str);
      };
      return { error, write, hasColors, helpWidth };
    }
    outputHelp(contextOptions) {
      let deprecatedCallback;
      if (typeof contextOptions === "function") {
        deprecatedCallback = contextOptions;
        contextOptions = undefined;
      }
      const outputContext = this._getOutputContext(contextOptions);
      const eventContext = {
        error: outputContext.error,
        write: outputContext.write,
        command: this
      };
      this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
      this.emit("beforeHelp", eventContext);
      let helpInformation = this.helpInformation({ error: outputContext.error });
      if (deprecatedCallback) {
        helpInformation = deprecatedCallback(helpInformation);
        if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
          throw new Error("outputHelp callback must return a string or a Buffer");
        }
      }
      outputContext.write(helpInformation);
      if (this._getHelpOption()?.long) {
        this.emit(this._getHelpOption().long);
      }
      this.emit("afterHelp", eventContext);
      this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
    }
    helpOption(flags, description) {
      if (typeof flags === "boolean") {
        if (flags) {
          if (this._helpOption === null)
            this._helpOption = undefined;
          if (this._defaultOptionGroup) {
            this._initOptionGroup(this._getHelpOption());
          }
        } else {
          this._helpOption = null;
        }
        return this;
      }
      this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
      if (flags || description)
        this._initOptionGroup(this._helpOption);
      return this;
    }
    _getHelpOption() {
      if (this._helpOption === undefined) {
        this.helpOption(undefined, undefined);
      }
      return this._helpOption;
    }
    addHelpOption(option) {
      this._helpOption = option;
      this._initOptionGroup(option);
      return this;
    }
    help(contextOptions) {
      this.outputHelp(contextOptions);
      let exitCode = Number(process2.exitCode ?? 0);
      if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
        exitCode = 1;
      }
      this._exit(exitCode, "commander.help", "(outputHelp)");
    }
    addHelpText(position, text2) {
      const allowedValues = ["beforeAll", "before", "after", "afterAll"];
      if (!allowedValues.includes(position)) {
        throw new Error(`Unexpected value for position to addHelpText.
Expecting one of '${allowedValues.join("', '")}'`);
      }
      const helpEvent = `${position}Help`;
      this.on(helpEvent, (context) => {
        let helpStr;
        if (typeof text2 === "function") {
          helpStr = text2({ error: context.error, command: context.command });
        } else {
          helpStr = text2;
        }
        if (helpStr) {
          context.write(`${helpStr}
`);
        }
      });
      return this;
    }
    _outputHelpIfRequested(args) {
      const helpOption = this._getHelpOption();
      const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
      if (helpRequested) {
        this.outputHelp();
        this._exit(0, "commander.helpDisplayed", "(outputHelp)");
      }
    }
  }
  function incrementNodeInspectorPort(args) {
    return args.map((arg) => {
      if (!arg.startsWith("--inspect")) {
        return arg;
      }
      let debugOption;
      let debugHost = "127.0.0.1";
      let debugPort = "9229";
      let match;
      if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
        debugOption = match[1];
      } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
        debugOption = match[1];
        if (/^\d+$/.test(match[3])) {
          debugPort = match[3];
        } else {
          debugHost = match[3];
        }
      } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
        debugOption = match[1];
        debugHost = match[3];
        debugPort = match[4];
      }
      if (debugOption && debugPort !== "0") {
        return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
      }
      return arg;
    });
  }
  function useColor() {
    if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
      return false;
    if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
      return true;
    return;
  }
  exports.Command = Command;
  exports.useColor = useColor;
});

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/index.js
var require_commander = __commonJS((exports) => {
  var { Argument } = require_argument();
  var { Command } = require_command();
  var { CommanderError, InvalidArgumentError } = require_error();
  var { Help } = require_help();
  var { Option } = require_option();
  exports.program = new Command;
  exports.createCommand = (name) => new Command(name);
  exports.createOption = (flags, description) => new Option(flags, description);
  exports.createArgument = (name, description) => new Argument(name, description);
  exports.Command = Command;
  exports.Option = Option;
  exports.Argument = Argument;
  exports.Help = Help;
  exports.CommanderError = CommanderError;
  exports.InvalidArgumentError = InvalidArgumentError;
  exports.InvalidOptionArgumentError = InvalidArgumentError;
});

// ../../node_modules/.bun/commander@14.0.3/node_modules/commander/esm.mjs
var import__ = __toESM(require_commander(), 1);
var {
  program,
  createCommand,
  createArgument,
  createOption,
  CommanderError,
  InvalidArgumentError,
  InvalidOptionArgumentError,
  Command,
  Argument,
  Option,
  Help
} = import__.default;

// src/utils/version-check.ts
import { existsSync, readFileSync, writeFileSync } from "fs";
import { join } from "path";
import { homedir } from "os";
var CHECK_INTERVAL = 24 * 60 * 60 * 1000;
var REGISTRY_URL = "https://registry.npmjs.org/@botpress/adk-cli";
var CACHE_DIR = join(homedir(), ".adk");
var CACHE_FILE = join(CACHE_DIR, "version-check.json");
function readCache() {
  try {
    if (existsSync(CACHE_FILE)) {
      return JSON.parse(readFileSync(CACHE_FILE, "utf-8"));
    }
  } catch {}
  return null;
}
function writeCache(cache) {
  try {
    const { mkdirSync } = __require("fs");
    if (!existsSync(CACHE_DIR)) {
      mkdirSync(CACHE_DIR, { recursive: true });
    }
    writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2));
  } catch {}
}
async function fetchLatestVersion() {
  try {
    const response = await fetch(REGISTRY_URL, {
      headers: { Accept: "application/json" }
    });
    if (!response.ok) {
      return null;
    }
    const data = await response.json();
    return data["dist-tags"]?.latest || null;
  } catch {
    return null;
  }
}
function compareVersions(current, latest) {
  const cleanCurrent = current.replace(/^v/, "");
  const cleanLatest = latest.replace(/^v/, "");
  const currentParts = cleanCurrent.split(".").map(Number);
  const latestParts = cleanLatest.split(".").map(Number);
  for (let i = 0;i < 3; i++) {
    const curr = currentParts[i] || 0;
    const lat = latestParts[i] || 0;
    if (lat > curr)
      return true;
    if (lat < curr)
      return false;
  }
  return false;
}
function checkForUpdates(currentVersion) {
  (async () => {
    try {
      const cache = readCache();
      const now = Date.now();
      if (cache && now - cache.lastCheck < CHECK_INTERVAL) {
        if (cache.latestVersion && compareVersions(currentVersion, cache.latestVersion)) {
          await showUpdateMessage(currentVersion, cache.latestVersion);
        }
        return;
      }
      const latestVersion = await fetchLatestVersion();
      if (latestVersion) {
        writeCache({
          lastCheck: now,
          latestVersion
        });
        if (compareVersions(currentVersion, latestVersion)) {
          await showUpdateMessage(currentVersion, latestVersion);
        }
      }
    } catch {}
  })();
}
async function showUpdateMessage(current, latest) {
  const frame = await renderToString((ctx) => {
    const theme = getActiveTheme();
    return box(ctx, { border: true, borderStyle: "rounded", borderColor: theme.status.warning, paddingX: 2 }, [
      box(ctx, { flexDirection: "column" }, [
        text(ctx, t`${bold("Update available!")} ${current} \u2192 ${fg(theme.status.success)(latest)}`),
        text(ctx, t`Run ${fg(theme.accent.cyan)("adk self-upgrade")} to update`)
      ])
    ]);
  });
  console.log(`
` + frame + `
`);
}

// src/utils/format-help.ts
function formatHelp(cmd, version) {
  const commands = cmd.commands;
  const theme = getActiveTheme();
  const logoLine1 = source_default.hex(theme.accent.purple)(` ${ADK_LOGO_LINE1}`);
  const logoLine2 = source_default.hex(theme.accent.purple)(` ${ADK_LOGO_LINE2}`);
  const title = source_default.hex(theme.text.primary).bold("Botpress ADK");
  const versionText = source_default.hex(theme.text.dim)(`v${version}`);
  const sections = [];
  sections.push("");
  sections.push(`${logoLine1}  ${title}`);
  sections.push(`${logoLine2}  ${versionText}
`);
  sections.push(source_default.hex(theme.text.primary).bold("Usage"));
  sections.push(`  ${source_default.hex(theme.text.dim)("$")} ${source_default.hex(theme.accent.cyan)("adk")} ${source_default.hex(theme.text.dim)("[command] [options]")}
`);
  const commandMap = new Map;
  for (const c of commands) {
    commandMap.set(c.name(), { name: c.name(), description: c.description(), aliases: c.aliases() });
    for (const sub of c.commands) {
      const fullName = `${c.name()} ${sub.name()}`;
      commandMap.set(fullName, { name: fullName, description: sub.description(), aliases: sub.aliases() });
    }
  }
  const categories = {
    "Getting Started": ["init", "login", "logout", "link"],
    Development: [
      "dev",
      "status",
      "check",
      "project upgrade",
      "build",
      "deploy",
      "chat",
      "run",
      "logs",
      "traces",
      "conversations",
      "workflows",
      "kb sync",
      "assets"
    ],
    Configuration: [
      "config",
      "config:set",
      "config:get",
      "secret",
      "secret:set",
      "secret:delete",
      "profiles",
      "theme",
      "telemetry",
      "models"
    ],
    Testing: ["evals", "evals runs"],
    Dependencies: ["integrations", "plugins"],
    Utilities: ["dashboard", "agents", "ps", "kill", "self-upgrade", "ai-upgrade"]
  };
  const commandHints = {
    link: { flag: "--local", note: "--local creates a local override file instead of modifying agent.json" }
  };
  for (const [category, commandNames] of Object.entries(categories)) {
    const categoryEntries = commandNames.map((n) => commandMap.get(n)).filter(Boolean);
    if (categoryEntries.length === 0)
      continue;
    sections.push(source_default.hex(theme.text.primary).bold(category));
    for (const entry of categoryEntries) {
      let nameDisplay = source_default.hex(theme.accent.cyan)(entry.name);
      let extraLength = 0;
      const hint = commandHints[entry.name];
      if (hint) {
        nameDisplay += " " + source_default.hex(theme.text.dim)(hint.flag);
        extraLength = 1 + hint.flag.length;
      }
      if (entry.aliases.length > 0) {
        nameDisplay += source_default.hex(theme.text.dim)(`, ${entry.aliases.join(", ")}`);
      }
      const actualLength = entry.name.length + extraLength + (entry.aliases.length > 0 ? entry.aliases.join(", ").length + 2 : 0);
      const padding = " ".repeat(Math.max(0, 24 - actualLength));
      const descriptionText = source_default.hex(theme.text.secondary)(entry.description);
      sections.push(`  ${nameDisplay}${padding}  ${descriptionText}`);
      if (hint) {
        sections.push(`  ${" ".repeat(24)}  ${source_default.hex(theme.text.dim)(`\u21B3 ${hint.note}`)}`);
      }
    }
    sections.push("");
  }
  sections.push(source_default.hex(theme.text.primary).bold("Options"));
  const options = [
    { flags: "--version, -V", description: "Show version number" },
    { flags: "--help, -h", description: "Show help" },
    { flags: "--no-cache", description: "Disable caching for integration lookups" }
  ];
  for (const option of options) {
    const flagsDisplay = source_default.hex(theme.accent.yellow)(option.flags);
    const padding = " ".repeat(Math.max(0, 24 - option.flags.length));
    const descriptionText = source_default.hex(theme.text.secondary)(option.description);
    sections.push(`  ${flagsDisplay}${padding}  ${descriptionText}`);
  }
  sections.push("");
  sections.push(source_default.hex(theme.text.dim)("For more information, visit https://botpress.com/docs"));
  return sections.join(`
`);
}
function formatCommandHelp(cmd) {
  const theme = getActiveTheme();
  const sections = [];
  const commandPath = getCommandPath(cmd);
  sections.push("");
  sections.push(source_default.hex(theme.text.primary).bold(cmd.name()));
  sections.push(source_default.hex(theme.text.secondary)(cmd.description()));
  sections.push("");
  sections.push(source_default.hex(theme.text.primary).bold("Usage"));
  const usage = cmd.usage();
  sections.push(`  ${source_default.hex(theme.text.dim)("$")} ${source_default.hex(theme.accent.cyan)("adk")} ${source_default.hex(theme.accent.cyan)(commandPath)} ${source_default.hex(theme.text.dim)(usage)}`);
  sections.push("");
  const subcommands = cmd.commands;
  if (subcommands.length > 0) {
    sections.push(source_default.hex(theme.text.primary).bold("Commands"));
    for (const sub of subcommands) {
      const nameDisplay = source_default.hex(theme.accent.cyan)(`${cmd.name()} ${sub.name()}`);
      const actualLength = cmd.name().length + 1 + sub.name().length;
      const padding = " ".repeat(Math.max(0, 24 - actualLength));
      const descriptionText = source_default.hex(theme.text.secondary)(sub.description());
      sections.push(`  ${nameDisplay}${padding}  ${descriptionText}`);
    }
    sections.push("");
  }
  const options = cmd.options.filter((option) => !option.hidden);
  if (options.length > 0) {
    sections.push(source_default.hex(theme.text.primary).bold("Options"));
    for (const option of options) {
      const flags = option.flags;
      const description = option.description;
      const flagsDisplay = source_default.hex(theme.accent.yellow)(flags);
      const flagsPadded = flagsDisplay.padEnd(30);
      const descriptionText = source_default.hex(theme.text.secondary)(description);
      sections.push(`  ${flagsPadded}  ${descriptionText}`);
    }
    sections.push("");
  }
  return sections.join(`
`);
}
function getCommandPath(cmd) {
  const names = [];
  let current = cmd;
  while (current && current.parent) {
    names.unshift(current.name());
    current = current.parent;
  }
  return names.join(" ") || cmd.name();
}
function formatWelcome(version) {
  const theme = getActiveTheme();
  const logoLine1 = source_default.hex(theme.accent.purple)(` ${ADK_LOGO_LINE1}`);
  const logoLine2 = source_default.hex(theme.accent.purple)(` ${ADK_LOGO_LINE2}`);
  const title = source_default.hex(theme.text.primary).bold("Botpress ADK");
  const versionText = source_default.hex(theme.text.dim)(`v${version}`);
  const sections = [];
  sections.push("");
  sections.push(`${logoLine1}  ${title}`);
  sections.push(`${logoLine2}  ${versionText}
`);
  sections.push(source_default.hex(theme.text.secondary)("Welcome to the Botpress Agent Development Kit!"));
  sections.push(source_default.hex(theme.text.dim)(`Build AI agents with TypeScript and deploy to Botpress Cloud.
`));
  sections.push(source_default.hex(theme.text.primary).bold("Quick Start"));
  const quickStartCommands = [
    {
      command: "adk init",
      description: "Create a new agent project"
    },
    {
      command: "adk login",
      description: "Authenticate with Botpress Cloud"
    },
    {
      command: "adk dev",
      description: "Start development mode (from agent directory)"
    },
    {
      command: "adk help",
      description: "Show all available commands"
    }
  ];
  for (const item of quickStartCommands) {
    const commandDisplay = source_default.hex(theme.accent.cyan)(item.command);
    const padding = " ".repeat(Math.max(0, 24 - item.command.length));
    const descriptionText = source_default.hex(theme.text.secondary)(item.description);
    sections.push(`  ${commandDisplay}${padding}  ${descriptionText}`);
  }
  sections.push("");
  sections.push(source_default.hex(theme.text.dim)("Learn more: https://www.botpress.com/docs/for-developers/adk/overview"));
  sections.push("");
  return sections.join(`
`);
}

// src/utils/string-similarity.ts
function calculateLevenshteinDistance(str1, str2) {
  const len1 = str1.length;
  const len2 = str2.length;
  const matrix = [];
  for (let i = 0;i <= len1; i++) {
    matrix[i] = [i];
  }
  for (let j = 0;j <= len2; j++) {
    matrix[0][j] = j;
  }
  for (let i = 1;i <= len1; i++) {
    for (let j = 1;j <= len2; j++) {
      if (str1[i - 1] === str2[j - 1]) {
        matrix[i][j] = matrix[i - 1][j - 1];
      } else {
        matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + 1);
      }
    }
  }
  return matrix[len1][len2];
}
function calculateSimilarityScore(str1, str2) {
  const len1 = str1.length;
  const len2 = str2.length;
  const maxLen = Math.max(len1, len2);
  const minLen = Math.min(len1, len2);
  if (maxLen === 0)
    return 1;
  const distance = calculateLevenshteinDistance(str1, str2);
  let score = 1 - distance / maxLen;
  const lengthDiff = Math.abs(len1 - len2);
  if (lengthDiff > 2) {
    score *= 0.5;
  } else if (lengthDiff > 1) {
    score *= 0.75;
  }
  if (str1[0] === str2[0]) {
    score *= 1.1;
    const prefixLen = Math.min(3, minLen);
    if (str1.slice(0, prefixLen) === str2.slice(0, prefixLen)) {
      score *= 1.15;
    }
  }
  return Math.min(1, score);
}

// src/utils/command-suggestions.ts
function findSimilarCommands(unknownCommand, allCommands) {
  const commandNames = [];
  for (const cmd of allCommands) {
    const cmdName = cmd.name();
    const aliases = cmd.aliases();
    const mainScore = calculateSimilarityScore(unknownCommand.toLowerCase(), cmdName.toLowerCase());
    commandNames.push({ command: cmd, name: cmdName, score: mainScore });
    for (const alias of aliases) {
      const aliasScore = calculateSimilarityScore(unknownCommand.toLowerCase(), alias.toLowerCase());
      commandNames.push({ command: cmd, name: alias, score: aliasScore });
    }
  }
  commandNames.sort((a, b) => b.score - a.score);
  const filtered = commandNames.filter((item) => {
    if (item.name.toLowerCase() === unknownCommand.toLowerCase()) {
      return false;
    }
    if (item.score < 0.5) {
      return false;
    }
    const lengthDiff = Math.abs(unknownCommand.length - item.name.length);
    if (lengthDiff > 3 && item.score < 0.65) {
      return false;
    }
    return true;
  });
  const seen = new Set;
  const unique = [];
  for (const item of filtered) {
    if (!seen.has(item.command)) {
      seen.add(item.command);
      unique.push(item.command);
      if (unique.length >= 3)
        break;
    }
  }
  return unique;
}
function formatSuggestion(unknownCommand, suggestions) {
  if (suggestions.length === 0) {
    return "";
  }
  if (suggestions.length === 1) {
    return `Did you mean ${suggestions[0].name()}?`;
  }
  const names = suggestions.map((cmd) => cmd.name());
  if (suggestions.length === 2) {
    return `Did you mean ${names[0]} or ${names[1]}?`;
  }
  return `Did you mean ${names.slice(0, -1).join(", ")}, or ${names[names.length - 1]}?`;
}

// src/commands/integrations/index.ts
function registerIntegrationsCommands(program2, runCliCommand) {
  const integrations = program2.command("integrations").description("Manage agent integrations");
  integrations.command("add").description("Add an integration").argument("<name>", "integration name (e.g., slack or slack@1.4.2)").option("--alias <alias>", "use a custom alias").option("--target <env>", "dev or prod (default: dev)").option("--config <kv...>", "configuration value (repeatable: key=value)").option("--format <format>", "output format (text|json, default: text)").action(async (name, options) => {
    try {
      await runCliCommand("integrations:add", async () => {
        const { adkIntegrationsAdd } = await import("./chunk-0vj5ngv1.js");
        await adkIntegrationsAdd(name, options);
      });
    } catch (error) {
      fatalWith("integrations:add", options.format, error);
    }
  });
  integrations.command("remove").description("Remove an integration").argument("<alias>", "integration alias to remove").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("integrations:remove", async () => {
        const { adkIntegrationsRemove } = await import("./chunk-36bn8cqe.js");
        await adkIntegrationsRemove(alias, options);
      });
    } catch (error) {
      fatalWith("integrations:remove", options.format, error);
    }
  });
  integrations.command("upgrade").description("Upgrade an integration").argument("<alias>", "integration alias to upgrade").option("--to <version>", "target version (default: latest)").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("integrations:upgrade", async () => {
        const { adkIntegrationsUpgrade } = await import("./chunk-d6hepd93.js");
        await adkIntegrationsUpgrade(alias, options);
      });
    } catch (error) {
      fatalWith("integrations:upgrade", options.format, error);
    }
  });
  integrations.command("enable").description("Enable an integration").argument("<alias>", "integration alias to enable").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("integrations:enable", async () => {
        const { adkIntegrationsEnable } = await import("./chunk-7grnzkq6.js");
        await adkIntegrationsEnable(alias, options);
      });
    } catch (error) {
      fatalWith("integrations:enable", options.format, error);
    }
  });
  integrations.command("disable").description("Disable an integration").argument("<alias>", "integration alias to disable").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("integrations:disable", async () => {
        const { adkIntegrationsDisable } = await import("./chunk-tnrraq65.js");
        await adkIntegrationsDisable(alias, options);
      });
    } catch (error) {
      fatalWith("integrations:disable", options.format, error);
    }
  });
  integrations.command("configure").description("Configure an integration").argument("<alias>", "integration alias to configure").option("--set <kv...>", "config values (key=value ...)").option("--unset <key...>", "config keys to remove").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("integrations:configure", async () => {
        const { adkIntegrationsConfigure } = await import("./chunk-ygvxqc3w.js");
        await adkIntegrationsConfigure(alias, options);
      });
    } catch (error) {
      fatalWith("integrations:configure", options.format, error);
    }
  });
  integrations.command("info").description("Show information about an integration from the registry").argument("<name>", "integration name (e.g., slack or slack@1.4.2)").option("--format <format>", "output format (text|json)").action(async (name, options) => {
    try {
      await runCliCommand("integrations:info", async () => {
        const { adkIntegrationsInfo } = await import("./chunk-nap3ybfa.js");
        await adkIntegrationsInfo(name, options);
      });
    } catch (error) {
      fatalWith("integrations:info", options.format, error);
    }
  });
  integrations.command("search").description("Search the integration registry").argument("[query]", "search query (optional when --interface is provided)").option("--interface <name>", "list integrations that implement this interface").option("--format <format>", "output format (text|json)").action(async (query, options) => {
    try {
      await runCliCommand("integrations:search", async () => {
        const { adkIntegrationsSearch } = await import("./chunk-s89fmq4d.js");
        await adkIntegrationsSearch(query ?? "", options);
      });
    } catch (error) {
      fatalWith("integrations:search", options.format, error);
    }
  });
  integrations.command("list").description("List installed integrations").option("--target <env>", "dev or prod (default: dev)").option("--verbose", "show config values").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("integrations:list", async () => {
        const { adkIntegrationsList } = await import("./chunk-84shyvse.js");
        await adkIntegrationsList(options);
      });
    } catch (error) {
      fatalWith("integrations:list", options.format, error);
    }
  });
  integrations.command("status").description("Show each integration\u2019s capability state (available/unconfigured/disabled/\u2026) with remediation").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("integrations:status", async () => {
        const { adkIntegrationsStatus } = await import("./chunk-vkn1nntc.js");
        await adkIntegrationsStatus(options);
      });
    } catch (error) {
      fatalWith("integrations:status", options.format, error);
    }
  });
  integrations.command("copy").description("Copy integration state from one env to another").requiredOption("--from <env>", "source env (dev or prod)").requiredOption("--to <env>", "target env (dev or prod)").option("--yes", "allow destructive changes without confirmation").option("--dry-run", "show what would change without writing").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("integrations:copy", async () => {
        const { adkIntegrationsCopy } = await import("./chunk-9r079byr.js");
        await adkIntegrationsCopy(options);
      });
    } catch (error) {
      fatalWith("integrations:copy", options.format, error);
    }
  });
  integrations.command("diff").description("Show dependency state differences").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("integrations:diff", async () => {
        const { adkIntegrationsDiff } = await import("./chunk-p8q8bnpw.js");
        await adkIntegrationsDiff(options);
      });
    } catch (error) {
      fatalWith("integrations:diff", options.format, error);
    }
  });
}

// src/commands/plugins/index.ts
function registerPluginsCommands(program2, runCliCommand) {
  const plugins = program2.command("plugins").description("Manage agent plugins");
  plugins.command("add").description("Add a plugin").argument("<name>", "plugin name (e.g., support-bot or support-bot@0.3.0)").option("--alias <alias>", "use a custom alias").option("--dep <kv...>", "wire interface dependency (repeatable: iface=integration-alias)").option("--target <env>", "dev or prod (default: dev)").option("--config <kv...>", "configuration value (repeatable: key=value)").option("--format <format>", "output format (text|json, default: text)").action(async (name, options) => {
    try {
      await runCliCommand("plugins:add", async () => {
        const { adkPluginsAdd } = await import("./chunk-2fdzrh7w.js");
        await adkPluginsAdd(name, options);
      });
    } catch (error) {
      fatalWith("plugins:add", options.format, error);
    }
  });
  plugins.command("remove").description("Remove a plugin").argument("<alias>", "plugin alias to remove").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("plugins:remove", async () => {
        const { adkPluginsRemove } = await import("./chunk-pwgknhrk.js");
        await adkPluginsRemove(alias, options);
      });
    } catch (error) {
      fatalWith("plugins:remove", options.format, error);
    }
  });
  plugins.command("upgrade").description("Upgrade a plugin").argument("<alias>", "plugin alias to upgrade").option("--to <version>", "target version (default: latest)").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("plugins:upgrade", async () => {
        const { adkPluginsUpgrade } = await import("./chunk-xem9e9wv.js");
        await adkPluginsUpgrade(alias, options);
      });
    } catch (error) {
      fatalWith("plugins:upgrade", options.format, error);
    }
  });
  plugins.command("enable").description("Enable a plugin").argument("<alias>", "plugin alias to enable").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("plugins:enable", async () => {
        const { adkPluginsEnable } = await import("./chunk-ypava17b.js");
        await adkPluginsEnable(alias, options);
      });
    } catch (error) {
      fatalWith("plugins:enable", options.format, error);
    }
  });
  plugins.command("disable").description("Disable a plugin").argument("<alias>", "plugin alias to disable").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("plugins:disable", async () => {
        const { adkPluginsDisable } = await import("./chunk-65staq0m.js");
        await adkPluginsDisable(alias, options);
      });
    } catch (error) {
      fatalWith("plugins:disable", options.format, error);
    }
  });
  plugins.command("configure").description("Configure a plugin").argument("<alias>", "plugin alias to configure").option("--set <kv...>", "config values (key=value ...)").option("--unset <key...>", "config keys to remove").option("--map <kv...>", "wire interface deps (iface=alias ...)").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (alias, options) => {
    try {
      await runCliCommand("plugins:configure", async () => {
        const { adkPluginsConfigure } = await import("./chunk-brg5tmg7.js");
        await adkPluginsConfigure(alias, options);
      });
    } catch (error) {
      fatalWith("plugins:configure", options.format, error);
    }
  });
  plugins.command("info").description("Show information about a plugin from the registry").argument("<name>", "plugin name (e.g., support-bot or support-bot@0.3.0)").option("--format <format>", "output format (text|json)").action(async (name, options) => {
    try {
      await runCliCommand("plugins:info", async () => {
        const { adkPluginsInfo } = await import("./chunk-2rd4jv9w.js");
        await adkPluginsInfo(name, options);
      });
    } catch (error) {
      fatalWith("plugins:info", options.format, error);
    }
  });
  plugins.command("search").description("Search the plugin registry").argument("<query>", "search query").option("--format <format>", "output format (text|json)").action(async (query, options) => {
    try {
      await runCliCommand("plugins:search", async () => {
        const { adkPluginsSearch } = await import("./chunk-24qsjhax.js");
        await adkPluginsSearch(query, options);
      });
    } catch (error) {
      fatalWith("plugins:search", options.format, error);
    }
  });
  plugins.command("list").description("List installed plugins").option("--target <env>", "dev or prod (default: dev)").option("--verbose", "show config values").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("plugins:list", async () => {
        const { adkPluginsList } = await import("./chunk-s8wcrvzk.js");
        await adkPluginsList(options);
      });
    } catch (error) {
      fatalWith("plugins:list", options.format, error);
    }
  });
  plugins.command("status").description("Show each plugin\u2019s capability state (available/unconfigured/unresolved/\u2026) with remediation").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("plugins:status", async () => {
        const { adkPluginsStatus } = await import("./chunk-cn85pd9m.js");
        await adkPluginsStatus(options);
      });
    } catch (error) {
      fatalWith("plugins:status", options.format, error);
    }
  });
  plugins.command("copy").description("Copy plugin state from one env to another").requiredOption("--from <env>", "source env (dev or prod)").requiredOption("--to <env>", "target env (dev or prod)").option("--yes", "allow destructive changes without confirmation").option("--dry-run", "show what would change without writing").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("plugins:copy", async () => {
        const { adkPluginsCopy } = await import("./chunk-pgphsmc4.js");
        await adkPluginsCopy(options);
      });
    } catch (error) {
      fatalWith("plugins:copy", options.format, error);
    }
  });
  plugins.command("diff").description("Show dependency state differences").option("--target <env>", "dev or prod (default: dev)").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("plugins:diff", async () => {
        const { adkPluginsDiff } = await import("./chunk-ebvsk0na.js");
        await adkPluginsDiff(options);
      });
    } catch (error) {
      fatalWith("plugins:diff", options.format, error);
    }
  });
}

// src/commands/interfaces/index.ts
function registerInterfacesCommands(program2, runCliCommand) {
  const interfaces = program2.command("interfaces").description("Inspect built-in agent interfaces");
  interfaces.command("list").description("List built-in interfaces").option("--format <format>", "output format (text|json)").action(async (options) => {
    try {
      await runCliCommand("interfaces:list", async () => {
        const { adkInterfacesList } = await import("./chunk-9hf2717g.js");
        await adkInterfacesList(options);
      }, false);
    } catch (error) {
      fatalWith("interfaces:list", options.format, error);
    }
  });
  interfaces.command("info").description("Show information about a built-in interface").argument("<name>", "interface name (e.g., llm)").option("--format <format>", "output format (text|json)").action(async (name, options) => {
    try {
      await runCliCommand("interfaces:info", async () => {
        const { adkInterfacesInfo } = await import("./chunk-31g1n70d.js");
        await adkInterfacesInfo(name, options);
      }, false);
    } catch (error) {
      fatalWith("interfaces:info", options.format, error);
    }
  });
}

// src/commands/dependencies/index.ts
function registerDependenciesCommands(program2, runCliCommand) {
  const dependencies = program2.command("dependencies").description("Manage dependency snapshots");
  dependencies.command("export").description("Export integration and plugin state to a JSON snapshot").argument("[output]", "snapshot path (default: <project-name>.dependencies.<target>.json)").option("--target <env>", "dev or prod (default: dev)").option("--no-config", "omit integration and plugin configuration").option("--format <format>", "output format (text|json)").action(async (output, options) => {
    try {
      await runCliCommand("dependencies:export", async () => {
        const { adkDependenciesExport } = await import("./chunk-391fbq02.js");
        await adkDependenciesExport(output, options);
      });
    } catch (error) {
      fatalWith("dependencies:export", options.format, error);
    }
  });
  dependencies.command("import").description("Import a dependency JSON snapshot into an environment").argument("<file>", "snapshot path created by adk dependencies export").option("--target <env>", "dev or prod (default: snapshot env)").option("--dry-run", "show what would change without writing").option("--yes", "allow prod or destructive changes without confirmation").option("--format <format>", "output format (text|json)").action(async (file, options) => {
    try {
      await runCliCommand("dependencies:import", async () => {
        const { adkDependenciesImport } = await import("./chunk-6w08067b.js");
        await adkDependenciesImport(file, options);
      });
    } catch (error) {
      fatalWith("dependencies:import", options.format, error);
    }
  });
}

// src/utils/command-scope.ts
var COMMAND_SCOPES = {
  adk: "global",
  help: "global",
  home: "global",
  version: "global",
  init: "global",
  import: "global",
  login: "global",
  logout: "global",
  profiles: "global",
  "profiles:list": "global",
  "profiles:set": "global",
  "self-upgrade": "global",
  "self-update": "global",
  telemetry: "global",
  theme: "global",
  dashboard: "global",
  ps: "global",
  kill: "global",
  flags: "global",
  interfaces: "global",
  "interfaces:list": "global",
  "interfaces:info": "global",
  integrations: "global",
  "integrations:info": "global",
  "integrations:search": "global",
  plugins: "global",
  "plugins:info": "global",
  "plugins:search": "global",
  dependencies: "project",
  "dependencies:export": "project",
  "dependencies:import": "project",
  export: "project",
  dev: "project",
  status: "project",
  build: "project",
  check: "project",
  "project:upgrade": "project-diagnostic",
  deploy: "project",
  link: "project",
  "agent0:upgrade": "project",
  "ai-upgrade": "project",
  logs: "project",
  traces: "project",
  conversations: "project",
  "conversations:list": "project",
  "conversations:show": "project",
  chat: "project",
  run: "project",
  workflows: "project",
  "workflows:list": "project",
  "workflows:inspect": "project",
  "workflows:run": "project",
  "workflows:runs": "project",
  config: "project",
  "config:get": "project",
  "config:set": "project",
  secret: "project",
  "secret:set": "project",
  "secret:delete": "project",
  models: "project",
  evals: "project",
  "evals:runs": "project",
  "kb:sync": "project",
  "integrations:add": "project",
  "integrations:remove": "project",
  "integrations:upgrade": "project",
  "integrations:enable": "project",
  "integrations:disable": "project",
  "integrations:configure": "project",
  "integrations:list": "project",
  "integrations:status": "project",
  "integrations:copy": "project",
  "integrations:diff": "project",
  "plugins:add": "project",
  "plugins:remove": "project",
  "plugins:upgrade": "project",
  "plugins:enable": "project",
  "plugins:disable": "project",
  "plugins:configure": "project",
  "plugins:list": "project",
  "plugins:status": "project",
  "plugins:copy": "project",
  "plugins:diff": "project",
  assets: "project",
  "assets:sync": "project",
  "assets:list": "project",
  "assets:status": "project",
  "assets:pull": "project",
  fleet: "project",
  "fleet:upload": "project",
  "fleet:remove": "project"
};

class CommandScopeNotConfiguredError extends Error {
  commandKey;
  constructor(commandKey) {
    super(`No command scope configured for '${commandKey}'. Add it to COMMAND_SCOPES.`);
    this.commandKey = commandKey;
    this.name = "CommandScopeNotConfiguredError";
  }
}
function normalizeCommandKey(commandKey) {
  return commandKey.trim().replace(/\s+/g, ":");
}
function getCommandScope(commandKey) {
  const normalized = normalizeCommandKey(commandKey);
  const scope = COMMAND_SCOPES[normalized];
  if (!scope) {
    throw new CommandScopeNotConfiguredError(normalized);
  }
  return scope;
}
function shouldRunRuntimePreflight(scope) {
  return scope === "project";
}
async function preflightRuntimeForCommand(commandKey, startPath = process.cwd(), deps = {}) {
  const scope = getCommandScope(commandKey);
  if (!shouldRunRuntimePreflight(scope)) {
    return { scope };
  }
  const resolveRoot = deps.findAgentRootOrFail ?? findAgentRootOrFail;
  const checkRuntime = deps.preflightRuntimeVersionCheck ?? preflightRuntimeVersionCheck;
  const agentRoot = await resolveRoot(startPath);
  const report = checkRuntime(agentRoot);
  return { scope, agentRoot, report };
}

// src/cli.ts
var logger = createCliLogger();
var internalUiServerArgIndex = process.argv.indexOf(INTERNAL_UI_SERVER_ARG);
if (internalUiServerArgIndex !== -1) {
  const { runUiServerEntry } = await import("./chunk-s5hr8v9q.js");
  await runUiServerEntry(process.argv.slice(internalUiServerArgIndex + 1));
  process.exit(0);
}
var _telemetry;
async function getTelemetry() {
  _telemetry ??= await import("./chunk-vk04e24d.js");
  return _telemetry.default;
}
var _installBpCLI;
async function ensureBpCLI() {
  _installBpCLI ??= await import("./chunk-55yvh1kg.js");
  await _installBpCLI.installBpCLI();
}
var handlingFatalError = false;
function installGlobalErrorHandlers() {
  const capture = async (error, fatal) => {
    try {
      const telemetry = await getTelemetry();
      telemetry.captureException(error, { source: "cli", fatal });
      if (fatal) {
        await telemetry.shutdown();
      }
    } catch {}
  };
  process.on("uncaughtException", (error) => {
    if (handlingFatalError)
      return;
    handlingFatalError = true;
    logger.error(error instanceof Error ? error.stack ?? error.message : String(error));
    capture(error, true).finally(() => process.exit(1));
  });
  process.on("unhandledRejection", (reason) => {
    logger.warn(`Unhandled promise rejection: ${reason instanceof Error ? reason.message : String(reason)}`);
    capture(reason, false);
  });
}
installGlobalErrorHandlers();
async function trackCmd(commandName, handler, requiresAuth = true) {
  const startTime = Date.now();
  let success = false;
  const telemetry = await getTelemetry();
  telemetry.flushSpooledExceptions();
  try {
    if (requiresAuth) {
      import("./chunk-skj2g2ed.js").then(({ identifyUser }) => identifyUser(process.cwd())).catch(() => {});
    }
    telemetry.track("command_run", { command: commandName, started: true });
    const result = await handler();
    success = true;
    return result;
  } catch (error) {
    success = false;
    telemetry.track("command_run", {
      command: commandName,
      success: false,
      duration: Date.now() - startTime,
      error: sanitizeErrorMessage(error instanceof Error ? error.message : String(error))
    });
    const errCtx = error instanceof Error ? error : undefined;
    telemetry.captureException(error, {
      command: commandName,
      source: "cli",
      ...errCtx?.botId !== undefined ? { bot_id: errCtx.botId } : {},
      ...errCtx?.stage !== undefined ? { stage: errCtx.stage } : {},
      ...errCtx?.detail !== undefined ? { error_detail: errCtx.detail } : {}
    });
    throw error;
  } finally {
    if (success) {
      telemetry.track("command_run", {
        command: commandName,
        success: true,
        duration: Date.now() - startTime
      });
    }
    await telemetry.shutdown();
  }
}
async function runCliCommand(commandName, handler, requiresAuth = true) {
  await preflightRuntimeForCommand(commandName);
  return trackCmd(commandName, handler, requiresAuth);
}
function ensureDevNodeEnv() {
  process.env.NODE_ENV = "production";
}
if (!checkNodeVersion(true)) {
  checkNodeVersion(false);
  process.exit(1);
}
program.name("adk").description("Botpress Agent Development Kit (ADK) - CLI for building AI agents").version(CLI_VERSION).option("--no-cache", "Disable caching for integration lookups").option("--profile <profile>", "Credentials profile to use for this command").configureHelp({
  formatHelp: () => formatHelp(program, CLI_VERSION)
});
program.hook("preAction", async (thisCommand, actionCommand) => {
  await ensureBpCLI();
  const opts = thisCommand.optsWithGlobals();
  if (opts.profile) {
    const { auth, AdkError } = await import("./chunk-ka3e16hs.js");
    const commandName = actionCommand.name();
    if (commandName === "logout") {
      return;
    }
    if (commandName !== "login") {
      const profiles = await auth.listProfiles();
      const exists = profiles.some((p) => p.name === opts.profile);
      if (!exists) {
        const available = profiles.map((p) => p.name);
        const hint = available.length > 0 ? `Available profiles: ${available.join(", ")}` : "No profiles found. Run 'adk login' to create one.";
        logger.fatal(new AdkError({
          code: "PROFILE_NOT_FOUND",
          message: `Profile '${opts.profile}' not found. ${hint}`,
          expected: true
        }));
      }
    }
    auth.setProfileOverride(opts.profile);
  }
});
program.command("init").description("Initialize a new ADK agent project").argument("[name]", "name of the agent project (required with --yes --format json)").option("-t, --template <template>", "template to use (default: blank, required with --yes --format json)").option("-y, --yes", "skip prompts and use sensible defaults").option("--defaults", "alias for --yes").option("--skip-link", "skip the interactive linking step (required with --yes --format json)").option("--list-templates", "list available templates and exit").option("--format <format>", "output format (json)").action(async (name, options) => {
  try {
    await runCliCommand("init", async () => {
      const { adkInit } = await import("./chunk-dphnems3.js");
      await adkInit(name, options);
    }, false);
  } catch (error) {
    fatalWith("init", options.format, error);
  }
});
program.command("export").description("Export the current ADK project as a portable archive").argument("[output]", "archive path (default: <project-name>.adk)").option("--no-config", "omit integration and plugin configuration from dependency snapshots").option("--format <format>", "output format (json)").action(async (output, options) => {
  try {
    await runCliCommand("export", async () => {
      const { adkExport } = await import("./chunk-hyhtg415.js");
      await adkExport(output, options);
    });
  } catch (error) {
    fatalWith("export", options.format, error);
  }
});
program.command("import").description("Import an ADK project archive and link new bots").argument("<archive>", "archive path created by adk export").argument("[directory]", "destination directory (default: archive project name)").option("--workspace <workspaceId>", "destination workspace ID").option("--bot <botId>", "destination production bot ID").option("--dev <devBotId>", "destination dev bot ID (optional)").option("--api-url <apiUrl>", "Botpress API URL (e.g., https://api.botpress.cloud)").option("-f, --force", "skip confirmation prompts").option("--package-manager <packageManager>", "package manager to install dependencies (bun|pnpm|yarn|npm)").option("--format <format>", "output format (json)").action(async (archive, directory, options) => {
  try {
    await runCliCommand("import", async () => {
      const { adkImport } = await import("./chunk-3nq8semd.js");
      await adkImport(archive, directory, options);
    });
  } catch (error) {
    fatalWith("import", options.format, error);
  }
});
program.command("dev").description("Start development mode with hot reloading").option("-p, --port <port>", "port for development server", "3000").option("--port-console <port>", "port for console server", "3001").option("--otlp", "enable OTLP export to external collector (default port 4318)").option("--port-otlp <port>", "port for OTLP collector endpoint (Jaeger, otel-tui, etc.)").option("-v, --verbose", "show additional details (project path, log file)").option("--non-interactive", "emit structured NDJSON events to stdout instead of the status panel").option("--no-watch", "disable file watching and hot reload").addOption(new Option("--fleet").hideHelp()).addHelpText("after", `
Examples:
  $ adk dev                              # static status panel (DevConsole carries the UI)
  $ adk dev --non-interactive            # NDJSON events to stdout
  $ adk dev --non-interactive --port 4000 --port-console 4001

adk dev runs the agent locally; the rich dev UI (conversations, traces,
searchable log history, integrations) lives in the web DevConsole. A real TTY
gets a status panel with a rolling tail of recent activity; CI / pipes /
--non-interactive get the NDJSON event stream.

Discovering the running DevConsole from a script:
  - Read ~/.adk/console.port (atomic write \u2014 safe to read mid-startup once present)
  - Or run: adk dashboard --no-browser --format json
  - Or run: adk ps --format json

In --non-interactive mode every stdout line is a JSON log record:
{ ts, level, tag, event, message, ... }. tag is 'dev' for the session's own
records and the in-process server subsystem (e.g. 'cognitive-proxy', 'timing')
for the rest \u2014 all share the one stream. The event:'ready' record includes
serverPort, botPort, agentPath, healthUrl, and botUrl \u2014 agents shouldn't need to
parse log lines to find any of these. Fatal startup errors are records with
level:'error' and fatal:true.
`).action(async (options) => {
  checkForUpdates(CLI_VERSION);
  try {
    await runCliCommand("dev", async () => {
      ensureDevNodeEnv();
      const { adkDev } = await import("./chunk-e0a9ej4b.js");
      await adkDev(options.port, {
        ui: !options.nonInteractive,
        adkDevConsolePortStr: options.portConsole,
        otlp: options.otlp,
        portOtlp: options.portOtlp,
        verbose: options.verbose,
        nonInteractive: options.nonInteractive,
        watch: options.watch,
        fleet: options.fleet
      });
    });
  } catch (error) {
    logger.fatal(error);
  }
});
program.command("status").description("Show project status, integrations, and local server state").option("--format <format>", "output format (json)").addOption(new Option("--offline").hideHelp()).addHelpText("after", `
Examples:
  $ adk status
  $ adk status --format json
`).action(async (options) => {
  try {
    await runCliCommand("status", async () => {
      const { adkStatus } = await import("./chunk-b7axc645.js");
      await adkStatus({
        format: options.format,
        noCache: program.opts().noCache,
        offline: options.offline
      });
    }, false);
  } catch (error) {
    fatalWith("status", options.format, error);
  }
});
program.command("build").description("Build the agent for production").option("--format <format>", "output format (json)").action(async (options) => {
  checkForUpdates(CLI_VERSION);
  try {
    await runCliCommand("build", async () => {
      const { adkBuild } = await import("./chunk-nwzh5t37.js");
      await adkBuild({ format: options.format });
    });
  } catch (error) {
    fatalWith("build", options.format, error);
  }
});
program.command("check").description("Validate project structure, config, and primitives (without login required)").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("check", async () => {
      const { adkCheck } = await import("./chunk-ekmb1wzh.js");
      await adkCheck({ format: options.format });
    }, false);
  } catch (error) {
    fatalWith("check", options.format, error);
  }
});
var projectCommand = program.command("project").description("Inspect and upgrade the current ADK project");
projectCommand.command("upgrade").description("Apply ADK project compatibility updates").option("--dry-run", "review required project updates without applying them").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("project:upgrade", async () => {
      const { adkProjectUpgrade } = await import("./chunk-taqhk06x.js");
      await adkProjectUpgrade({ dryRun: options.dryRun, format: options.format });
    }, false);
  } catch (error) {
    fatalWith("project:upgrade", options.format, error);
  }
});
program.command("deploy").description("Deploy the agent to Botpress").option("-e, --env <environment>", "deployment environment", "production").option("-y, --yes", "auto-approve preflight changes without prompting").option("--confirm-storage-changes", "confirm destructive storage changes (table/KB/asset deletions)").option("--dry-run", "compute deploy plan without applying changes").option("--allow-unconfigured", "deploy even if enabled dependencies are unconfigured/unresolved (ships them inert)").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("deploy", async () => {
      const { adkDeploy } = await import("./chunk-cjmk2xvw.js");
      await adkDeploy(options.env, {
        autoApprove: options.yes,
        confirmStorageChanges: options.confirmStorageChanges,
        dryRun: options.dryRun,
        allowUnconfigured: options.allowUnconfigured,
        format: options.format
      });
    });
  } catch (error) {
    fatalWith("deploy", options.format, error);
  }
});
program.command("login").description("Authenticate with your Botpress account").option("--token <token>", "Botpress API token").option("--profile <profile>", "profile name to save credentials under").option("--api-url <url>", "Botpress API URL", "https://api.botpress.cloud").action(async (options) => {
  try {
    const resolvedProfile = options.profile || program.opts().profile;
    await runCliCommand("login", async () => {
      const { adkLogin } = await import("./chunk-h502aj93.js");
      await adkLogin({ ...options, profile: resolvedProfile });
    }, false);
  } catch (error) {
    logger.fatal(error);
  }
});
program.command("logout").description("Remove ADK credentials for the current or named profile").option("--profile <profile>", "profile name to remove").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    const resolvedProfile = options.profile || program.opts().profile;
    await runCliCommand("logout", async () => {
      const { adkLogout } = await import("./chunk-4a16dzz9.js");
      await adkLogout({ profile: resolvedProfile, format: options.format });
    }, false);
  } catch (error) {
    fatalWith("logout", options.format, error);
  }
});
var profiles = program.command("profiles").description("Manage authentication profiles");
profiles.command("list").description("List all configured profiles").action(async () => {
  try {
    await runCliCommand("profiles:list", async () => {
      const { adkProfilesList } = await import("./chunk-vyqx7ht6.js");
      await adkProfilesList();
    }, false);
  } catch (error) {
    logger.fatal(error);
  }
});
profiles.command("set").description("Switch to a different profile").argument("[profile]", "profile name to switch to").action(async (profile) => {
  try {
    await runCliCommand("profiles:set", async () => {
      const { adkProfilesSet } = await import("./chunk-vyqx7ht6.js");
      await adkProfilesSet(profile);
    }, false);
  } catch (error) {
    logger.fatal(error);
  }
});
registerDependenciesCommands(program, runCliCommand);
registerIntegrationsCommands(program, runCliCommand);
registerPluginsCommands(program, runCliCommand);
registerInterfacesCommands(program, runCliCommand);
program.command("self-upgrade").alias("self-update").description("Upgrade ADK CLI to the latest version (or a specific tag/version)").argument("[tag-or-version]", "Tag (beta, next) or version (1.13.0) to install").action(async (tagOrVersion) => {
  try {
    await runCliCommand("self-upgrade", async () => {
      const { adkSelfUpgrade } = await import("./chunk-acb1abp2.js");
      await adkSelfUpgrade(CLI_VERSION, tagOrVersion);
    }, false);
  } catch (error) {
    logger.fatal(error);
  }
});
var agent0Command = program.command("agent0").description("Manage Agent(0)");
agent0Command.command("upgrade").description("Create or update the project Agent(0) capability bundle").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("agent0:upgrade", async () => {
      const { adkAgent0Upgrade } = await import("./chunk-0ddswn0s.js");
      await adkAgent0Upgrade(options);
    }, false);
  } catch (error) {
    createCliLogger({ format: options.format }).fatal(error);
  }
});
program.command("ai-upgrade").description("Update ADK skills and slash commands for external coding agents").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("ai-upgrade", async () => {
      const { adkUpdate } = await import("./chunk-0ddswn0s.js");
      await adkUpdate(options);
    }, false);
  } catch (error) {
    fatalWith("ai-upgrade", options.format, error);
  }
});
program.command("telemetry").description("Manage telemetry preferences").option("--status", "show telemetry status").option("--enable", "enable telemetry").option("--disable", "disable telemetry").action(async (options) => {
  try {
    const { adkTelemetry } = await import("./chunk-mhepbw69.js");
    await adkTelemetry(options);
  } catch (error) {
    logger.fatal(error);
  }
});
program.command("theme").description("Manage CLI theme preferences").option("--set <theme>", "set theme (dark, light, or system)").action(async (options) => {
  try {
    const { adkTheme } = await import("./chunk-d7sywxs3.js");
    await adkTheme(options);
  } catch (error) {
    logger.fatal(error);
  }
});
program.command("dashboard").description("Open the DevConsole dashboard, or print its address for scripting").option("--port-console <port>", "starting port for the console server", "3001").option("--no-browser", "do not open the dashboard in a browser").option("--format <format>", "output format (json) \u2014 emits {port, url, wasSpawned}").addHelpText("after", `
Examples:
  $ adk dashboard                                # open in browser
  $ adk dashboard --no-browser                   # ensure singleton is running, print URL
  $ adk dashboard --no-browser --format json     # script-friendly: {"port":3001,"url":"http://localhost:3001",...}

The DevConsole port is also persisted to ~/.adk/console.port for any tool
that needs to discover it without invoking adk.
`).action(async (options) => {
  try {
    await runCliCommand("dashboard", async () => {
      const { adkDashboard } = await import("./chunk-6fb6dkp1.js");
      await adkDashboard({
        portConsole: options.portConsole,
        openBrowser: options.browser !== false,
        format: options.format
      });
    }, false);
  } catch (error) {
    fatalWith("dashboard", options.format, error);
  }
});
program.command("ps").description("List running ADK dev processes (DevConsole + connected agents)").option("--format <format>", "output format (json)").option("--watch [seconds]", "refresh the display every N seconds (default 2)", false).option("--cloud", "include cloud prod selections in the listing").option("--wide", "show all columns (runtime, both PIDs, path)").addHelpText("after", `
Examples:
  $ adk ps                                       # compact column listing (one-shot)
  $ adk ps --wide                                # all columns: runtime, both PIDs, path
  $ adk ps --cloud                               # include cloud prod selections
  $ adk ps --watch                               # refresh every 2 seconds
  $ adk ps --watch 5                             # refresh every 5 seconds
  $ adk ps --format json                         # JSON payload (one-shot only)

Reads ~/.adk/console.port to find the running DevConsole. Exits with a
non-zero status if no DevConsole is running \u2014 start one with \`adk dev\`
or \`adk dashboard\`.

Note: --watch cannot be used with --format json.
`).action(async (options) => {
  try {
    await runCliCommand("ps", async () => {
      const { adkPs } = await import("./chunk-xwab2nyf.js");
      let watchValue = false;
      if (options.watch === true) {
        watchValue = 2;
      } else if (typeof options.watch === "string") {
        const parsed = parseInt(options.watch, 10);
        watchValue = isNaN(parsed) ? 2 : parsed;
      }
      await adkPs({
        format: options.format,
        watch: watchValue,
        cloud: options.cloud,
        wide: options.wide
      });
    }, false);
  } catch (error) {
    fatalWith("ps", options.format, error);
  }
});
program.command("kill").description("Stop running ADK dev agents (and optionally the DevConsole)").argument("[targets...]", "agent path(s), name(s), or path fragment(s) to stop").option("--all", "stop all running local agents, then shut down the DevConsole").option("--current", "stop the agent in the current directory").option("--pid <pid...>", "stop agent(s) matching the given ADK process PID(s)", (v, a) => {
  const n = parseInt(v, 10);
  return isNaN(n) ? a : [...a, n];
}, []).option("-f, --force", "force kill (SIGKILL) if graceful shutdown fails and adkPid is available").option("--dry-run", "show what would be killed without sending any signals").option("--format <format>", "output format (json)").addHelpText("after", `
Examples:
  $ adk kill --current                           # stop the agent in the current directory
  $ adk kill my-agent                            # stop by name or path fragment
  $ adk kill /home/user/projects/my-agent        # stop by exact path
  $ adk kill --all                               # stop all agents and the DevConsole
  $ adk kill --all --dry-run                     # preview what would be stopped
  $ adk kill --pid 12345                         # stop agent with adkPid 12345
  $ adk kill --format json --all                 # JSON output

Reads ~/.adk/console.port to find the running DevConsole. Exits with a
non-zero status if no DevConsole is running \u2014 start one with \`adk dev\`
or \`adk dashboard\`.

Note: --all stops all local agents first, then requests DevConsole shutdown.
The DevConsole cannot be targeted directly \u2014 use --all to stop everything.
`).action(async (targets, options) => {
  try {
    await runCliCommand("kill", async () => {
      const { adkKill } = await import("./chunk-qeq7gc5y.js");
      await adkKill(targets, {
        all: options.all,
        current: options.current,
        pid: options.pid,
        force: options.force,
        dryRun: options.dryRun,
        format: options.format
      });
    }, false);
  } catch (error) {
    fatalWith("kill", options.format, error);
  }
});
program.command("link").description("Link local agent to workspace and bot").option("--workspace <workspaceId>", "workspace ID").option("--bot <botId>", "bot ID to link to").option("--dev <devBotId>", "dev bot ID (optional)").option("--api-url <apiUrl>", "Botpress API URL (e.g., https://api.botpress.cloud)").option("-f, --force", "overwrite existing agent.json if present").option("--local", "write to gitignored agent.local.json, which overrides agent.json without changing it (for multi-dev workflows)").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("link", async () => {
      const { adkLink } = await import("./chunk-mkjmp0en.js");
      await adkLink(options);
    });
  } catch (error) {
    fatalWith("link", options.format, error);
  }
});
program.command("logs").description("Query dev server logs from .adk/logs/").argument("[tokens...]", "filter tokens (error, warning, info, since=1h, limit=50)").option("-f, --follow", "follow log output (tail -f style)").option("--summary", "emit a single JSON summary snapshot (requires --format json)").option("--format <format>", "output format (json)").addHelpText("after", `
Filter tokens:
  error                 show errors only
  warning               show errors + warnings
  info                  show errors + warnings + info
  since=<duration>      only entries newer than duration (e.g. 30s, 5m, 1h, 2d, 1w)
  limit=<n>             max entries to show (default: 50; in --follow mode, caps total output then exits)

Examples:
  $ adk logs                       # last 50 log entries
  $ adk logs error                 # errors only
  $ adk logs warning since=1h      # warnings+errors from last hour
  $ adk logs --follow              # stream all entries, then follow
  $ adk logs --follow limit=10     # show last 10, then follow
  $ adk logs --format json         # streaming NDJSON output
  $ adk logs --summary --format json
                                  # aggregate summary JSON snapshot
  $ adk logs error limit=10        # last 10 errors
`).action(async (tokens, options) => {
  try {
    await runCliCommand("logs", async () => {
      const { adkLogs } = await import("./chunk-8crxvdch.js");
      await adkLogs(tokens, options);
    }, false);
  } catch (error) {
    fatalWith("logs", options.format, error);
  }
});
program.command("traces").description("Query trace data from local SQLite store").argument("[tokens...]", "filter tokens (error, workflow=name, action=name, trace=id, since=1h, limit=20)").option("-f, --follow", "follow new traces as they complete").option("--format <format>", "output format (json)").option("--include-llm", "include LLM instructions, code, and tools in drill-in mode").addHelpText("after", `
Filter tokens:
  error                 show only traces with errors
  workflow=<name>       filter by workflow name (comma-separated for multiple)
  action=<name>         filter by action/tool name
  trigger=<name>        filter by trigger name
  conversation=<id>     filter by conversation ID
  trace=<id>            drill into specific trace(s) \u2014 shows full span tree
  since=<duration>      only traces newer than duration (e.g. 30s, 5m, 1h, 2d, 1w)
  until=<duration>      only traces older than duration
  limit=<n>             max traces to show (default: 20)

Examples:
  $ adk traces                              # last 20 traces
  $ adk traces error                        # error traces only
  $ adk traces since=1h                     # last hour
  $ adk traces workflow=onboarding          # by workflow
  $ adk traces trace=<id>                   # drill into a trace
  $ adk traces trace=<id> --include-llm     # with LLM content
  $ adk traces --format json                # JSON output
  $ adk traces --follow                     # stream new traces
  $ adk traces --follow error               # stream errors only
`).action(async (tokens, options) => {
  try {
    await runCliCommand("traces", async () => {
      const { adkTraces } = await import("./chunk-124gxhts.js");
      await adkTraces(tokens, options);
    }, false);
  } catch (error) {
    fatalWith("traces", options.format, error);
  }
});
var conversations = program.command("conversations").description("List and inspect conversations from local trace data");
conversations.command("list", { isDefault: true }).description("List recent conversations").argument("[tokens...]", "filter tokens (limit=20, since=1h)").option("--format <format>", "output format (json)").addHelpText("after", `
Filter tokens:
  limit=<n>             max conversations to show (default: 20)
  since=<duration>      only conversations newer than duration (e.g. 30s, 5m, 1h, 2d)

Examples:
  $ adk conversations
  $ adk conversations list
  $ adk conversations list limit=5
  $ adk conversations list since=1h
  $ adk conversations list --format json
`).action(async (tokens, options) => {
  try {
    await runCliCommand("conversations", async () => {
      const { adkConversationsList } = await import("./chunk-rqmzps3v.js");
      await adkConversationsList(tokens, options);
    }, false);
  } catch (error) {
    fatalWith("conversations", options.format, error);
  }
});
conversations.command("show").description("Show conversation timeline and details").argument("<id>", "conversation ID").option("--include-llm", "include LLM reasoning spans").option("--format <format>", "output format (json)").addHelpText("after", `
Examples:
  $ adk conversations show <id>
  $ adk conversations show <id> --include-llm
  $ adk conversations show <id> --format json
`).action(async (id, options) => {
  try {
    await runCliCommand("conversations:show", async () => {
      const { adkConversationsShow } = await import("./chunk-rqmzps3v.js");
      await adkConversationsShow(id, options);
    }, false);
  } catch (error) {
    fatalWith("conversations:show", options.format, error);
  }
});
program.command("chat").description("Chat with your agent in development mode").option("--single <message>", "send one message, print the response, and exit").option("--format <format>", "output format (json)").option("--conversation-id <id>", "continue a conversation (use --format json to get the ID)").option("--timeout <duration>", "max wait duration (500ms, 30s, 1m, 5m)", "60s").addHelpText("after", `
Examples:
  $ adk chat
  $ adk chat --single "What's the status of order 12345?"
  $ adk chat --single "Hello" --format json
  $ adk chat --single "Run the full analysis" --timeout 30s
  $ adk chat --single "Follow up question" --conversation-id <id>

Notes:
  - Requires \`adk dev\` to be running
  - Conversation continuation requires \`adk dev\` to be running (user token is persisted automatically)
`).action(async (options) => {
  try {
    const result = await runCliCommand("chat", async () => {
      const { adkChat } = await import("./chunk-hsfdm54v.js");
      return adkChat(options);
    });
    if (options.single !== undefined && result?.shouldExitAfterSuccess) {
      process.exit(0);
    }
  } catch (error) {
    fatalWith("chat", options.format, error);
  }
});
program.command("run").description("Run a TypeScript script with the full ADK runtime (actions, Zai, tables, etc.)").argument("<script>", "path to the TypeScript script to run").argument("[args...]", "additional arguments passed to the script").option("-f, --force", "force regeneration of the bot project").option("--prod", "use production bot (default: uses dev bot)").addHelpText("after", `
Examples:
  $ adk run ./scripts/migrate.ts
  $ adk run ./scripts/backfill.ts --prod
  $ adk run ./scripts/seed.ts -- --limit 100

The script runs with the full ADK runtime initialized, so you can import
and use actions, Zai, tables, and integration actions directly:

  import { actions, adk, z } from '@botpress/runtime'

  const result = await actions.browser.webSearch({ query: 'hello' })
  const extracted = await adk.zai.extract('some text', z.object({ name: z.string() }))
`).action(async (script, args, options) => {
  try {
    await runCliCommand("run", async () => {
      const { adkRun } = await import("./chunk-tvtbc8vk.js");
      await adkRun(script, args, options);
    });
  } catch (error) {
    logger.fatal(error);
  }
});
var workflows = program.command("workflows").description("List, inspect, and run workflows from the local dev server");
workflows.command("list", { isDefault: true }).description("List all discovered workflows").option("--format <format>", "output format (json)").addHelpText("after", `
Examples:
  $ adk workflows
  $ adk workflows list
  $ adk workflows list --format json
`).action(async (options) => {
  try {
    await runCliCommand("workflows", async () => {
      const { adkWorkflowsList } = await import("./chunk-z062p2ya.js");
      await adkWorkflowsList(options);
    });
  } catch (error) {
    fatalWith("workflows", options.format, error);
  }
});
workflows.command("inspect").description("Inspect a workflow schema and metadata").argument("<name>", "workflow name").option("--format <format>", "output format (json)").addHelpText("after", `
Examples:
  $ adk workflows inspect onboarding
  $ adk workflows inspect onboarding --format json
`).action(async (name, options) => {
  try {
    await runCliCommand("workflows:inspect", async () => {
      const { adkWorkflowsInspect } = await import("./chunk-z062p2ya.js");
      await adkWorkflowsInspect(name, options);
    });
  } catch (error) {
    fatalWith("workflows:inspect", options.format, error);
  }
});
workflows.command("run").description("Run a workflow and optionally wait for completion").argument("<name>", "workflow name").argument("[payload]", "workflow payload as a JSON string").option("--wait", "wait for the workflow to reach a terminal state").option("--timeout <duration>", "max wait duration (500ms, 30s, 1m, 5m); implies --wait").option("--format <format>", "output format (json)", "json").addHelpText("after", `
Examples:
  $ adk workflows run onboarding '{"userId":"123"}'
  $ adk workflows run onboarding '{"userId":"123"}' --wait --timeout 500ms
  $ adk workflows run onboarding '{"userId":"123"}' --wait --timeout 30s
  $ echo '{"userId":"123"}' | adk workflows run onboarding --wait
`).action(async (name, payload, options) => {
  try {
    await runCliCommand("workflows:run", async () => {
      const { adkWorkflowsRun } = await import("./chunk-z062p2ya.js");
      await adkWorkflowsRun(name, payload, options);
    });
  } catch (error) {
    fatalWith("workflows:run", options.format, error);
  }
});
workflows.command("runs").description("List workflow runs, or show one by id").argument("[workflowIdOrTokens...]", "workflow id (wrkflow_...) or filter tokens (name=foo, status=failed, limit=20)").option("--format <format>", "output format (json)").addHelpText("after", `
Examples:
  $ adk workflows runs                              # recent runs
  $ adk workflows runs name=onboarding              # filter by definition name
  $ adk workflows runs status=failed limit=5        # latest 5 failed runs
  $ adk workflows runs nextToken=<token>            # fetch the next page
  $ adk workflows runs wrkflow_01KSF...             # show one run (status + state + steps)
`).action(async (args, options) => {
  try {
    await runCliCommand("workflows:runs", async () => {
      const { adkWorkflowsRuns, isWorkflowInstanceId } = await import("./chunk-z062p2ya.js");
      const first = args[0];
      if (first && isWorkflowInstanceId(first)) {
        await adkWorkflowsRuns(first, options);
      } else {
        await adkWorkflowsRuns(args, options);
      }
    });
  } catch (error) {
    fatalWith("workflows:runs", options.format, error);
  }
});
program.command("config").description('Configure agent settings interactively (use "config:get" or "config:set" for specific values)').option("--prod", "use production configuration").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("config", async () => {
      const { adkConfig } = await import("./chunk-anmpv3vm.js");
      await adkConfig(undefined, options);
    });
  } catch (error) {
    fatalWith("config", options.format, error);
  }
});
program.command("config:get").description("Get a configuration value").argument("<key>", "configuration key").option("--prod", "use production configuration").option("--format <format>", "output format (json)").action(async (key, options) => {
  try {
    await runCliCommand("config:get", async () => {
      const { adkConfigGet } = await import("./chunk-anmpv3vm.js");
      await adkConfigGet(key, options);
    });
  } catch (error) {
    fatalWith("config:get", options.format, error);
  }
});
program.command("config:set").description("Set a configuration value").argument("<key>", "configuration key").argument("<value>", "configuration value").option("--prod", "use production configuration").option("--format <format>", "output format (json)").action(async (key, value, options) => {
  try {
    await runCliCommand("config:set", async () => {
      const { adkConfigSet } = await import("./chunk-anmpv3vm.js");
      await adkConfigSet(key, value, options);
    });
  } catch (error) {
    fatalWith("config:set", options.format, error);
  }
});
program.command("secret").description("Show declared secrets and their status").option("--prod", "use production bot").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("secret", async () => {
      const { adkSecret } = await import("./chunk-1m1bvk5h.js");
      await adkSecret(options);
    });
  } catch (error) {
    fatalWith("secret", options.format, error);
  }
});
program.command("secret:set").description("Set a secret value").argument("<key>", "secret key (SCREAMING_SNAKE_CASE)").argument("<value>", "secret value").option("--prod", "use production bot").option("--format <format>", "output format (json)").action(async (key, value, options) => {
  try {
    await runCliCommand("secret:set", async () => {
      const { adkSecretSet } = await import("./chunk-1m1bvk5h.js");
      await adkSecretSet(key, value, options);
    });
  } catch (error) {
    fatalWith("secret:set", options.format, error);
  }
});
program.command("secret:delete").description("Delete a secret").argument("<key>", "secret key").option("--prod", "use production bot").option("--format <format>", "output format (json)").action(async (key, options) => {
  try {
    await runCliCommand("secret:delete", async () => {
      const { adkSecretDelete } = await import("./chunk-1m1bvk5h.js");
      await adkSecretDelete(key, options);
    });
  } catch (error) {
    fatalWith("secret:delete", options.format, error);
  }
});
program.command("models").description("List available Cognitive models for the current bot").option("--format <format>", "output format (json)").action(async (opts) => {
  try {
    await runCliCommand("models", async () => {
      const { adkModels } = await import("./chunk-phkmqevg.js");
      await adkModels(opts);
    });
  } catch (error) {
    fatalWith("models", opts.format, error);
  }
});
var evals = program.command("evals").description("Run and manage eval suites");
evals.argument("[name]", "Run a specific eval by name").option("--tag <tag>", "Run only evals with this tag").option("--type <type>", "Run only evals of this type (capability|regression)").option("--judge-model <model>", "Model to use for llm_judge assertions (e.g. openai:gpt-4o)").option("--format <format>", "output format (json)").option("-v, --verbose", "Show full details for all evals, not just failures").option("--server <url>", "Dev server URL (auto-starts in lightweight mode if not running)").option("--prod", "Run evals on the production bot via Vortex").action(async (name, opts) => {
  try {
    await runCliCommand("evals", async () => {
      const { adkEvalsRun } = await import("./chunk-cy1cnkej.js");
      await adkEvalsRun(name, opts);
    });
  } catch (error) {
    fatalWith("evals", opts.format, error);
  }
});
evals.command("runs").description("List or show eval run history").argument("[runId]", "Show a specific run by ID").option("--latest", "Show the latest run").option("--limit <n>", "Max runs to list", "10").option("-v, --verbose", "Show full details for all evals in a run").option("--format <format>", "output format (json)").action(async (runId, opts) => {
  try {
    await runCliCommand("evals:runs", async () => {
      const { adkEvalsRuns } = await import("./chunk-cy1cnkej.js");
      await adkEvalsRuns(runId, opts);
    });
  } catch (error) {
    fatalWith("evals:runs", opts.format, error);
  }
});
var kb = program.command("kb").description("Manage knowledge bases and synchronization");
kb.command("sync").description("Synchronize knowledge bases with Botpress (requires --dev or --prod)").option("--dev", "sync with development bot").option("--prod", "sync with production bot").option("--dry-run", "preview changes without applying them").option("-y, --yes", "skip confirmation prompts").option("--confirm-storage-changes", "confirm destructive storage changes (KB deletions)").option("--force", "force re-sync all knowledge bases").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("kb:sync", async () => {
      const { adkKbSync } = await import("./chunk-rha80zvt.js");
      await adkKbSync({ ...options, confirmDeleteKbs: options.confirmStorageChanges });
    });
  } catch (error) {
    fatalWith("kb:sync", options.format, error);
  }
});
var assets = program.command("assets").description("Manage agent assets and static files");
assets.command("sync").description("Synchronize assets with remote storage").option("--dry-run", "preview changes without applying them").option("-y, --yes", "skip confirmation prompts").option("--bail-on-failure", "stop on first error").option("--force", "force re-upload all files").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("assets:sync", async () => {
      const { adkAssetsSync } = await import("./chunk-sxbgyvbx.js");
      await adkAssetsSync(options);
    });
  } catch (error) {
    fatalWith("assets:sync", options.format, error);
  }
});
assets.command("list").description("List all asset files").option("--local", "show only local assets").option("--remote", "show only remote assets").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("assets:list", async () => {
      const { adkAssetsList } = await import("./chunk-sxbgyvbx.js");
      await adkAssetsList(options);
    });
  } catch (error) {
    fatalWith("assets:list", options.format, error);
  }
});
assets.command("status").description("Show asset synchronization status").option("--format <format>", "output format (json)").action(async (options) => {
  try {
    await runCliCommand("assets:status", async () => {
      const { adkAssetsStatus } = await import("./chunk-sxbgyvbx.js");
      await adkAssetsStatus(options);
    });
  } catch (error) {
    fatalWith("assets:status", options.format, error);
  }
});
assets.command("pull").description("Download remote assets to local directory").action(async () => {
  try {
    await runCliCommand("assets:pull", async () => {
      const { adkAssetsPull } = await import("./chunk-sxbgyvbx.js");
      await adkAssetsPull();
    });
  } catch (error) {
    logger.fatal(error);
  }
});
var fleet = program.command("fleet").description("Manage Fleet embedded frontends");
fleet.command("upload").description("Package and upload a static frontend dist for Fleet embedding").requiredOption("--dist <dir>", "static frontend dist directory containing index.html").option("--target <env>", "dev or prod (default: dev)").option("--label <label>", "Fleet embed label (default: App)").option("--rotate-secret", "rotate the fleetembedsecret bot tag").option("--dry-run", "preview the upload without writing files or tags").option("--format <format>", "output format (json)").addHelpText("after", `
Examples:
  $ adk fleet upload --target dev --dist ./frontend/dist --label "Dashboard"
  $ adk fleet upload --target prod --dist ./frontend/dist --label "Dashboard"
  $ adk fleet upload --target dev --dist ./frontend/dist --dry-run --format json
`).action(async (options) => {
  try {
    await runCliCommand("fleet:upload", async () => {
      const { adkFleetUpload } = await import("./chunk-xmj7eker.js");
      await adkFleetUpload(options);
    });
  } catch (error) {
    fatalWith("fleet:upload", options.format, error);
  }
});
fleet.command("remove").description("Remove the uploaded Fleet app package and clear Fleet bot tags").option("--target <env>", "dev or prod (default: dev)").option("--dry-run", "preview removal without deleting files or clearing tags").option("--format <format>", "output format (json)").addHelpText("after", `
Examples:
  $ adk fleet remove --target dev
  $ adk fleet remove --target prod
  $ adk fleet remove --target dev --dry-run --format json
`).action(async (options) => {
  try {
    await runCliCommand("fleet:remove", async () => {
      const { adkFleetRemove } = await import("./chunk-xmj7eker.js");
      await adkFleetRemove(options);
    });
  } catch (error) {
    fatalWith("fleet:remove", options.format, error);
  }
});
program.command("flags", { hidden: true }).description("Show feature-flag values for the current profile").option("--format <format>", "output format (json)").action(async (opts) => {
  try {
    await runCliCommand("flags", async () => {
      const { adkFlags } = await import("./chunk-fekf0395.js");
      await adkFlags(opts);
    });
  } catch (error) {
    fatalWith("flags", opts.format, error);
  }
});
function configureAllCommandsHelp() {
  function configureHelpRecursive(cmd) {
    cmd.configureHelp({
      formatHelp: () => formatCommandHelp(cmd)
    });
    cmd.commands.forEach((subcmd) => {
      configureHelpRecursive(subcmd);
    });
  }
  program.commands.forEach((cmd) => {
    configureHelpRecursive(cmd);
  });
}
configureAllCommandsHelp();
program.on("command:*", function(operands) {
  const unknownCommand = operands[0];
  const allCommands = Array.from(program.commands);
  const suggestions = findSimilarCommands(unknownCommand, allCommands);
  const suggestionText = formatSuggestion(unknownCommand, suggestions);
  logger.error(`adk: "${unknownCommand}" is not an adk command. See 'adk help'.
`);
  if (suggestionText) {
    logger.warn(`\uD83D\uDCA1 ${suggestionText}
`);
  }
  program.help();
});
async function main() {
  const args = process.argv.slice(2);
  if (args.includes("--version") || args.includes("-V")) {
    checkForUpdates(CLI_VERSION);
  }
  const hasCommand = args.some((arg) => !arg.startsWith("-") && !arg.startsWith("--"));
  if (!hasCommand && args.length > 0 && args.every((arg) => arg === "--no-cache")) {
    try {
      const { adkInfo } = await import("./chunk-15cecm1h.js");
      await adkInfo(undefined, { noCache: true });
    } catch (error) {
      logger.fatal(error);
    }
  } else if (!hasCommand && args.length === 0) {
    checkForUpdates(CLI_VERSION);
    const agentRoot = await findAgentRoot(process.cwd());
    if (agentRoot) {
      try {
        await runCliCommand("dev", async () => {
          ensureDevNodeEnv();
          const { adkDev } = await import("./chunk-e0a9ej4b.js");
          await adkDev("3000", {
            ui: true,
            adkDevConsolePortStr: "3001"
          });
        });
      } catch (error) {
        logger.fatal(error);
      }
    } else {
      const isInteractive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
      if (!isInteractive) {
        logger.info(formatWelcome(CLI_VERSION));
        return;
      }
      try {
        await runCliCommand("home", async () => {
          const { adkHome } = await import("./chunk-1nvfpd8y.js");
          await adkHome({ version: CLI_VERSION });
        }, false);
      } catch (error) {
        logger.fatal(error);
      }
    }
  } else {
    program.parse();
  }
}
main();