// Force strict mode and setup for ESM
"use strict";
import {
  init_esm,
  isSpanContextValid,
  trace
} from "./chunk-Z2Z3GUXZ.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/utils/errors.ts
init_esbuild_shims();
var MAX_STRINGIFIED_ERROR_MESSAGE_LENGTH = 1e3;
function isNodeError(error) {
  return error instanceof Error && "code" in error;
}
__name(isNodeError, "isNodeError");
function isAbortError(error) {
  if (!error || typeof error !== "object") {
    return false;
  }
  if (error instanceof Error && error.name === "AbortError") {
    return true;
  }
  if (isNodeError(error) && error.code === "ABORT_ERR") {
    return true;
  }
  return false;
}
__name(isAbortError, "isAbortError");
function describeErrorCause(cause) {
  if (cause == null) return void 0;
  if (cause instanceof AggregateError && Array.isArray(cause.errors)) {
    const inner = cause.errors.map((e) => describeSingleError(e)).filter((s) => Boolean(s));
    if (inner.length > 0) {
      return [...new Set(inner)].join("; ");
    }
  }
  return describeSingleError(cause);
}
__name(describeErrorCause, "describeErrorCause");
function describeSingleError(err) {
  if (err instanceof Error) {
    const code = err.code;
    const codeStr = typeof code === "string" ? code : void 0;
    const msg = err.message?.trim();
    if (msg && codeStr && !msg.includes(codeStr)) {
      return `${codeStr}: ${msg}`;
    }
    return msg || codeStr || (err.name !== "Error" ? err.name : void 0);
  }
  if (err && typeof err === "object" && !Array.isArray(err)) {
    const rec = err;
    const code = rec["code"];
    const codeStr = typeof code === "string" && code ? code : typeof code === "number" ? String(code) : void 0;
    const message = rec["message"];
    const msg = typeof message === "string" && message.trim() ? message.trim() : void 0;
    if (msg && codeStr && !msg.includes(codeStr)) {
      return `${codeStr}: ${msg}`;
    }
    return msg || codeStr;
  }
  const str = String(err);
  return str && str !== "[object Object]" ? str : void 0;
}
__name(describeSingleError, "describeSingleError");
function truncateStringifiedErrorMessage(message) {
  if (message.length <= MAX_STRINGIFIED_ERROR_MESSAGE_LENGTH) {
    return message;
  }
  return `${message.slice(0, MAX_STRINGIFIED_ERROR_MESSAGE_LENGTH - 3)}...`;
}
__name(truncateStringifiedErrorMessage, "truncateStringifiedErrorMessage");
function getErrorMessage(error) {
  if (error instanceof Error) {
    const detail = describeErrorCause(error.cause);
    if (detail && detail !== error.message) {
      return truncateStringifiedErrorMessage(
        `${error.message} (cause: ${detail})`
      );
    }
    return error.message;
  }
  if (error !== null && typeof error === "object" && !Array.isArray(error)) {
    const { message, cause } = error;
    if (typeof message === "string" && message.trim()) {
      const detail = describeErrorCause(cause);
      const result = detail && detail !== message ? `${message} (cause: ${detail})` : message;
      return truncateStringifiedErrorMessage(result);
    }
    try {
      const serialized = JSON.stringify(error);
      return serialized ? truncateStringifiedErrorMessage(serialized) : String(error);
    } catch {
      const detail = describeSingleError(error);
      return detail ? truncateStringifiedErrorMessage(detail) : String(error);
    }
  }
  try {
    return String(error);
  } catch {
    return "Failed to get error details";
  }
}
__name(getErrorMessage, "getErrorMessage");
function getErrorStatus(error) {
  if (typeof error !== "object" || error === null) {
    return void 0;
  }
  const err = error;
  const value = err.status ?? err.statusCode ?? err.response?.status ?? err.error?.code;
  if (typeof value === "number" && value >= 100 && value <= 599) {
    return value;
  }
  if (typeof err.message === "string") {
    const match = err.message.match(/HTTP_STATUS\/(\d{3})\b/);
    if (match) {
      const parsed = Number(match[1]);
      if (parsed >= 100 && parsed <= 599) {
        return parsed;
      }
    }
  }
  return void 0;
}
__name(getErrorStatus, "getErrorStatus");
function getErrorType(error) {
  if (typeof error !== "object" || error === null) {
    return "unknown";
  }
  const constructorName = error instanceof Error && error.constructor.name !== "Error" ? error.constructor.name : void 0;
  const sdkType = error.type;
  const baseType = constructorName ?? sdkType ?? (error instanceof Error ? error.name : "unknown");
  const cause = error instanceof Error ? error.cause : void 0;
  const causeCode = cause && typeof cause === "object" && "code" in cause ? cause.code : void 0;
  return causeCode ? `${baseType}:${causeCode}` : baseType;
}
__name(getErrorType, "getErrorType");
var FatalError = class extends Error {
  constructor(message, exitCode) {
    super(message);
    this.exitCode = exitCode;
  }
  static {
    __name(this, "FatalError");
  }
};
var FatalAuthenticationError = class extends FatalError {
  static {
    __name(this, "FatalAuthenticationError");
  }
  constructor(message) {
    super(message, 41);
  }
};
var FatalInputError = class extends FatalError {
  static {
    __name(this, "FatalInputError");
  }
  constructor(message) {
    super(message, 42);
  }
};
var FatalSandboxError = class extends FatalError {
  static {
    __name(this, "FatalSandboxError");
  }
  constructor(message) {
    super(message, 44);
  }
};
var FatalConfigError = class extends FatalError {
  static {
    __name(this, "FatalConfigError");
  }
  constructor(message) {
    super(message, 52);
  }
};
var FatalTurnLimitedError = class extends FatalError {
  static {
    __name(this, "FatalTurnLimitedError");
  }
  constructor(message) {
    super(message, 53);
  }
};
var FatalToolExecutionError = class extends FatalError {
  static {
    __name(this, "FatalToolExecutionError");
  }
  constructor(message) {
    super(message, 54);
  }
};
var FatalBudgetExceededError = class extends FatalError {
  static {
    __name(this, "FatalBudgetExceededError");
  }
  constructor(message) {
    super(message, 55);
  }
};
var FatalCancellationError = class extends FatalError {
  static {
    __name(this, "FatalCancellationError");
  }
  constructor(message) {
    super(message, 130);
  }
};
var ForbiddenError = class extends Error {
  static {
    __name(this, "ForbiddenError");
  }
};
var UnauthorizedError = class extends Error {
  static {
    __name(this, "UnauthorizedError");
  }
};
var BadRequestError = class extends Error {
  static {
    __name(this, "BadRequestError");
  }
};
function toFriendlyError(error) {
  if (error && typeof error === "object" && "response" in error) {
    const gaxiosError = error;
    const data = parseResponseData(gaxiosError);
    if (data.error && data.error.message && data.error.code) {
      switch (data.error.code) {
        case 400:
          return new BadRequestError(data.error.message);
        case 401:
          return new UnauthorizedError(data.error.message);
        case 403:
          return new ForbiddenError(data.error.message);
        default:
      }
    }
  }
  return error;
}
__name(toFriendlyError, "toFriendlyError");
function parseResponseData(error) {
  if (typeof error.response?.data === "string") {
    return JSON.parse(error.response?.data);
  }
  return error.response?.data;
}
__name(parseResponseData, "parseResponseData");

// packages/core/src/utils/paths.ts
init_esbuild_shims();
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import * as crypto from "node:crypto";
var QWEN_DIR = ".qwen";
var GOOGLE_ACCOUNTS_FILENAME = "google_accounts.json";
var isDirectoryCache = /* @__PURE__ */ new Map();
var VALIDATE_PATH_CACHE_MAX = 1024;
function _resetValidatePathCacheForTest() {
  isDirectoryCache.clear();
}
__name(_resetValidatePathCacheForTest, "_resetValidatePathCacheForTest");
var SHELL_SPECIAL_CHARS = /[ \t()[\]{};|*?$`'"#&<>!~,]/;
var PATH_ARG_KEYS = [
  "file_path",
  "path",
  "filePath",
  "notebook_path"
];
var UNESCAPE_REGEX = (() => {
  const inner = SHELL_SPECIAL_CHARS.source.slice(1, -1);
  return new RegExp(`\\\\([${inner}])`, "g");
})();
function tildeifyPath(filePath) {
  const rawHomeDir = os.homedir();
  if (!rawHomeDir) {
    return filePath;
  }
  const homeDir = path.normalize(rawHomeDir);
  const normalizedPath = path.normalize(filePath);
  if (normalizedPath === homeDir) {
    return "~";
  }
  if (normalizedPath.startsWith(`${homeDir}${path.sep}`)) {
    return normalizedPath.replace(homeDir, "~");
  }
  return filePath;
}
__name(tildeifyPath, "tildeifyPath");
function expandTilde(p) {
  if (!p) {
    return "";
  }
  if (p === "~") {
    return os.homedir();
  }
  if (p === "~/" || p === "~\\") {
    return os.homedir() + path.sep;
  }
  if (p.startsWith("~/")) {
    return path.join(os.homedir(), p.substring(2));
  }
  if (p.startsWith("~\\")) {
    const rest = p.substring(2);
    const hasTrailingSep = rest.endsWith("/") || rest.endsWith("\\");
    const expandedPath = path.join(
      os.homedir(),
      ...rest.split(/[/\\]+/).filter(Boolean)
    );
    return hasTrailingSep ? expandedPath + path.sep : expandedPath;
  }
  return p;
}
__name(expandTilde, "expandTilde");
function expandHomeDir(p) {
  if (!p) {
    return "";
  }
  const userProfilePrefix = "%userprofile%";
  const lowerPath = p.toLowerCase();
  if (lowerPath === userProfilePrefix) {
    return path.normalize(os.homedir());
  }
  if (lowerPath === `${userProfilePrefix}/` || lowerPath === `${userProfilePrefix}\\`) {
    return path.normalize(os.homedir() + path.sep);
  }
  if (lowerPath.startsWith(`${userProfilePrefix}/`) || lowerPath.startsWith(`${userProfilePrefix}\\`)) {
    const rest = p.substring(userProfilePrefix.length + 1);
    const hasTrailingSep = rest.endsWith("/") || rest.endsWith("\\");
    const expandedPath = path.join(
      os.homedir(),
      ...rest.split(/[/\\]+/).filter(Boolean)
    );
    return path.normalize(
      hasTrailingSep ? expandedPath + path.sep : expandedPath
    );
  }
  if (lowerPath.startsWith(userProfilePrefix)) {
    return path.normalize(os.homedir() + p.substring(userProfilePrefix.length));
  }
  return path.normalize(expandTilde(p));
}
__name(expandHomeDir, "expandHomeDir");
function shortenPath(filePath, maxLen = 80) {
  if (filePath.length <= maxLen) {
    return filePath;
  }
  const separator = path.sep;
  const ellipsis = "...";
  if (maxLen < 10) {
    return filePath.substring(0, maxLen - 3) + ellipsis;
  }
  const parsedPath = path.parse(filePath);
  const root = parsedPath.root;
  const relativePath = filePath.substring(root.length);
  const segments = relativePath.split(separator).filter((s) => s !== "");
  if (segments.length === 0) {
    return root.length <= maxLen ? root : root.substring(0, maxLen - 3) + ellipsis;
  }
  if (segments.length === 1) {
    const full = root + segments[0];
    if (full.length <= maxLen) {
      return full;
    }
    const keepLen = Math.floor((maxLen - 3) / 2);
    const start = full.substring(0, keepLen);
    const end = full.substring(full.length - keepLen);
    return `${start}${ellipsis}${end}`;
  }
  const startPart = root + segments[0];
  const endSegments = [];
  for (let i = segments.length - 1; i >= 1; i--) {
    const segment = segments[i];
    const endPart = [segment, ...endSegments].join(separator);
    const needsEllipsis = i > 1;
    let candidateResult;
    if (needsEllipsis) {
      candidateResult = startPart + separator + ellipsis + separator + endPart;
    } else {
      candidateResult = startPart + separator + endPart;
    }
    if (candidateResult.length <= maxLen) {
      endSegments.unshift(segment);
      if (i === 1) {
        return candidateResult;
      }
    } else {
      break;
    }
  }
  if (endSegments.length === 0) {
    const keepLen = Math.floor((maxLen - 3) / 2);
    const start = filePath.substring(0, keepLen);
    const end = filePath.substring(filePath.length - keepLen);
    return `${start}${ellipsis}${end}`;
  }
  return startPart + separator + ellipsis + separator + endSegments.join(separator);
}
__name(shortenPath, "shortenPath");
function makeRelative(targetPath, rootDirectory) {
  const resolvedTargetPath = path.resolve(targetPath);
  const resolvedRootDirectory = path.resolve(rootDirectory);
  if (!isSubpath(resolvedRootDirectory, resolvedTargetPath)) {
    return resolvedTargetPath;
  }
  const relativePath = path.relative(resolvedRootDirectory, resolvedTargetPath);
  return relativePath || ".";
}
__name(makeRelative, "makeRelative");
function escapePath(filePath) {
  let result = "";
  for (let i = 0; i < filePath.length; i++) {
    const char = filePath[i];
    let backslashCount = 0;
    for (let j = i - 1; j >= 0 && filePath[j] === "\\"; j--) {
      backslashCount++;
    }
    const isAlreadyEscaped = backslashCount % 2 === 1;
    if (!isAlreadyEscaped && SHELL_SPECIAL_CHARS.test(char)) {
      result += "\\" + char;
    } else {
      result += char;
    }
  }
  return result;
}
__name(escapePath, "escapePath");
function unescapePath(filePath) {
  if (os.platform() === "win32") {
    return filePath;
  }
  const unescaped = filePath.replace(UNESCAPE_REGEX, "$1");
  return unescaped;
}
__name(unescapePath, "unescapePath");
function getProjectHash(projectRoot) {
  const normalizedPath = os.platform() === "win32" ? projectRoot.toLowerCase() : projectRoot;
  return crypto.createHash("sha256").update(normalizedPath).digest("hex");
}
__name(getProjectHash, "getProjectHash");
function sanitizeCwd(cwd) {
  const normalizedCwd = os.platform() === "win32" ? cwd.toLowerCase() : cwd;
  return normalizedCwd.replace(/[^a-zA-Z0-9]/g, "-");
}
__name(sanitizeCwd, "sanitizeCwd");
function isSubpath(parentPath, childPath) {
  const isWindows = os.platform() === "win32";
  const pathModule = isWindows ? path.win32 : path;
  const relative2 = pathModule.relative(parentPath, childPath);
  return !relative2.startsWith(`..${pathModule.sep}`) && relative2 !== ".." && !pathModule.isAbsolute(relative2);
}
__name(isSubpath, "isSubpath");
function isSubpaths(parentPath, childPath) {
  return parentPath.some((p) => isSubpath(p, childPath));
}
__name(isSubpaths, "isSubpaths");
function resolvePath(baseDir = process.cwd(), relativePath) {
  const expandedPath = expandTilde(relativePath);
  if (path.isAbsolute(expandedPath)) {
    return expandedPath;
  } else {
    return path.resolve(baseDir, expandedPath);
  }
}
__name(resolvePath, "resolvePath");
function validatePath(config, resolvedPath, options = {}) {
  const { allowFiles = false, allowExternalPaths = false } = options;
  const workspaceContext = config.getWorkspaceContext();
  const isWithinWorkspace = workspaceContext.isPathWithinWorkspace(resolvedPath);
  if (!allowExternalPaths && !isWithinWorkspace) {
    throw new Error("Path is not within workspace");
  }
  if (allowExternalPaths && !isWithinWorkspace) {
    return;
  }
  let isDirectory = isDirectoryCache.get(resolvedPath);
  if (isDirectory === void 0) {
    try {
      isDirectory = fs.statSync(resolvedPath).isDirectory();
    } catch (error) {
      if (isNodeError(error) && error.code === "ENOENT") {
        throw new Error(`Path does not exist: ${resolvedPath}`);
      }
      throw error;
    }
    if (isDirectoryCache.size >= VALIDATE_PATH_CACHE_MAX) {
      const oldest = isDirectoryCache.keys().next().value;
      if (oldest !== void 0) isDirectoryCache.delete(oldest);
    }
    isDirectoryCache.set(resolvedPath, isDirectory);
  }
  if (!allowFiles && !isDirectory) {
    throw new Error(`Path is not a directory: ${resolvedPath}`);
  }
}
__name(validatePath, "validatePath");
function resolveAndValidatePath(config, relativePath, options = {}) {
  const targetDir = config.getTargetDir();
  if (!relativePath) {
    return targetDir;
  }
  const resolvedPath = resolvePath(targetDir, relativePath);
  validatePath(config, resolvedPath, options);
  return resolvedPath;
}
__name(resolveAndValidatePath, "resolveAndValidatePath");

// packages/core/src/config/storage.ts
init_esbuild_shims();
import * as path2 from "node:path";
import * as os2 from "node:os";
import * as fs2 from "node:fs";
import { AsyncLocalStorage } from "node:async_hooks";
var GOOGLE_ACCOUNTS_FILENAME2 = "google_accounts.json";
var OAUTH_FILE = "oauth_creds.json";
var SKILL_PROVIDER_CONFIG_DIRS = [".qwen", ".agents"];
var TMP_DIR_NAME = "tmp";
var BIN_DIR_NAME = "bin";
var PROJECT_DIR_NAME = "projects";
var IDE_DIR_NAME = "ide";
var PLANS_DIR_NAME = "plans";
var DEBUG_DIR_NAME = "debug";
var ARENA_DIR_NAME = "arena";
function isResolvedPathWithinDirectory(childPath, parentPath) {
  const relativePath = path2.relative(parentPath, childPath);
  return relativePath === "" || !relativePath.startsWith(`..${path2.sep}`) && relativePath !== ".." && !path2.isAbsolute(relativePath);
}
__name(isResolvedPathWithinDirectory, "isResolvedPathWithinDirectory");
var Storage = class _Storage {
  static {
    __name(this, "Storage");
  }
  targetDir;
  /**
   * Custom runtime output base directory set via settings.
   * When null, falls back to getGlobalQwenDir().
   */
  static runtimeBaseDir = null;
  static runtimeBaseDirContext = new AsyncLocalStorage();
  constructor(targetDir) {
    this.targetDir = targetDir;
  }
  /**
   * Expands tilde and resolves relative paths to absolute.
   */
  static resolvePath(dir, cwd) {
    let resolved = dir;
    if (resolved === "~" || resolved.startsWith("~/") || resolved.startsWith("~\\")) {
      const relativeSegments = resolved === "~" ? [] : resolved.slice(2).split(/[/\\]+/).filter(Boolean);
      resolved = path2.join(os2.homedir(), ...relativeSegments);
    }
    if (!path2.isAbsolute(resolved)) {
      resolved = cwd ? path2.resolve(cwd, resolved) : path2.resolve(resolved);
    }
    return resolved;
  }
  /**
   * Sanitizes a session id for use as a plan filename.
   *
   * Plan files are keyed by session id, but the raw id is public SDK input.
   * Strip directory separators and Windows-invalid filename characters so a
   * hostile value cannot escape the plans directory.
   */
  static sanitizePlanSessionId(sessionId) {
    const safeName = path2.basename(sessionId.replace(/\\/g, "/")).replace(/^\.+/g, "_").replace(/[<>:"|?*\x00-\x1F]/g, "_");
    return safeName || "_";
  }
  static resolveRuntimeBaseDir(dir, cwd) {
    if (!dir) {
      return null;
    }
    return _Storage.resolvePath(dir, cwd);
  }
  /**
   * Sets the custom runtime output base directory.
   * Handles tilde (~) expansion and resolves relative paths to absolute.
   * Pass null/undefined/empty string to reset to default (getGlobalQwenDir()).
   * @param dir - The directory path, or null/undefined to reset
   * @param cwd - Base directory for resolving relative paths (defaults to process.cwd()).
   *              Pass the project root so that relative values like ".qwen" resolve
   *              per-project, enabling a single global config to work across all projects.
   */
  static setRuntimeBaseDir(dir, cwd) {
    _Storage.runtimeBaseDir = _Storage.resolveRuntimeBaseDir(dir, cwd);
  }
  /**
   * Runs function execution in an async context with a specific runtime output dir.
   * This is used to isolate runtime output paths between concurrent sessions.
   */
  static runWithRuntimeBaseDir(dir, cwd, fn) {
    const resolved = _Storage.resolveRuntimeBaseDir(dir, cwd);
    return _Storage.runtimeBaseDirContext.run(resolved, fn);
  }
  /**
   * Returns the base directory for all runtime output (temp files, debug logs,
   * session data, todos, insights, etc.).
   *
   * Priority: QWEN_RUNTIME_DIR env var > setRuntimeBaseDir() value > getGlobalQwenDir()
   * @returns Absolute path to the runtime output base directory
   */
  static getRuntimeBaseDir() {
    const envDir = process.env["QWEN_RUNTIME_DIR"];
    if (envDir) {
      return _Storage.resolveRuntimeBaseDir(envDir) ?? _Storage.getGlobalQwenDir();
    }
    const contextualDir = _Storage.runtimeBaseDirContext.getStore();
    if (contextualDir !== void 0) {
      return contextualDir ?? _Storage.getGlobalQwenDir();
    }
    if (_Storage.runtimeBaseDir) {
      return _Storage.runtimeBaseDir;
    }
    return _Storage.getGlobalQwenDir();
  }
  static getGlobalQwenDir() {
    const envDir = process.env["QWEN_HOME"];
    if (envDir) {
      return _Storage.resolvePath(envDir);
    }
    const homeDir = os2.homedir();
    if (!homeDir) {
      return path2.join(os2.tmpdir(), ".qwen");
    }
    return path2.join(homeDir, QWEN_DIR);
  }
  static getMcpOAuthTokensPath() {
    return path2.join(_Storage.getGlobalQwenDir(), "mcp-oauth-tokens.json");
  }
  static getGlobalSettingsPath() {
    return path2.join(_Storage.getGlobalQwenDir(), "settings.json");
  }
  static getInstallationIdPath() {
    return path2.join(_Storage.getGlobalQwenDir(), "installation_id");
  }
  static getGoogleAccountsPath() {
    return path2.join(_Storage.getGlobalQwenDir(), GOOGLE_ACCOUNTS_FILENAME2);
  }
  static getUserCommandsDir() {
    return path2.join(_Storage.getGlobalQwenDir(), "commands");
  }
  static getGlobalMemoryFilePath() {
    return path2.join(_Storage.getGlobalQwenDir(), "memory.md");
  }
  static getGlobalTempDir() {
    return path2.join(_Storage.getRuntimeBaseDir(), TMP_DIR_NAME);
  }
  static getGlobalDebugDir() {
    return path2.join(_Storage.getRuntimeBaseDir(), DEBUG_DIR_NAME);
  }
  static getDebugLogPath(sessionId) {
    return path2.join(_Storage.getGlobalDebugDir(), `${sessionId}.txt`);
  }
  static getGlobalIdeDir() {
    return path2.join(_Storage.getGlobalQwenDir(), IDE_DIR_NAME);
  }
  /**
   * Resolves pathToResolve by realpathing its deepest existing ancestor and
   * appending the not-yet-created remainder.
   */
  static resolvePathThroughExistingAncestor(pathToResolve) {
    let candidate = pathToResolve;
    while (true) {
      try {
        const realCandidate = fs2.realpathSync(candidate);
        const remainder = path2.relative(candidate, pathToResolve);
        return path2.join(realCandidate, remainder);
      } catch (err) {
        if (err.code !== "ENOENT") {
          throw err;
        }
        const parent = path2.dirname(candidate);
        if (parent === candidate) {
          return pathToResolve;
        }
        candidate = parent;
      }
    }
  }
  /**
   * Checks whether {@link childPath} resides within {@link parentPath},
   * resolving symbolic links to prevent traversal bypass attacks.
   */
  static isPathWithinDirectory(childPath, parentPath) {
    const realParent = _Storage.resolvePathThroughExistingAncestor(parentPath);
    const realChild = _Storage.resolvePathThroughExistingAncestor(childPath);
    return isResolvedPathWithinDirectory(realChild, realParent);
  }
  static assertPathWithinDirectory(childPath, parentPath, errorMessage) {
    if (!_Storage.isPathWithinDirectory(childPath, parentPath)) {
      throw new FatalConfigError(errorMessage);
    }
  }
  static getPlansDir(projectRoot, plansDirectory) {
    const configuredPlansDirectory = plansDirectory?.trim();
    if (configuredPlansDirectory) {
      if (!projectRoot) {
        throw new FatalConfigError(
          "projectRoot is required when plansDirectory is configured."
        );
      }
      const resolvedProjectRoot = path2.resolve(projectRoot);
      const resolvedPlansDirectory = _Storage.resolvePath(
        configuredPlansDirectory,
        resolvedProjectRoot
      );
      _Storage.assertPathWithinDirectory(
        resolvedPlansDirectory,
        resolvedProjectRoot,
        `plansDirectory must resolve within the project root.`
      );
      return resolvedPlansDirectory;
    }
    return path2.join(_Storage.getGlobalQwenDir(), PLANS_DIR_NAME);
  }
  static getPlanFilePath(sessionId, projectRoot, plansDirectory) {
    return path2.join(
      _Storage.getPlansDir(projectRoot, plansDirectory),
      `${_Storage.sanitizePlanSessionId(sessionId)}.md`
    );
  }
  static getGlobalBinDir() {
    return path2.join(_Storage.getGlobalQwenDir(), BIN_DIR_NAME);
  }
  static getGlobalArenaDir() {
    return path2.join(_Storage.getGlobalQwenDir(), ARENA_DIR_NAME);
  }
  getQwenDir() {
    return path2.join(this.targetDir, QWEN_DIR);
  }
  getProjectDir() {
    const projectId = sanitizeCwd(this.getProjectRoot());
    const projectsDir = path2.join(
      _Storage.getRuntimeBaseDir(),
      PROJECT_DIR_NAME
    );
    return path2.join(projectsDir, projectId);
  }
  getProjectTempDir() {
    const hash = getProjectHash(this.getProjectRoot());
    const tempDir = _Storage.getGlobalTempDir();
    const targetDir = path2.join(tempDir, hash);
    return targetDir;
  }
  getToolResultsDir() {
    return path2.join(this.getProjectTempDir(), "tool-results");
  }
  ensureProjectTempDirExists() {
    fs2.mkdirSync(this.getProjectTempDir(), { recursive: true });
  }
  static getOAuthCredsPath() {
    return path2.join(_Storage.getGlobalQwenDir(), OAUTH_FILE);
  }
  getProjectRoot() {
    return this.targetDir;
  }
  getWorkspaceSettingsPath() {
    return path2.join(this.getQwenDir(), "settings.json");
  }
  getProjectCommandsDir() {
    return path2.join(this.getQwenDir(), "commands");
  }
  /**
   * Project-level saved-workflow scripts directory: `<targetDir>/.qwen/workflows`.
   * Saved workflow scripts (`<name>.js`) here are surfaced as slash commands
   * and resolvable by `workflow('<name>')` from inside a running workflow.
   */
  getProjectWorkflowsDir() {
    return path2.join(this.getQwenDir(), "workflows");
  }
  /**
   * User-level saved-workflow scripts directory: `~/.qwen/workflows`. User
   * scope is lower-precedence than project scope when the same `<name>.js`
   * exists in both.
   */
  static getUserWorkflowsDir() {
    return path2.join(_Storage.getGlobalQwenDir(), "workflows");
  }
  /**
   * Per-run workflow artifact directory: `<projectDir>/workflows`. Holds
   * completed-run snapshot JSON files (`<runId>.json`) for the `/workflows`
   * recent list, and per-run resume journals (`<runId>/journal.jsonl`).
   */
  getWorkflowRunsDir() {
    return path2.join(this.getProjectDir(), "workflows");
  }
  /**
   * Path to the persisted snapshot of a completed workflow run.
   */
  getWorkflowRunSnapshotPath(runId) {
    return path2.join(this.getWorkflowRunsDir(), `${runId}.json`);
  }
  /**
   * Path to the resume journal for an in-progress / resumable workflow run.
   */
  getWorkflowRunJournalPath(runId) {
    return path2.join(this.getWorkflowRunsDir(), runId, "journal.jsonl");
  }
  /**
   * Path to the runtime-status sidecar JSON for this session.
   *
   * Co-located with the per-session chat log under
   * `<projectDir>/chats/<sessionId>.runtime.json` so external observers
   * (terminal multiplexers, IDE integrations, status daemons) can scan
   * the same directory used for chat history to find live sessions.
   */
  getRuntimeStatusPath(sessionId) {
    return path2.join(
      this.getProjectDir(),
      "chats",
      `${sessionId}.runtime.json`
    );
  }
  getProjectTempCheckpointsDir() {
    return path2.join(this.getProjectTempDir(), "checkpoints");
  }
  getExtensionsDir() {
    return path2.join(this.getQwenDir(), "extensions");
  }
  getExtensionsConfigPath() {
    return path2.join(this.getExtensionsDir(), "qwen-extension.json");
  }
  getUserSkillsDirs() {
    const homeDir = os2.homedir() || os2.tmpdir();
    return SKILL_PROVIDER_CONFIG_DIRS.map(
      (dir) => dir === QWEN_DIR ? path2.join(_Storage.getGlobalQwenDir(), "skills") : path2.join(homeDir, dir, "skills")
    );
  }
  /**
   * Returns the user-level extensions directory (~/.qwen/extensions/).
   * Extensions installed at user scope are stored here, as opposed to
   * project-level extensions which live in <project>/.qwen/extensions/.
   */
  static getUserExtensionsDir() {
    return path2.join(_Storage.getGlobalQwenDir(), "extensions");
  }
  getHistoryFilePath() {
    return path2.join(this.getProjectTempDir(), "shell_history");
  }
};

// packages/core/src/utils/symlink.ts
init_esbuild_shims();
import { promises as fs3 } from "node:fs";
import path3 from "node:path";
async function updateSymlink(linkPath, targetPath, options) {
  const { fallbackCopy = true } = options ?? {};
  const linkDir = path3.dirname(linkPath);
  const relativeTarget = path3.relative(linkDir, targetPath);
  try {
    await fs3.unlink(linkPath);
  } catch {
  }
  try {
    await fs3.symlink(relativeTarget, linkPath);
    return;
  } catch {
  }
  if (fallbackCopy) {
    try {
      await fs3.copyFile(targetPath, linkPath);
    } catch {
    }
  }
}
__name(updateSymlink, "updateSymlink");

// packages/core/src/telemetry/trace-context.ts
init_esbuild_shims();
init_esm();

// packages/core/src/telemetry/session-context.ts
init_esbuild_shims();
var sessionRootContext;
var currentSessionId;
function setSessionContext(ctx, sessionId) {
  sessionRootContext = ctx;
  currentSessionId = sessionId;
}
__name(setSessionContext, "setSessionContext");
function getSessionContext() {
  return sessionRootContext;
}
__name(getSessionContext, "getSessionContext");
function getCurrentSessionId() {
  return currentSessionId;
}
__name(getCurrentSessionId, "getCurrentSessionId");

// packages/core/src/telemetry/trace-context.ts
function extractTraceContext(span) {
  const ctx = span?.spanContext();
  if (ctx && isSpanContextValid(ctx)) {
    return {
      traceId: ctx.traceId,
      spanId: ctx.spanId,
      traceFlags: ctx.traceFlags
    };
  }
  return null;
}
__name(extractTraceContext, "extractTraceContext");
function getActiveSpanTraceContext() {
  try {
    return extractTraceContext(trace.getActiveSpan());
  } catch {
    return null;
  }
}
__name(getActiveSpanTraceContext, "getActiveSpanTraceContext");
function getSessionRootTraceContext() {
  try {
    const sessionCtx = getSessionContext();
    return extractTraceContext(
      sessionCtx ? trace.getSpan(sessionCtx) : void 0
    );
  } catch {
    return null;
  }
}
__name(getSessionRootTraceContext, "getSessionRootTraceContext");
function getTraceContext() {
  return getActiveSpanTraceContext() ?? getSessionRootTraceContext();
}
__name(getTraceContext, "getTraceContext");
function formatTraceparent(ctx) {
  const flags = (ctx.traceFlags & 255).toString(16).padStart(2, "0");
  return `00-${ctx.traceId}-${ctx.spanId}-${flags}`;
}
__name(formatTraceparent, "formatTraceparent");
var shellTracePropagationEnabled = false;
function setShellTracePropagation(enabled) {
  shellTracePropagationEnabled = enabled;
}
__name(setShellTracePropagation, "setShellTracePropagation");
function isShellTracePropagationEnabled() {
  return shellTracePropagationEnabled;
}
__name(isShellTracePropagationEnabled, "isShellTracePropagationEnabled");

// packages/core/src/utils/debugLogger.ts
init_esbuild_shims();
import { promises as fs4 } from "node:fs";
import path4 from "node:path";
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
import util from "node:util";
var ensureDebugDirPromise = null;
var ensuredDebugDirPath = null;
var hasWriteFailure = false;
var globalSession = null;
var sessionContext = new AsyncLocalStorage2();
function isDebugLogFileEnabled() {
  const value = process.env["QWEN_DEBUG_LOG_FILE"];
  if (!value) return false;
  const normalized = value.trim().toLowerCase();
  return !["", "0", "false", "off", "no"].includes(normalized);
}
__name(isDebugLogFileEnabled, "isDebugLogFileEnabled");
function getActiveSession() {
  return sessionContext.getStore() ?? globalSession;
}
__name(getActiveSession, "getActiveSession");
function ensureDebugDirExists() {
  const debugDirPath = Storage.getGlobalDebugDir();
  if (!ensureDebugDirPromise || ensuredDebugDirPath !== debugDirPath) {
    ensuredDebugDirPath = debugDirPath;
    ensureDebugDirPromise = fs4.mkdir(debugDirPath, { recursive: true }).then(() => void 0).catch(() => {
      hasWriteFailure = true;
      ensureDebugDirPromise = null;
      ensuredDebugDirPath = null;
    });
  }
  return ensureDebugDirPromise ?? Promise.resolve();
}
__name(ensureDebugDirExists, "ensureDebugDirExists");
function formatArgs(args) {
  return args.map((arg) => {
    if (arg instanceof Error) {
      return arg.stack ?? `${arg.name}: ${arg.message}`;
    }
    return arg;
  }).map((arg) => typeof arg === "string" ? arg : util.inspect(arg)).join(" ");
}
__name(formatArgs, "formatArgs");
function buildLogLine(level, message, tag, traceCtx) {
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const tagPart = tag ? ` [${tag}]` : "";
  const tracePart = traceCtx ? ` [trace_id=${traceCtx.traceId} span_id=${traceCtx.spanId}]` : "";
  return `${timestamp} [${level}]${tagPart}${tracePart} ${message}
`;
}
__name(buildLogLine, "buildLogLine");
function writeLog(session, level, tag, args) {
  if (!isDebugLogFileEnabled()) {
    return;
  }
  const sessionId = session.getSessionId();
  const logFilePath = Storage.getDebugLogPath(sessionId);
  const message = formatArgs(args);
  const traceCtx = getTraceContext();
  const line = buildLogLine(level, message, tag, traceCtx);
  void ensureDebugDirExists().then(() => fs4.appendFile(logFilePath, line, "utf8")).catch(() => {
    hasWriteFailure = true;
  });
}
__name(writeLog, "writeLog");
function isDebugLoggingDegraded() {
  return hasWriteFailure;
}
__name(isDebugLoggingDegraded, "isDebugLoggingDegraded");
function resetDebugLoggingState() {
  hasWriteFailure = false;
  ensureDebugDirPromise = null;
  ensuredDebugDirPath = null;
}
__name(resetDebugLoggingState, "resetDebugLoggingState");
var DEBUG_LATEST_ALIAS = "latest";
function updateLatestDebugLogAlias(sessionId) {
  if (!isDebugLogFileEnabled()) {
    return;
  }
  const aliasPath = path4.join(Storage.getGlobalDebugDir(), DEBUG_LATEST_ALIAS);
  const targetPath = Storage.getDebugLogPath(sessionId);
  void ensureDebugDirExists().then(() => updateSymlink(aliasPath, targetPath, { fallbackCopy: false })).catch(() => {
  });
}
__name(updateLatestDebugLogAlias, "updateLatestDebugLogAlias");
function setDebugLogSession(session) {
  globalSession = session ?? null;
  if (session) {
    updateLatestDebugLogAlias(session.getSessionId());
  }
}
__name(setDebugLogSession, "setDebugLogSession");
function runWithDebugLogSession(session, fn) {
  return sessionContext.run(session, fn);
}
__name(runWithDebugLogSession, "runWithDebugLogSession");
function createDebugLogger(tag) {
  return {
    isEnabled: /* @__PURE__ */ __name(() => getActiveSession() !== null, "isEnabled"),
    debug: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session) return;
      writeLog(session, "DEBUG", tag, args);
    }, "debug"),
    info: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session) return;
      writeLog(session, "INFO", tag, args);
    }, "info"),
    warn: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session) return;
      writeLog(session, "WARN", tag, args);
    }, "warn"),
    error: /* @__PURE__ */ __name((...args) => {
      const session = getActiveSession();
      if (!session) return;
      writeLog(session, "ERROR", tag, args);
    }, "error")
  };
}
__name(createDebugLogger, "createDebugLogger");

export {
  isNodeError,
  isAbortError,
  getErrorMessage,
  getErrorStatus,
  getErrorType,
  FatalError,
  FatalAuthenticationError,
  FatalInputError,
  FatalSandboxError,
  FatalConfigError,
  FatalTurnLimitedError,
  FatalToolExecutionError,
  FatalBudgetExceededError,
  FatalCancellationError,
  ForbiddenError,
  UnauthorizedError,
  BadRequestError,
  toFriendlyError,
  QWEN_DIR,
  GOOGLE_ACCOUNTS_FILENAME,
  _resetValidatePathCacheForTest,
  SHELL_SPECIAL_CHARS,
  PATH_ARG_KEYS,
  tildeifyPath,
  expandHomeDir,
  shortenPath,
  makeRelative,
  escapePath,
  unescapePath,
  getProjectHash,
  sanitizeCwd,
  isSubpath,
  isSubpaths,
  resolvePath,
  validatePath,
  resolveAndValidatePath,
  SKILL_PROVIDER_CONFIG_DIRS,
  Storage,
  updateSymlink,
  setSessionContext,
  getCurrentSessionId,
  getActiveSpanTraceContext,
  getTraceContext,
  formatTraceparent,
  setShellTracePropagation,
  isShellTracePropagationEnabled,
  isDebugLoggingDegraded,
  resetDebugLoggingState,
  setDebugLogSession,
  runWithDebugLogSession,
  createDebugLogger
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Code
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
