CoolFace
Datasetpublic

basant307/AI_Governance_Project

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
0likes45downloads
cli.js423 linesDownload Raw Back to dist
1// Force strict mode and setup for ESM2"use strict";3import {4  initCpuProfiler5} from "./chunks/chunk-JIRZLLCO.js";6import {7  initStartupProfiler8} from "./chunks/chunk-ITOGNELQ.js";9import {10  normalizeServeFastPathArgv11} from "./chunks/chunk-FXGLL2HL.js";12import "./chunks/chunk-2GCQE7TQ.js";13import {14  init_esbuild_shims15} from "./chunks/chunk-A4BMJM77.js";16import {17  __name18} from "./chunks/chunk-J2S4EL5Y.js";19 20// packages/cli/src/cli.ts21init_esbuild_shims();22import { pathToFileURL } from "node:url";23initStartupProfiler();24initCpuProfiler();25var TOP_LEVEL_COMMANDS = [26  ["auth", "Configure authentication (removed)"],27  ["channel <command>", "Manage messaging channels (Telegram, Discord, etc.)"],28  ["extensions <command>", "Manage Qwen Code extensions."],29  ["hooks", "Manage Qwen Code hooks (use /hooks in interactive mode)."],30  ["mcp", "Manage MCP servers"],31  [32    "review <command>",33    "Internal helpers used by the /review skill (PR worktree setup, context fetch, rules loading, presubmit checks, cleanup)"34  ],35  [36    "serve",37    "Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)"38  ],39  ["sessions <command>", "Manage Qwen Code sessions"]40];41var MCP_COMMANDS = [42  ["add <name> <commandOrUrl> [args...]", "Add a server"],43  ["remove <name>", "Remove a server"],44  ["list", "List all configured MCP servers"],45  ["reconnect [server-name]", "Reconnect to MCP servers"],46  ["approve [name]", "Approve a pending MCP server"],47  ["reject [name]", "Reject a pending MCP server"]48];49var TOP_LEVEL_HELP_OPTIONS = [50  ["model", { alias: "m", type: "string", description: "Model" }],51  [52    "fallback-model",53    {54      type: "array",55      description: "Fallback model(s) for capacity errors, repeatable or comma-separated (max 3)"56    }57  ],58  [59    "prompt",60    {61      alias: "p",62      type: "string",63      description: "Prompt. Appended to input on stdin (if any)."64    }65  ],66  [67    "prompt-interactive",68    {69      alias: "i",70      type: "string",71      description: "Execute the provided prompt and continue in interactive mode"72    }73  ],74  [75    "safe-mode",76    {77      type: "boolean",78      description: "Disable all customizations (context files, hooks, extensions, skills, MCP servers) for troubleshooting."79    }80  ],81  [82    "sandbox",83    {84      alias: "s",85      type: "boolean",86      description: "Run in sandbox?"87    }88  ],89  [90    "output-format",91    {92      alias: "o",93      type: "string",94      choices: ["text", "json", "stream-json"],95      description: "The format of the CLI output."96    }97  ],98  [99    "continue",100    {101      alias: "c",102      type: "boolean",103      description: "Resume the most recent session for the current project."104    }105  ],106  [107    "resume",108    {109      alias: "r",110      type: "string",111      description: "Resume a specific session by its ID. Use without an ID to show session picker."112    }113  ]114];115var VALUE_FLAGS = /* @__PURE__ */ new Set([116  "--model",117  "-m",118  "--fallback-model",119  "--prompt",120  "-p",121  "--prompt-interactive",122  "-i",123  "--output-format",124  "-o",125  "--resume",126  "-r"127]);128function writeStdoutLine(line) {129  process.stdout.write(line.endsWith("\n") ? line : `${line}130`);131}132__name(writeStdoutLine, "writeStdoutLine");133function hasFlag(argv, long, short) {134  for (let i = 0; i < argv.length; i++) {135    const arg = argv[i];136    if (arg === "--") {137      return false;138    }139    if (VALUE_FLAGS.has(arg)) {140      i++;141      continue;142    }143    if (arg === long || arg === short) {144      return true;145    }146  }147  return false;148}149__name(hasFlag, "hasFlag");150async function buildTopLevelHelpParser() {151  const { default: yargs } = await import("./chunks/yargs-B64EYTCF.js");152  const parser = yargs([]).scriptName("qwen").usage(153    "Usage: qwen [options] [command]\n\nQwen Code - Launch an interactive CLI, use -p/--prompt for non-interactive mode"154  ).version("0.19.7").alias("v", "version").help().alias("h", "help").strict().demandCommand(0, 0);155  for (const [option, config] of TOP_LEVEL_HELP_OPTIONS) {156    parser.option(option, config);157  }158  for (const [command, description] of TOP_LEVEL_COMMANDS) {159    parser.command(command, description);160  }161  return parser;162}163__name(buildTopLevelHelpParser, "buildTopLevelHelpParser");164function firstPositionalArg(argv) {165  for (let i = 0; i < argv.length; i++) {166    const arg = argv[i];167    if (arg === "--") {168      return void 0;169    }170    if (VALUE_FLAGS.has(arg)) {171      i++;172      continue;173    }174    if (!arg.startsWith("-")) {175      return arg;176    }177  }178  return void 0;179}180__name(firstPositionalArg, "firstPositionalArg");181function normalizeMcpFastPathArgv(argv) {182  if (argv[0] === "mcp" && argv[1] === "--") {183    return [argv[0], ...argv.slice(2)];184  }185  return argv;186}187__name(normalizeMcpFastPathArgv, "normalizeMcpFastPathArgv");188function resolveBootstrapRoute(rawArgv) {189  const argv = normalizeServeFastPathArgv(rawArgv);190  if (hasFlag(argv, "--version", "-v")) {191    return "version";192  }193  const firstArg = argv[0];194  if (firstArg === "serve") {195    return "serve";196  }197  if (firstArg === "mcp") {198    return "mcp";199  }200  const firstPositional = firstPositionalArg(argv);201  if (hasFlag(argv, "--help", "-h") && firstPositional === void 0) {202    return "help";203  }204  return "default";205}206__name(resolveBootstrapRoute, "resolveBootstrapRoute");207async function printTopLevelHelp() {208  const help = await (await buildTopLevelHelpParser()).getHelp();209  writeStdoutLine(help);210}211__name(printTopLevelHelp, "printTopLevelHelp");212function printMcpHelp() {213  const lines = [214    "Usage: qwen mcp <command>",215    "",216    "Manage MCP servers",217    "",218    "Commands:",219    ...MCP_COMMANDS.map(220      ([command, description]) => `  qwen mcp ${command}  ${description}`221    )222  ];223  writeStdoutLine(lines.join("\n"));224}225__name(printMcpHelp, "printMcpHelp");226async function printBootstrapVersion() {227  if ("0.19.7") {228    writeStdoutLine("0.19.7");229    return;230  }231  const { getCliVersion } = await import("./chunks/version-CEDD6ZZR.js");232  writeStdoutLine(await getCliVersion());233}234__name(printBootstrapVersion, "printBootstrapVersion");235async function runMcpFastPath(rawArgv) {236  const argv = normalizeMcpFastPathArgv(normalizeServeFastPathArgv(rawArgv));237  const hasSubcommand = argv.length > 1 && !argv[1].startsWith("-");238  if (!hasSubcommand) {239    printMcpHelp();240    return;241  }242  const [{ default: yargsInstance }, { mcpCommand }] = await Promise.all([243    import("./chunks/yargs-B64EYTCF.js"),244    import("./chunks/mcp-N35SV7MV.js")245  ]);246  const parser = yargsInstance([]).scriptName("qwen").command(mcpCommand).version(false).help().alias("h", "help").strict().strictCommands().demandCommand(1, "You need at least one command before continuing.").fail((message, error, yargs) => {247    writeStderrLine(message || error?.message || "Unknown argument error");248    yargs.showHelp();249    process.exitCode = 1;250  }).exitProcess(false);251  if (hasFlag(argv.slice(2), "--help", "-h")) {252    await parseYargsHelp(parser, argv);253    return;254  }255  await parseYargsCommand(parser, argv);256}257__name(runMcpFastPath, "runMcpFastPath");258async function parseYargsHelp(parser, argv) {259  await new Promise((resolve, reject) => {260    parser.parse(261      argv,262      (error, _argv, output) => {263        if (output) {264          writeStdoutLine(output);265        }266        if (error) {267          reject(error);268          return;269        }270        resolve();271      }272    );273  });274}275__name(parseYargsHelp, "parseYargsHelp");276async function parseYargsCommand(parser, argv) {277  await new Promise((resolve) => {278    parser.parse(279      argv,280      (error, _argv, output) => {281        if (output) {282          writeStdoutLine(output);283        }284        if (error) {285          writeStderrLine(error.message);286          process.exitCode = 1;287        }288        resolve();289      }290    );291  });292}293__name(parseYargsCommand, "parseYargsCommand");294async function runCliEntry(rawArgv = process.argv.slice(2)) {295  const argv = normalizeServeFastPathArgv(rawArgv);296  const route = resolveBootstrapRoute(argv);297  if (route === "version") {298    await printBootstrapVersion();299    return;300  }301  if (route === "serve") {302    const { tryRunServeFastPath } = await import("./chunks/fast-path-6EWGBIVK.js");303    if (await tryRunServeFastPath(argv)) {304      return;305    }306  } else if (route === "mcp") {307    await runMcpFastPath(argv);308    return;309  } else if (route === "help") {310    await printTopLevelHelp();311    return;312  }313  const { main } = await import("./chunks/gemini-4VOCF2EZ.js");314  await main();315}316__name(runCliEntry, "runCliEntry");317function getErrnoCode(error) {318  if (!error || typeof error !== "object") {319    return void 0;320  }321  const code = error.code;322  return typeof code === "string" ? code : void 0;323}324__name(getErrnoCode, "getErrnoCode");325function isExpectedPtyRaceError(error) {326  if (!(error instanceof Error)) {327    return false;328  }329  const message = error.message;330  const code = getErrnoCode(error);331  if (code === "EIO" && message.includes("read") || message.includes("read EIO")) {332    return true;333  }334  if (code === "EAGAIN" && message.includes("read") || message.includes("read EAGAIN")) {335    return true;336  }337  return message.includes("ioctl(2) failed, EBADF") || message.includes("Cannot resize a pty that has already exited");338}339__name(isExpectedPtyRaceError, "isExpectedPtyRaceError");340async function handleCriticalError(error) {341  const [{ FatalError }, { AlreadyReportedError }] = await Promise.all([342    import("./chunks/src-735HNRTT.js"),343    import("./chunks/errors-ABW54KTC.js")344  ]);345  if (error instanceof FatalError) {346    let errorMessage = error.message;347    if (!process.env["NO_COLOR"]) {348      errorMessage = `\x1B[31m${errorMessage}\x1B[0m`;349    }350    writeStderrLine(errorMessage);351    process.exit(error.exitCode);352  }353  if (error instanceof AlreadyReportedError) {354    process.exit(error.exitCode);355  }356  writeStderrLine("An unexpected critical error occurred:");357  if (error instanceof Error) {358    writeStderrLine(error.stack ?? error.message);359  } else {360    writeStderrLine(String(error));361  }362  process.exit(1);363}364__name(handleCriticalError, "handleCriticalError");365function writeStderrLine(line) {366  process.stderr.write(line.endsWith("\n") ? line : `${line}367`);368}369__name(writeStderrLine, "writeStderrLine");370async function runCliEntryPoint(run = runCliEntry, handleError = handleCriticalError) {371  process.on("uncaughtException", (error) => {372    if (isExpectedPtyRaceError(error)) {373      return;374    }375    if (error instanceof Error) {376      writeStderrLine(error.stack ?? error.message);377    } else {378      writeStderrLine(String(error));379    }380    process.exit(1);381  });382  try {383    await run();384  } catch (error) {385    try {386      await handleError(error);387    } catch (handlerError) {388      writeStderrLine("An unexpected critical error occurred:");389      writeStderrLine("Original error:");390      if (error instanceof Error) {391        writeStderrLine(error.stack ?? error.message);392      } else {393        writeStderrLine(String(error));394      }395      writeStderrLine("Error handler failed:");396      if (handlerError instanceof Error) {397        writeStderrLine(handlerError.stack ?? handlerError.message);398      } else {399        writeStderrLine(String(handlerError));400      }401      process.exit(1);402    }403  }404}405__name(runCliEntryPoint, "runCliEntryPoint");406if (process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href) {407  void runCliEntryPoint();408}409export {410  MCP_COMMANDS,411  TOP_LEVEL_COMMANDS,412  handleCriticalError,413  isExpectedPtyRaceError,414  resolveBootstrapRoute,415  runCliEntry,416  runCliEntryPoint417};418/**419 * @license420 * Copyright 2026 Qwen Team421 * SPDX-License-Identifier: Apache-2.0422 */423 
basant307/AI_Governance_Project · CoolFace