// Force strict mode and setup for ESM
"use strict";
import {
  DEFAULT_DARK_THEME_NAME,
  DEFAULT_LIGHT_THEME_NAME
} from "./chunk-RKUWKYED.js";
import {
  SUPPORTED_LANGUAGES,
  detectSystemLanguage,
  getLanguageNameFromLocale,
  getLanguageSettingsOptions,
  t
} from "./chunk-W7RFHI5L.js";
import {
  getHomeEnvFallbackVars,
  loadEnvironment,
  preResolveHomeEnvOverrides
} from "./chunk-ENW2BPUW.js";
import {
  CONSOLIDATED_DISABLE_KEYS,
  V1_INDICATOR_KEYS,
  V1_TO_V2_MIGRATION_MAP,
  V1_TO_V2_PRESERVE_DISABLE_MAP,
  V2_CONTAINER_KEYS,
  resolveEnvVarsInObject
} from "./chunk-GOXKNSDZ.js";
import {
  getSystemDefaultsPath,
  getSystemSettingsPath
} from "./chunk-IDS7MSUP.js";
import {
  ENV_CORRUPTED_PATH,
  ENV_WAS_RECOVERED
} from "./chunk-QRUIS3DN.js";
import {
  isWorkspaceTrusted,
  updateSettingsFilePreservingFormat
} from "./chunk-FXXY6GR5.js";
import {
  require_strip_json_comments
} from "./chunk-ALGGS7UH.js";
import {
  DEFAULT_MAX_SUBAGENT_DEPTH,
  DEFAULT_MAX_TOOL_CALLS_PER_TURN,
  DEFAULT_STOP_HOOK_BLOCK_CAP,
  DEFAULT_TOOL_OUTPUT_BATCH_BUDGET,
  DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD,
  DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,
  DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
  stripRuntimeSnapshotPrefix
} from "./chunk-KN5EBZLT.js";
import {
  DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES
} from "./chunk-L5U3ELZX.js";
import {
  DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH,
  SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT
} from "./chunk-D5K5YBSN.js";
import {
  FatalConfigError,
  Storage,
  createDebugLogger,
  getErrorMessage
} from "./chunk-7NFB7LBQ.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name,
  __toESM
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/config/settings.ts
init_esbuild_shims();
import * as fs3 from "node:fs";
import * as path2 from "node:path";
import { homedir } from "node:os";
import process from "node:process";
var import_strip_json_comments = __toESM(require_strip_json_comments(), 1);

// packages/cli/src/config/modelProvidersScope.ts
init_esbuild_shims();
function hasOwnModelProviders(settingsObj) {
  if (!settingsObj || typeof settingsObj !== "object") {
    return false;
  }
  const obj = settingsObj;
  return Object.prototype.hasOwnProperty.call(obj, "modelProviders");
}
__name(hasOwnModelProviders, "hasOwnModelProviders");
function getModelProvidersOwnerScope(settings) {
  if (settings.isTrusted && hasOwnModelProviders(settings.workspace.settings)) {
    return "Workspace" /* Workspace */;
  }
  if (hasOwnModelProviders(settings.user.settings)) {
    return "User" /* User */;
  }
  return void 0;
}
__name(getModelProvidersOwnerScope, "getModelProvidersOwnerScope");
function getPersistScopeForModelSelection(settings) {
  return getModelProvidersOwnerScope(settings) ?? "User" /* User */;
}
__name(getPersistScopeForModelSelection, "getPersistScopeForModelSelection");
function getWritableScopes(settings) {
  return settings.isTrusted ? ["Workspace" /* Workspace */, "User" /* User */] : ["User" /* User */];
}
__name(getWritableScopes, "getWritableScopes");
function getOwnKeyScope(settings, key) {
  for (const scope of getWritableScopes(settings)) {
    const obj = settings.forScope(scope).settings;
    if (Object.prototype.hasOwnProperty.call(obj, key)) return scope;
  }
  return void 0;
}
__name(getOwnKeyScope, "getOwnKeyScope");

// packages/cli/src/config/settingsSchema.ts
init_esbuild_shims();
var TOGGLE_TYPES = /* @__PURE__ */ new Set([
  "boolean",
  "enum"
]);
var HOOK_DEFINITION_ITEMS = {
  type: "object",
  description: "A hook definition with an optional matcher and a list of hook configurations.",
  properties: {
    matcher: {
      type: "string",
      description: "An optional matcher pattern to filter when this hook definition applies."
    },
    sequential: {
      type: "boolean",
      description: "Whether the hooks should be executed sequentially instead of in parallel."
    },
    hooks: {
      type: "array",
      description: "The list of hook configurations to execute.",
      required: true,
      items: {
        type: "object",
        description: "A hook configuration entry that defines a hook to execute.",
        properties: {
          type: {
            type: "string",
            description: 'The type of hook. Note: "function" type is only available via SDK registration, not settings.json.',
            enum: ["command", "http"],
            required: true
          },
          command: {
            type: "string",
            description: 'The command to execute when the hook is triggered. Required for "command" type.'
          },
          url: {
            type: "string",
            description: 'The URL to send the POST request to. Required for "http" type.'
          },
          headers: {
            type: "object",
            description: "HTTP headers to include in the request. Supports env var interpolation ($VAR, ${VAR}).",
            additionalProperties: { type: "string" }
          },
          allowedEnvVars: {
            type: "array",
            description: "List of environment variables allowed for interpolation in headers and URL.",
            items: { type: "string" }
          },
          name: {
            type: "string",
            description: "An optional name for the hook."
          },
          description: {
            type: "string",
            description: "An optional description of what the hook does."
          },
          timeout: {
            type: "number",
            description: "Timeout in seconds for the hook execution."
          },
          env: {
            type: "object",
            description: "Environment variables to set when executing the hook command.",
            additionalProperties: { type: "string" }
          },
          async: {
            type: "boolean",
            description: 'Whether to execute the hook asynchronously (non-blocking, for "command" type only).'
          },
          once: {
            type: "boolean",
            description: 'Whether to execute the hook only once per session (for "http" type).'
          },
          statusMessage: {
            type: "string",
            description: "A message to display while the hook is executing."
          },
          shell: {
            type: "string",
            description: "The shell to use for command execution.",
            enum: ["bash", "powershell"]
          }
        }
      }
    }
  }
};
var SETTINGS_SCHEMA = {
  // Maintained for compatibility/criticality
  mcpServers: {
    type: "object",
    label: "MCP Servers",
    category: "Advanced",
    // Hot-reloadable (sub-task 3): a runtime edit is reconciled live by the
    // SettingsWatcher → reinitializeMcpServers path. Marking it
    // restart-required would make the watcher suppress MCP-only edits, so the
    // listener that drives the reconcile would never fire.
    requiresRestart: false,
    default: {},
    description: "Configuration for MCP servers.",
    showInDialog: false,
    mergeStrategy: "shallow_merge" /* SHALLOW_MERGE */
  },
  // Channels configuration (Telegram, Discord, etc.)
  channels: {
    type: "object",
    label: "Channels",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for messaging channels.",
    showInDialog: false,
    mergeStrategy: "shallow_merge" /* SHALLOW_MERGE */
  },
  // Model providers configuration grouped by authType
  modelProviders: {
    type: "object",
    label: "Model Providers",
    category: "Model",
    requiresRestart: false,
    default: {},
    description: 'Model providers configuration keyed by provider id (a built-in AuthType such as "openai" or "gemini", or a custom id mapped via providerProtocol). Each entry is an array of model configurations.',
    showInDialog: false,
    mergeStrategy: "replace" /* REPLACE */
  },
  // Maps a custom modelProviders provider id to its SDK protocol (AuthType).
  providerProtocol: {
    type: "object",
    label: "Provider Protocols",
    category: "Model",
    requiresRestart: true,
    default: {},
    description: 'Maps a custom modelProviders provider id to the SDK protocol that routes its requests (e.g. {"idealab": "openai"}). Lets a custom provider id reuse a built-in protocol. Built-in provider ids (openai, gemini, anthropic, vertex-ai, qwen-oauth) are routed automatically and need no entry.',
    showInDialog: false,
    mergeStrategy: "replace" /* REPLACE */
  },
  plansDirectory: {
    type: "string",
    label: "Plans Directory",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Custom directory for approved Plan Mode files. Relative paths are resolved from the project root, and the resolved path must stay within the project root. Defaults to ~/.qwen/plans.",
    showInDialog: false
  },
  // Environment variables fallback
  env: {
    type: "object",
    label: "Environment Variables",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Environment variables to set as fallback defaults. These are loaded with the lowest priority: system environment variables > .env files > settings.json env field.",
    showInDialog: false,
    mergeStrategy: "shallow_merge" /* SHALLOW_MERGE */
  },
  proxy: {
    type: "string",
    label: "Proxy",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Proxy URL for CLI HTTP requests. Takes precedence over proxy environment variables when --proxy is not provided.",
    showInDialog: false
  },
  general: {
    type: "object",
    label: "General",
    category: "General",
    requiresRestart: false,
    default: {},
    description: "General application settings.",
    showInDialog: false,
    properties: {
      preferredEditor: {
        type: "string",
        label: "Preferred Editor",
        category: "General",
        requiresRestart: false,
        default: void 0,
        description: "The preferred editor to open files in.",
        showInDialog: true
      },
      vimMode: {
        type: "boolean",
        label: "Vim Mode",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable Vim keybindings",
        showInDialog: true
      },
      voice: {
        type: "object",
        label: "Voice Dictation",
        category: "General",
        requiresRestart: false,
        default: {},
        description: "Voice dictation settings.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Voice Dictation",
            category: "General",
            requiresRestart: false,
            default: false,
            description: "Enable voice dictation in the prompt input.",
            showInDialog: false
          },
          mode: {
            type: "enum",
            label: "Voice Dictation Mode",
            category: "General",
            requiresRestart: false,
            default: "hold",
            description: 'How push-to-talk behaves: "hold" to talk while held, or "tap" to start and tap (or pause) to stop and submit.',
            showInDialog: false,
            options: [
              { value: "hold", label: "Hold to talk" },
              { value: "tap", label: "Tap to toggle" }
            ]
          },
          language: {
            type: "string",
            label: "Voice Dictation Language",
            category: "General",
            requiresRestart: false,
            default: "",
            description: 'Preferred spoken language for voice transcription (e.g. "english", "chinese"). Leave empty to auto-detect.',
            showInDialog: false
          },
          keytermsFile: {
            type: "string",
            label: "Voice Dictation Keyterms File",
            category: "General",
            requiresRestart: false,
            default: "",
            description: 'Path to a custom keyterms file (one term per line, "#" for comments) that biases voice transcription toward domain-specific terms. Relative paths resolve from the workspace root; defaults to ".qwen/voice-keyterms.txt" when present. The file contents are sent to the ASR provider and it is read only in trusted workspaces. Only applies to Qwen ASR models (qwen3-asr-*).',
            showInDialog: false
          },
          refineTranscript: {
            type: "boolean",
            label: "Refine Voice Transcript",
            category: "General",
            requiresRestart: false,
            default: true,
            description: "Clean up voice transcripts with the fast model before inserting them \u2014 removes filler words and fixes recognition errors while preserving meaning. Falls back to the raw transcript on failure, and is skipped when no fast model is configured.",
            showInDialog: false
          }
        }
      },
      enableAutoUpdate: {
        type: "boolean",
        label: "Enable Auto Update",
        category: "General",
        requiresRestart: false,
        default: true,
        description: "Enable automatic update checks and installations on startup.",
        showInDialog: true
      },
      showSessionRecap: {
        type: "boolean",
        label: "Show Session Recap",
        category: "General",
        requiresRestart: false,
        // Off by default — an ambient background LLM call isn't something
        // users should be opted into silently, especially when `fastModel`
        // is unset and the call would land on the main coding model.
        // Manual `/recap` works regardless.
        default: false,
        description: 'Auto-show a one-line "where you left off" recap when returning to the terminal after being away. Off by default. Use /recap to trigger manually regardless of this setting.',
        showInDialog: true
      },
      sessionRecapAwayThresholdMinutes: {
        type: "number",
        label: "Session Recap Away Threshold (minutes)",
        category: "General",
        requiresRestart: false,
        default: 5,
        minimum: 1,
        description: "How many minutes the terminal must be blurred before an auto-recap fires on the next focus-in. Matches Claude Code's default of 5 minutes; raise if you briefly alt-tab and do not want recaps to pile up.",
        showInDialog: true
      },
      cleanupPeriodDays: {
        type: "number",
        label: "Cleanup Period (days)",
        category: "General",
        // LoadedSettings._merged is cached without verified setValue→recompute
        // paths in all UI flows. Mark restart-required so users aren't
        // surprised when a mid-session edit doesn't take effect immediately.
        requiresRestart: true,
        default: 30,
        minimum: 0,
        description: "Number of days to retain ~/.qwen/file-history/ session backups used by /rewind and background subagent transcripts under <projectDir>/subagents/. Data older than this is removed by a background housekeeping pass that runs at most once per day. Set to 0 for minimum retention (~1 hour) \u2014 protects sessions touched in the last hour, plus the currently active session.",
        showInDialog: true
      },
      gitCoAuthor: {
        type: "object",
        label: "Attribution",
        category: "General",
        requiresRestart: false,
        // Match `normalizeGitCoAuthor`'s runtime defaults so the IDE
        // schema publishes the same "enabled by default" hint users see
        // at runtime. The empty-object form here would silently lose
        // editor-surfaced defaults.
        default: { commit: true, pr: true },
        description: "Attribution added to git commits and pull requests created through Qwen Code.",
        showInDialog: false,
        // Pre-V4 settings stored this as a single boolean. The V3→V4
        // migration rewrites those on first launch, but the IDE schema
        // validator runs before that — accept the boolean shape so users
        // editing settings.json in VS Code don't see a spurious warning
        // until they run qwen once. Config.normalizeGitCoAuthor handles
        // the boolean at runtime.
        legacyTypes: ["boolean"],
        properties: {
          commit: {
            type: "boolean",
            label: "Attribution: commit",
            category: "General",
            requiresRestart: false,
            default: true,
            description: "Add a Co-authored-by trailer to git commit messages AND attach a per-file AI-attribution git note (`refs/notes/ai-attribution`) for commits made through Qwen Code. Disabling skips both.",
            showInDialog: true
          },
          pr: {
            type: "boolean",
            label: "Attribution: PR",
            category: "General",
            requiresRestart: false,
            default: true,
            description: "Append a Qwen Code attribution line to PR descriptions when running `gh pr create`.",
            showInDialog: true
          }
        }
      },
      debugKeystrokeLogging: {
        type: "boolean",
        label: "Debug Keystroke Logging",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable debug logging of keystrokes to the console.",
        showInDialog: false
      },
      language: {
        type: "enum",
        label: "Language: UI",
        category: "General",
        requiresRestart: true,
        default: "auto",
        description: 'The language for the user interface. Use "auto" to detect from system settings. You can also use custom language codes (e.g., "es", "fr") by placing JS language files in ~/.qwen/locales/ (e.g., ~/.qwen/locales/es.js).',
        showInDialog: true,
        options: []
      },
      outputLanguage: {
        type: "string",
        label: "Language: Model",
        category: "General",
        requiresRestart: true,
        default: "auto",
        description: 'The language for LLM output. Use "auto" to detect from system settings, or set a specific language.',
        showInDialog: true
      },
      dynamicCommandTranslation: {
        type: "boolean",
        label: "Language: Dynamic Command Translation",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable AI translation for dynamic slash command descriptions. When disabled, dynamic commands use their original descriptions and do not trigger translation model calls.",
        showInDialog: true
      },
      terminalBell: {
        type: "boolean",
        label: "Terminal Bell Notification",
        category: "General",
        requiresRestart: false,
        default: true,
        description: "Play terminal bell sound when response completes or needs approval.",
        showInDialog: true
      },
      notificationMode: {
        type: "enum",
        label: "Notification Mode",
        category: "General",
        requiresRestart: false,
        default: "all",
        description: 'Which unfocused-terminal events fire a bell/OS notification. "all" fires on every tool approval prompt AND on task completion (current behavior). "task-complete" suppresses the per-approval notification and only fires when a long task returns to idle. Requires `terminalBell` to be enabled; otherwise no notifications fire regardless of mode.',
        showInDialog: true,
        options: [
          { value: "all", label: "All (approvals + task completion)" },
          { value: "task-complete", label: "Task completion only" }
        ]
      },
      preventSystemSleep: {
        type: "boolean",
        label: "Prevent System Sleep While Running",
        category: "General",
        // Read once at startup via Config.preventSystemSleep (a readonly field
        // captured in loadCliConfig), so a runtime toggle only takes effect
        // after restart.
        requiresRestart: true,
        default: true,
        description: "Prevent the system from sleeping while Qwen Code is streaming a model response or executing tools. Idle prompt time and permission prompts do not inhibit sleep.",
        showInDialog: true
      },
      chatRecording: {
        type: "boolean",
        label: "Chat Recording",
        category: "General",
        requiresRestart: true,
        default: true,
        description: "Enable saving chat history to disk. Disabling this will also prevent --continue and --resume from working.",
        showInDialog: false
      },
      defaultFileEncoding: {
        type: "enum",
        label: "Default File Encoding",
        category: "General",
        requiresRestart: false,
        default: "utf-8",
        description: 'Default encoding for new files. Use "utf-8" (default) for UTF-8 without BOM, or "utf-8-bom" for UTF-8 with BOM. Only change this if your project specifically requires BOM.',
        showInDialog: false,
        options: [
          { value: "utf-8", label: "UTF-8 (without BOM)" },
          { value: "utf-8-bom", label: "UTF-8 with BOM" }
        ]
      }
    }
  },
  output: {
    type: "object",
    label: "Output",
    category: "General",
    requiresRestart: false,
    default: {},
    description: "Settings for the CLI output.",
    showInDialog: false,
    properties: {
      format: {
        type: "enum",
        label: "Output Format",
        category: "General",
        requiresRestart: false,
        default: "text",
        description: "The format of the CLI output.",
        showInDialog: false,
        options: [
          { value: "text", label: "Text" },
          { value: "json", label: "JSON" }
        ]
      },
      showTimestamps: {
        type: "boolean",
        label: "Show Timestamps",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Show [HH:MM:SS] timestamp before each assistant response.",
        showInDialog: true
      }
    }
  },
  dualOutput: {
    type: "object",
    label: "Dual Output",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Dual-output sidecar mode: emit structured JSON events to a second channel while the TUI renders normally on stdout. See docs/users/features/dual-output.md. CLI flags take precedence over these settings.",
    showInDialog: false,
    properties: {
      jsonFile: {
        type: "string",
        label: "JSON Event File",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "File path for structured JSON event output. Equivalent to --json-file. Ignored if --json-fd or --json-file is also set.",
        showInDialog: false
      },
      inputFile: {
        type: "string",
        label: "Remote Input File",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "File path for remote input commands (JSONL). Equivalent to --input-file. Ignored if --input-file is also set.",
        showInDialog: false
      }
    }
  },
  ui: {
    type: "object",
    label: "UI",
    category: "UI",
    requiresRestart: false,
    default: {},
    description: "User interface settings.",
    showInDialog: false,
    properties: {
      theme: {
        type: "string",
        label: "Theme",
        category: "UI",
        requiresRestart: false,
        default: "Qwen Dark",
        description: "The color theme for the UI.",
        showInDialog: true
      },
      autoModeAcknowledged: {
        type: "boolean",
        label: "Auto Mode Acknowledged",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "True once the user has seen the first-time information message about the AUTO approval mode. Set automatically; not intended for manual configuration.",
        showInDialog: false
      },
      statusLine: {
        type: "object",
        label: "Status Line",
        category: "UI",
        requiresRestart: false,
        default: void 0,
        description: 'Status line display configuration. Use `type: "preset"` with built-in item ids, or `type: "command"` with a shell command. Optional command `refreshInterval` (seconds, >= 1) re-runs the command on a timer so external data stays fresh. Set `respectUserColors: true` to preserve ANSI color codes in command output instead of applying dim/theme styling. Set `hideContextIndicator: true` to hide the built-in context usage indicator in the footer right section. When unset (default), the built-in default preset (model, git branch, context usage, current dir) is shown automatically; set to `null` to explicitly disable the status line.',
        showInDialog: false
      },
      customThemes: {
        type: "object",
        label: "Custom Themes",
        category: "UI",
        requiresRestart: false,
        default: {},
        description: "Custom theme definitions.",
        showInDialog: false
      },
      hideBuiltinWorktreeIndicator: {
        type: "boolean",
        label: "Hide Built-in Worktree Indicator",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "When true, the built-in `\u2387 worktree-<branch> (<slug>)` line in the Footer is hidden. The worktree state is still surfaced to custom statusline scripts via the stdin payload (`worktree.{name, path, branch, original_cwd, original_branch}`). Keep at the default `false` unless your custom statusline renders the worktree itself \u2014 otherwise an active worktree silently has no UI affordance.",
        showInDialog: false
      },
      hideWindowTitle: {
        type: "boolean",
        label: "Hide Window Title",
        category: "UI",
        requiresRestart: true,
        default: false,
        description: "Hide the window title bar",
        showInDialog: false
      },
      disableWorkflowKeywordTrigger: {
        type: "boolean",
        label: "Disable Workflow Keyword Trigger",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "When true, mentioning the word `workflow` in a prompt no longer softly steers the turn toward the Workflow tool (and the Footer `workflow active` indicator is suppressed). Only applies when workflows are enabled.",
        showInDialog: true
      },
      showStatusInTitle: {
        type: "boolean",
        label: "Show Status in Title",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show Qwen Code session name and status in the terminal window title",
        showInDialog: true
      },
      hideTips: {
        type: "boolean",
        label: "Hide Tips",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide helpful tips in the UI",
        showInDialog: true
      },
      history: {
        type: "object",
        label: "History",
        category: "UI",
        requiresRestart: false,
        default: {},
        description: "History display settings.",
        showInDialog: false,
        properties: {
          collapseOnResume: {
            type: "boolean",
            label: "Collapse On Resume",
            category: "UI",
            requiresRestart: false,
            default: false,
            description: "Whether to collapse history by default when resuming a session.",
            showInDialog: false
          },
          collapsePreviewCount: {
            type: "number",
            label: "Collapse Preview Count",
            category: "UI",
            requiresRestart: false,
            default: 0,
            description: "Number of most recent user turns to keep visible when collapsing history on resume. 0 collapses all restored history by default; -1 shows all restored history.",
            showInDialog: false
          }
        }
      },
      showLineNumbers: {
        type: "boolean",
        label: "Show Line Numbers in Code",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show line numbers in the code output.",
        showInDialog: true
      },
      renderMode: {
        type: "enum",
        label: "Markdown Render Mode",
        category: "UI",
        requiresRestart: false,
        default: "render",
        description: 'Default Markdown display mode. Use "render" for rich visual previews, or "raw" to show source-oriented Markdown by default. Toggle during a session with Alt/Option+M; on macOS the terminal must send Option as Meta.',
        showInDialog: true,
        options: [
          { value: "render", label: "Render visual previews" },
          { value: "raw", label: "Show raw source" }
        ]
      },
      showCitations: {
        type: "boolean",
        label: "Show Citations",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show citations for generated text in the chat.",
        showInDialog: false
      },
      customWittyPhrases: {
        type: "array",
        label: "Custom Witty Phrases",
        category: "UI",
        requiresRestart: false,
        default: [],
        description: "Custom witty phrases to display during loading.",
        showInDialog: false
      },
      showResponseTokensPerSecond: {
        type: "boolean",
        label: "Show Response Tokens Per Second",
        category: "UI",
        requiresRestart: true,
        default: false,
        description: "Show a live tokens/sec estimate next to the response token counter while the model is streaming. Takes effect in the next session.",
        showInDialog: true
      },
      enableWelcomeBack: {
        type: "boolean",
        label: "Show Welcome Back Dialog",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: 'Show welcome back dialog when returning to a project with conversation history. Choosing "Start new chat session" suppresses the dialog for that project until the project summary changes.',
        showInDialog: true
      },
      enableUserFeedback: {
        type: "boolean",
        label: "Enable User Feedback",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show optional feedback dialog after conversations to help improve Qwen performance.",
        showInDialog: true
      },
      enableFollowupSuggestions: {
        type: "boolean",
        label: "Enable Follow-up Suggestions",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show context-aware follow-up suggestions after task completion. Press Tab, Right Arrow, or Enter to accept into the input buffer.",
        showInDialog: true
      },
      enableCacheSharing: {
        type: "boolean",
        label: "Enable Cache Sharing for Suggestions",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Use cache-aware forked queries for suggestion generation. Reduces cost on providers that support prefix caching (experimental).",
        showInDialog: false
      },
      enableSpeculation: {
        type: "boolean",
        label: "Enable Speculative Execution",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Speculatively execute accepted suggestions before submission. Results appear instantly when you accept (experimental).",
        showInDialog: false
      },
      accessibility: {
        type: "object",
        label: "Accessibility",
        category: "UI",
        requiresRestart: true,
        default: {},
        description: "Accessibility settings.",
        showInDialog: false,
        properties: {
          enableLoadingPhrases: {
            type: "boolean",
            label: "Enable Loading Phrases",
            category: "UI",
            requiresRestart: true,
            default: true,
            description: "Enable loading phrases (disable for accessibility)",
            showInDialog: true
          },
          screenReader: {
            type: "boolean",
            label: "Screen Reader Mode",
            category: "UI",
            requiresRestart: true,
            default: void 0,
            description: "Render output in plain-text to be more screen reader accessible",
            showInDialog: false
          }
        }
      },
      feedbackLastShownTimestamp: {
        type: "number",
        label: "Feedback Last Shown Timestamp",
        category: "UI",
        requiresRestart: false,
        default: 0,
        description: "The last time the feedback dialog was shown.",
        showInDialog: false
      },
      compactMode: {
        type: "boolean",
        label: "Compact Mode",
        category: "UI",
        requiresRestart: false,
        default: false,
        // Retired from the TUI (compact tool output is now always-on there, and
        // Ctrl+O opens the transcript instead of toggling this). Kept as a
        // hidden, schema-only setting so the web shell's independent compact
        // toggle can still persist via the daemon settings routes (mirrors
        // `voiceModel`). Not shown in the TUI settings dialog.
        description: "Compact view (web shell only; not used by the TUI).",
        showInDialog: false
      },
      useTerminalBuffer: {
        type: "boolean",
        label: "Virtualized History (reduces flicker on long sessions)",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Render conversation history in an in-app scrollable viewport instead of the terminal scrollback buffer. Recommended if you see flicker, scroll-storm, or interface freeze on long sessions, after Ctrl+O, after Ctrl+E / Ctrl+F (expand), after window resize, or when alt-tabbing back. Scroll with Shift+\u2191/\u2193 (line), PgUp/PgDn (page), Ctrl+Home/End (top/bottom), or the mouse wheel. Also enables mouse interactions: click an option in a menu/dialog to select it, hover to highlight it, and click in the prompt to position the cursor. Does NOT use the host terminal scrollback while enabled; for native text selection, hold Shift (or Option on macOS) while dragging.",
        showInDialog: true
      },
      showScrollbar: {
        type: "boolean",
        label: "Show Scrollbar (Virtualized History)",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show the auto-hiding scrollbar in the in-app scrollable viewport (Virtualized History). The bar appears while scrolling and fades out when idle. Disable to hide it entirely.",
        showInDialog: true
      },
      shellOutputMaxLines: {
        type: "number",
        label: "Shell Output Max Lines",
        category: "UI",
        requiresRestart: false,
        default: 5,
        description: "Max number of shell output lines shown inline. Set to 0 to disable the cap and show full output. The hidden line count is still surfaced via the `+N lines` indicator.",
        showInDialog: true
      },
      hideBanner: {
        type: "boolean",
        label: "Hide Banner",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide the startup ASCII banner and info panel.",
        showInDialog: true
      },
      customBannerTitle: {
        type: "string",
        label: "Custom Banner Title",
        category: "UI",
        requiresRestart: false,
        default: "",
        description: 'Replace the default ">_ Qwen Code" title shown in the banner info panel. The version suffix is always appended.',
        showInDialog: false
      },
      customBannerSubtitle: {
        type: "string",
        label: "Custom Banner Subtitle",
        category: "UI",
        requiresRestart: false,
        default: "",
        description: "Optional subtitle line rendered between the banner title and the auth/model line. When unset, the info panel keeps its blank spacer row.",
        showInDialog: false
      },
      customAsciiArt: {
        type: "object",
        label: "Custom ASCII Art",
        category: "UI",
        requiresRestart: false,
        default: void 0,
        description: 'Replace the default QWEN ASCII art. Accepts an inline string, {"path": "..."}, or {"small": ..., "large": ...} for width-aware selection.',
        showInDialog: false,
        // The runtime accepts three shapes (inline string, {path}, or
        // {small,large} where each tier is itself string-or-{path}). The
        // SettingDefinition `type: 'object'` keeps the in-app dialog out of
        // the way (we don't want a multi-line ASCII editor in the TUI), but
        // the JSON Schema needs a real union so VS Code stops flagging the
        // documented bare-string form.
        // The `oneOf` here uses three *mutually exclusive* branches rather
        // than one permissive object branch, so VS Code rejects nonsense
        // like `{ path, small, large }` (which the runtime would also
        // reject — see `normalizeTiers` in `customBanner.ts`).
        jsonSchemaOverride: {
          oneOf: [
            { type: "string" },
            // Bare `{path}` — no tier keys allowed.
            {
              type: "object",
              properties: { path: { type: "string" } },
              required: ["path"],
              additionalProperties: false
            },
            // Width-aware `{small?, large?}` — `path` not allowed at this
            // level; each tier is itself string-or-`{path}`.
            {
              type: "object",
              properties: {
                small: {
                  oneOf: [
                    { type: "string" },
                    {
                      type: "object",
                      properties: { path: { type: "string" } },
                      required: ["path"],
                      additionalProperties: false
                    }
                  ]
                },
                large: {
                  oneOf: [
                    { type: "string" },
                    {
                      type: "object",
                      properties: { path: { type: "string" } },
                      required: ["path"],
                      additionalProperties: false
                    }
                  ]
                }
              },
              additionalProperties: false
            }
          ]
        }
      }
    }
  },
  ide: {
    type: "object",
    label: "IDE",
    category: "IDE",
    requiresRestart: true,
    default: {},
    description: "IDE integration settings.",
    showInDialog: false,
    properties: {
      enabled: {
        type: "boolean",
        label: "Auto-connect to IDE",
        category: "IDE",
        requiresRestart: true,
        default: false,
        description: "Enable IDE integration mode",
        showInDialog: true
      },
      hasSeenNudge: {
        type: "boolean",
        label: "Has Seen IDE Integration Nudge",
        category: "IDE",
        requiresRestart: false,
        default: false,
        description: "Whether the user has seen the IDE integration nudge.",
        showInDialog: false
      }
    }
  },
  privacy: {
    type: "object",
    label: "Privacy",
    category: "Privacy",
    requiresRestart: true,
    default: {},
    description: "Privacy-related settings.",
    showInDialog: false,
    properties: {
      usageStatisticsEnabled: {
        type: "boolean",
        label: "Enable Usage Statistics",
        category: "Privacy",
        requiresRestart: true,
        default: true,
        description: "Enable collection of usage statistics",
        showInDialog: true
      }
    }
  },
  telemetry: {
    type: "object",
    label: "Telemetry",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Telemetry configuration.",
    showInDialog: false,
    jsonSchemaOverride: {
      type: "object",
      properties: {
        includeSensitiveSpanAttributes: {
          description: "When enabled, user prompts, system prompts, tool inputs/outputs, and model responses are written to native OTel span attributes in addition to the log-to-span bridge. Warning: this may expose sensitive data (file contents, shell commands, conversation history) to your OTLP backend.",
          type: "boolean",
          default: false
        },
        sensitiveSpanAttributeMaxLength: {
          description: "Maximum JavaScript string length for each sensitive native OTel span attribute content payload. Default: 1048576 (1 MiB). Maximum: 104857600 (100 MiB). Set lower if your collector or backend rejects large span attributes.",
          type: "integer",
          minimum: 1,
          maximum: SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT,
          default: DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH
        },
        resourceAttributes: {
          description: "Static resource attributes attached to every span/log/metric the SDK exports (OTLP or file outfile \u2014 they share the same Resource). Merged with the OTEL_RESOURCE_ATTRIBUTES env var; settings win on key conflict. Reserved keys (service.version, session.id) are dropped with a warning.",
          type: "object",
          additionalProperties: { type: "string" },
          default: {}
        },
        metrics: {
          description: "Per-signal cardinality controls for exported metrics.",
          type: "object",
          additionalProperties: false,
          properties: {
            includeSessionId: {
              description: "Include session.id on every metric data point. WARNING: each CLI session creates a new value, causing unbounded metric time-series fan-out at the backend. Only enable for short-term debugging \u2014 spans and logs still carry session.id.",
              type: "boolean",
              default: false
            }
          }
        }
      },
      additionalProperties: true
    }
  },
  outboundCorrelation: {
    type: "object",
    label: "Outbound Correlation",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "SECURITY-RELEVANT. Controls what client-side correlation data qwen-code writes into outbound LLM API requests (DashScope, OpenAI, Anthropic, etc.) \u2014 separate from `telemetry.*` which governs data flow into the operator's OWN OTLP collector. All values default to off. Opt in only when the LLM provider also reports into your OTel collector for cross-process trace stitching (e.g. ARMS Tracing + DashScope).",
    showInDialog: false,
    jsonSchemaOverride: {
      type: "object",
      properties: {
        propagateTraceContext: {
          description: "Requires `telemetry.enabled: true`. Inject W3C `traceparent` on outbound `fetch` requests (LLM SDK calls, MCP StreamableHTTP, WebFetch, ...) AND as a `TRACEPARENT` environment variable in shell child processes (Bash tool, hooks, monitor). When enabled, any existing `TRACEPARENT` in the parent environment is overwritten with qwen-code's own trace context. Default: false \u2014 trace context stays internal to the operator's OTLP collector. Set true when you want cross-process trace stitching with an OTel-aware LLM provider (e.g. ARMS+DashScope) or need shell scripts / CLI tools to participate in distributed tracing.",
          type: "boolean",
          default: false
        }
      },
      additionalProperties: false
    }
  },
  fastModel: {
    type: "string",
    label: "Fast Model",
    category: "Model",
    requiresRestart: false,
    default: "",
    description: "Model used for generating prompt suggestions and speculative execution. Leave empty to use the main model. A smaller/faster model (e.g., qwen3-coder-flash) reduces latency and cost.",
    showInDialog: true
  },
  visionModel: {
    type: "string",
    label: "Vision Model",
    category: "Model",
    requiresRestart: false,
    default: "",
    description: "Image-capable model used as the vision bridge: when a text-only main model receives an image, it is transcribed by this model first. Set with /model --vision. Leave empty to auto-pick a same-provider vision model.",
    showInDialog: true
  },
  visionBridgeTimeoutMs: {
    type: "integer",
    label: "Vision Bridge Timeout (ms)",
    category: "Model",
    // Read once in the Config constructor with no setter, so a mid-session
    // change only takes effect on restart.
    requiresRestart: true,
    default: void 0,
    minimum: 1,
    maximum: 2147483647,
    description: "Per-attempt timeout in milliseconds for the vision bridge image transcription call (a positive integer up to 2147483647). Unset uses the built-in 30s. Raise for slow or proxied vision endpoints.",
    showInDialog: false
  },
  modelFallbacks: {
    type: "string",
    label: "Model Fallbacks",
    category: "Model",
    requiresRestart: true,
    default: "",
    description: 'Ordered list of fallback model IDs (comma-separated, max 3) to try when the primary model hits capacity errors (429/503/529). Example: "qwen-plus,qwen-turbo". Set via CLI with --fallback-model.',
    showInDialog: true
  },
  voiceModel: {
    type: "string",
    label: "Voice Model",
    category: "Model",
    requiresRestart: false,
    default: "",
    description: "Model used for voice transcription. Set with /model --voice. Leave empty to keep voice dictation disabled until a voice model is selected.",
    showInDialog: false
  },
  model: {
    type: "object",
    label: "Model",
    category: "Model",
    requiresRestart: false,
    default: {},
    description: "Settings related to the generative model.",
    showInDialog: false,
    properties: {
      name: {
        type: "string",
        label: "Model",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "The model to use for conversations.",
        showInDialog: false
      },
      baseUrl: {
        type: "string",
        label: "Model Base URL",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Base URL paired with model.name; disambiguates which provider to use when multiple modelProviders entries share the same model id.",
        showInDialog: false
      },
      reasoningEffort: {
        type: "enum",
        label: "Reasoning Effort",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: 'How hard reasoning-capable models think, applied across all providers. Set with /effort. Each provider maps and clamps this to what the active model supports (e.g. Gemini caps at "high"; Anthropic clamps tiers a model lacks). Leave unset to use the model/provider default.',
        showInDialog: true,
        options: [
          { value: "low", label: "Low" },
          { value: "medium", label: "Medium" },
          { value: "high", label: "High" },
          { value: "xhigh", label: "Extra High" },
          { value: "max", label: "Max" }
        ]
      },
      maxSessionTurns: {
        type: "integer",
        label: "Max Session Turns",
        category: "Model",
        requiresRestart: false,
        default: -1,
        description: "Maximum number of user/model/tool turns to keep in a session. Must be an integer; -1 means unlimited.",
        showInDialog: false
      },
      maxWallTimeSeconds: {
        type: "number",
        label: "Max Wall-Clock Time (seconds)",
        category: "Model",
        requiresRestart: false,
        default: -1,
        description: "Run-level wall-clock budget for headless / unattended runs, in seconds. -1 means unlimited; otherwise must be in [1, ~2,147,483] (sub-second values and values above ~24 days are rejected as typos). Overridable per-invocation via --max-wall-time (which also accepts duration suffixes like 5m, 1.5h).",
        showInDialog: false
      },
      maxToolCalls: {
        type: "number",
        label: "Max Tool Calls",
        category: "Model",
        requiresRestart: false,
        default: -1,
        description: 'Cumulative tool-call budget for a run (counts every executed tool, success or failure; structured_output under --json-schema is exempt). -1 means unlimited; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos. Overridable via --max-tool-calls.',
        showInDialog: false
      },
      maxSubagentDepth: {
        type: "number",
        label: "Max Sub-agent Nesting Depth",
        category: "Model",
        requiresRestart: false,
        default: DEFAULT_MAX_SUBAGENT_DEPTH,
        description: "Maximum sub-agent nesting depth (1-based levels: a top-level sub-agent is level 1). 1 keeps sub-agents available but disables nesting; the default 5 allows nesting up to five levels deep. Values clamp to the range 1-100; non-finite values fall back to the default. Teammates, forks, and workflow-spawned agents never nest regardless of this setting. Overridable via --max-subagent-depth.",
        showInDialog: false
      },
      chatCompression: {
        type: "object",
        label: "Chat Compression",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Chat compression settings.",
        showInDialog: false
      },
      sessionTokenLimit: {
        type: "number",
        label: "Session Token Limit",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "The maximum number of tokens allowed in a session.",
        showInDialog: false
      },
      skipNextSpeakerCheck: {
        type: "boolean",
        label: "Skip Next Speaker Check",
        category: "Model",
        requiresRestart: false,
        default: true,
        description: "Skip the next speaker check.",
        showInDialog: false
      },
      skipWorkflowUsageWarning: {
        type: "boolean",
        label: "Skip Workflow Usage Warning",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Suppress the one-time Workflow tool usage banner that describes the QWEN_CODE_MAX_TOKENS_PER_WORKFLOW env knob. The banner fires at most once per session regardless of this setting.",
        showInDialog: false
      },
      skipLoopDetection: {
        type: "boolean",
        label: "Skip Loop Detection",
        category: "Model",
        requiresRestart: false,
        default: true,
        description: "Skip the opt-in streaming loop-detection heuristics (content/thought repetition, read-file and action stagnation, global-duplicate and alternating tool-call patterns). Defaults to true to avoid false-positive interruptions; set to false to re-enable them as an unattended-run guardrail. A minimal always-on guard (consecutive identical tool calls plus a per-turn tool-call cap, see model.maxToolCallsPerTurn) still runs regardless of this setting.",
        showInDialog: false
      },
      maxToolCallsPerTurn: {
        type: "integer",
        label: "Max Tool Calls Per Turn",
        category: "Model",
        requiresRestart: false,
        default: DEFAULT_MAX_TOOL_CALLS_PER_TURN,
        description: "Hard cap on tool calls within a single turn (one model turn plus its tool-result continuations; blocking Stop-hook continuations such as /goal iterations start a fresh budget). An always-on circuit breaker against runaway turns, independent of model.skipLoopDetection. Set to 0 or a negative value to disable the cap.",
        showInDialog: false
      },
      skipStartupContext: {
        type: "boolean",
        label: "Skip Startup Context",
        category: "Model",
        requiresRestart: true,
        default: false,
        description: "Avoid sending the workspace startup context at the beginning of each session.",
        showInDialog: false
      },
      enableOpenAILogging: {
        type: "boolean",
        label: "Enable OpenAI Logging",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Enable OpenAI logging.",
        showInDialog: false
      },
      openAILoggingDir: {
        type: "string",
        label: "OpenAI Logging Directory",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Custom directory path for OpenAI API logs. If not specified, defaults to logs/openai in the current working directory.",
        showInDialog: false
      },
      generationConfig: {
        type: "object",
        label: "Generation Configuration",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Generation configuration settings.",
        showInDialog: false,
        properties: {
          timeout: {
            type: "number",
            label: "Timeout",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Request timeout in milliseconds.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          maxRetries: {
            type: "number",
            label: "Max Retries",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Maximum number of retries for failed requests.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          enableCacheControl: {
            type: "boolean",
            label: "Enable Cache Control",
            category: "Generation Configuration",
            requiresRestart: false,
            default: true,
            description: "Enable cache control for DashScope providers.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          forceGlobalCacheScope: {
            type: "boolean",
            label: "Force Global Cache Scope",
            category: "Generation Configuration",
            requiresRestart: false,
            default: false,
            description: "Force scope:'global' on Anthropic cache_control entries even when the base URL is not an Anthropic-native origin (e.g. proxy providers like Routify, OpenRouter). Requires the proxy to forward cache_control fields and the prompt-caching-scope-2026-01-05 beta.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          splitToolMedia: {
            type: "boolean",
            label: "Split Tool Result Media",
            category: "Generation Configuration",
            requiresRestart: false,
            default: true,
            description: 'When true, media (images / audio / video / files) returned by tool calls \u2014 including the built-in read_file and MCP tools \u2014 is split into a follow-up user message instead of being embedded in the `role: "tool"` message. The OpenAI Chat Completions spec only permits text on tool messages, so strict OpenAI-compatible servers (e.g., doubao / new-api / LM Studio) silently drop or reject embedded media and the model never sees an image read via read_file (QwenLM/qwen-code#4876, #3616). Default true is spec-compliant and safe for permissive providers; set false only to restore the legacy embed-in-tool-message behavior.',
            parentKey: "generationConfig",
            showInDialog: false
          },
          toolResultContentFormat: {
            type: "enum",
            label: "Tool Result Content Format",
            category: "Generation Configuration",
            requiresRestart: false,
            default: "parts",
            description: 'Controls how text-only tool results are serialized in OpenAI-compatible requests. Use "parts" for the default content-part array shape. Use "string" only for legacy OpenAI-compatible runtimes whose tool templates ignore text content parts (for example older GLM-5.1 vLLM/SGLang templates; QwenLM/qwen-code#3361). Tool-returned media is still handled by splitToolMedia.',
            parentKey: "generationConfig",
            showInDialog: false,
            options: [
              { value: "parts", label: "Content Parts (Default)" },
              { value: "string", label: "String" }
            ]
          },
          schemaCompliance: {
            type: "enum",
            label: "Tool Schema Compliance",
            category: "Generation Configuration",
            requiresRestart: false,
            default: "auto",
            description: 'The compliance mode for tool schemas sent to the model. Use "openapi_30" for strict OpenAPI 3.0 compatibility (e.g., for Gemini).',
            parentKey: "generationConfig",
            showInDialog: false,
            options: [
              { value: "auto", label: "Auto (Default)" },
              { value: "openapi_30", label: "OpenAPI 3.0 Strict" }
            ]
          },
          contextWindowSize: {
            type: "number",
            label: "Context Window Size",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Overrides the default context window size for the selected model. Use this setting when a provider's effective context limit differs from Qwen Code's default. This value defines the model's assumed maximum context capacity, not a per-request token limit.",
            parentKey: "generationConfig",
            showInDialog: false
          }
        }
      }
    }
  },
  modelPricing: {
    type: "object",
    label: "Model Pricing",
    category: "Model",
    requiresRestart: false,
    default: void 0,
    description: 'Optional per-model pricing for cost estimation in /stats model. Example: {"qwen3-coder": {"inputPerMillionTokens": 0.30, "outputPerMillionTokens": 1.20}}',
    showInDialog: false
  },
  context: {
    type: "object",
    label: "Context",
    category: "Context",
    requiresRestart: false,
    default: {},
    description: "Settings for managing context provided to the model.",
    showInDialog: false,
    properties: {
      fileName: {
        type: "object",
        label: "Context File Name",
        category: "Context",
        requiresRestart: false,
        default: void 0,
        description: "The name of the context file or files.",
        showInDialog: false,
        jsonSchemaOverride: {
          anyOf: [
            { type: "string" },
            { type: "array", items: { type: "string" } }
          ]
        }
      },
      importFormat: {
        type: "enum",
        label: "Memory Import Format",
        category: "Context",
        requiresRestart: false,
        default: void 0,
        description: "The format to use when importing memory.",
        showInDialog: false,
        options: [
          { value: "tree", label: "Tree" },
          { value: "flat", label: "Flat" }
        ]
      },
      includeDirectories: {
        type: "array",
        label: "Include Directories",
        category: "Context",
        requiresRestart: false,
        default: [],
        description: "Additional directories to include in the workspace context. Missing directories will be skipped with a warning.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      },
      loadFromIncludeDirectories: {
        type: "boolean",
        label: "Load Memory From Include Directories",
        category: "Context",
        requiresRestart: false,
        default: false,
        description: "Whether to load memory files from include directories.",
        showInDialog: false
      },
      clearContextOnIdle: {
        type: "object",
        label: "Clear Context On Idle",
        category: "Context",
        requiresRestart: false,
        default: {},
        description: "Settings for clearing stale or oversized tool result context. Use -1 to disable a threshold.",
        showInDialog: false,
        properties: {
          toolResultsThresholdMinutes: {
            type: "number",
            label: "Tool Results Idle Threshold (minutes)",
            category: "Context",
            requiresRestart: false,
            default: 60,
            description: "Minutes of inactivity before clearing old tool result content. Use -1 to disable.",
            showInDialog: false
          },
          toolResultsNumToKeep: {
            type: "number",
            label: "Tool Results Number To Keep",
            category: "Context",
            requiresRestart: false,
            default: 5,
            description: "Integer number of most-recent compactable tool results to preserve when clearing. Values below 1 are floored to 1.",
            jsonSchemaOverride: {
              type: "integer",
              default: 5,
              description: "Integer number of most-recent compactable tool results to preserve when clearing. Values below 1 are floored to 1."
            },
            showInDialog: false
          },
          toolResultsTotalCharsThreshold: {
            type: "number",
            label: "Tool Results Total Chars Threshold",
            category: "Context",
            requiresRestart: false,
            default: DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD,
            description: "Total compactable tool result output characters allowed in history before clearing oldest results. Use -1 to disable. This is a soft threshold: protected recent tool results may keep the total above it.",
            showInDialog: false
          }
        }
      },
      fileFiltering: {
        type: "object",
        label: "File Filtering",
        category: "Context",
        requiresRestart: true,
        default: {},
        description: "Settings for git-aware file filtering.",
        showInDialog: false,
        properties: {
          respectGitIgnore: {
            type: "boolean",
            label: "Respect .gitignore",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Respect .gitignore files when searching",
            showInDialog: true
          },
          respectQwenIgnore: {
            type: "boolean",
            label: "Respect .qwenignore",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Respect .qwenignore and configured custom ignore files when searching",
            showInDialog: true
          },
          customIgnoreFiles: {
            type: "array",
            label: "Custom Ignore Files",
            category: "Context",
            requiresRestart: true,
            default: [...DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES],
            description: "Project-root-relative ignore files to use instead of the defaults (`.agentignore`, `.aiignore`) when respectQwenIgnore is enabled. .qwenignore is always included when respectQwenIgnore is enabled.",
            showInDialog: false,
            items: { type: "string" }
          },
          enableRecursiveFileSearch: {
            type: "boolean",
            label: "Enable Recursive File Search",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Enable recursive file search functionality",
            showInDialog: false
          },
          enableFuzzySearch: {
            type: "boolean",
            label: "Enable Fuzzy Search",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Enable fuzzy search when searching for files.",
            showInDialog: true
          }
        }
      },
      autoCompactThreshold: {
        type: "number",
        label: "Auto-Compact Threshold",
        category: "Context",
        requiresRestart: false,
        default: void 0,
        description: "Target fraction of the context window at which auto-compaction triggers (greater than 0, up to 1). Acts as a ceiling on the trigger: on large windows this is the effective trigger (~85%); on smaller windows compaction may fire earlier to leave room to summarize. Default is 0.85 (85%).",
        showInDialog: false,
        jsonSchemaOverride: {
          type: "number",
          minimum: 0.01,
          maximum: 1
        }
      }
    }
  },
  memory: {
    type: "object",
    label: "Memory",
    category: "Memory",
    requiresRestart: false,
    default: {},
    description: "Settings for managed auto-memory.",
    showInDialog: false,
    properties: {
      enableManagedAutoMemory: {
        type: "boolean",
        label: "Enable Managed Auto-Memory",
        category: "Memory",
        requiresRestart: false,
        default: true,
        description: "Enable background extraction of memories from conversations.",
        showInDialog: false
      },
      enableManagedAutoDream: {
        type: "boolean",
        label: "Enable Managed Auto-Dream",
        category: "Memory",
        requiresRestart: false,
        default: true,
        description: "Enable automatic consolidation (dream) of collected memories.",
        showInDialog: false
      },
      enableAutoSkill: {
        type: "boolean",
        label: "Enable Auto Skill",
        category: "Memory",
        requiresRestart: false,
        default: false,
        description: "Enable background review for reusable project skills after tool-heavy sessions.",
        showInDialog: false
      },
      autoSkillConfirm: {
        type: "boolean",
        label: "Confirm Auto Skills Before Saving",
        category: "Memory",
        requiresRestart: false,
        default: true,
        description: "Ask for confirmation before auto-generated skills are added to the skill library. When off, auto-skills are saved immediately.",
        showInDialog: false
      },
      agentTimeoutMinutes: {
        type: "number",
        label: "Memory Agent Timeout (minutes)",
        category: "Memory",
        requiresRestart: true,
        default: void 0,
        minimum: 0,
        description: "Max runtime in minutes for background memory agents (extraction, dream, remember, skill review). Unset uses each agent's built-in default (2\u20135 minutes); 0 disables the time limit. Useful for slow local models that need longer than the defaults.",
        showInDialog: false
      },
      enableTeamMemory: {
        type: "boolean",
        label: "Enable Team Memory",
        category: "Memory",
        requiresRestart: false,
        default: false,
        description: "Enable a project memory tier shared with collaborators via the git-tracked `.qwen/team-memory/` directory. Off by default; writes to it are secret-scanned and reviewable in the git diff.",
        showInDialog: false
      },
      enableTeamMemorySync: {
        type: "boolean",
        label: "Enable Team Memory Git Sync",
        category: "Memory",
        requiresRestart: false,
        default: false,
        description: "When team memory is enabled, automatically commit, fast-forward-pull, and push the `.qwen/team-memory/` directory at session start so collaborators stay in sync. Off by default; requires a configured git upstream.",
        showInDialog: false
      }
    }
  },
  slashCommands: {
    type: "object",
    label: "Slash Commands",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for slash commands exposed by the CLI. Useful for locking down the command surface in multi-tenant or enterprise deployments.",
    showInDialog: false,
    properties: {
      disabled: {
        type: "array",
        label: "Disabled Slash Commands",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: 'Slash command names to hide and refuse to execute. Matched case-insensitively against the final command name (for extension commands this is the disambiguated form, e.g. "myext.deploy"). Merged as a union across settings scopes, so workspace settings can add to but not remove entries defined in system/user settings.',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      }
    }
  },
  skills: {
    type: "object",
    label: "Skills",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Configuration for skills (SKILL.md-based capabilities) exposed to the model.",
    showInDialog: false,
    properties: {
      disabled: {
        type: "array",
        label: "Disabled Skills",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "Skill names to hide. Matched case-insensitively against the skill name. Hidden skills do not appear in <available_skills> or as /<name> slash commands. UNION-merged across systemDefaults/user/workspace/system scopes \u2014 workspace cannot remove entries defined in higher scopes.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      }
    }
  },
  permissions: {
    type: "object",
    label: "Permissions",
    category: "Tools",
    requiresRestart: true,
    default: {},
    description: "Permission rules controlling tool usage. Rules are evaluated in priority order: deny > ask > allow.",
    showInDialog: false,
    properties: {
      allow: {
        type: "array",
        label: "Allow Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: 'Tools or commands that are auto-approved without confirmation. Examples: "ShellTool", "Bash(git *)", "ReadFileTool".',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      ask: {
        type: "array",
        label: "Ask Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Tools or commands that always require user confirmation. Takes precedence over allow rules.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      deny: {
        type: "array",
        label: "Deny Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: 'Tools or commands that are always blocked. Highest priority rule. Examples: "ShellTool", "Bash(rm -rf *)".',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      autoMode: {
        type: "object",
        label: "Auto Mode",
        category: "Tools",
        requiresRestart: true,
        default: {},
        description: "Settings consumed by the AUTO approval mode classifier.",
        showInDialog: false,
        properties: {
          classifier: {
            type: "object",
            label: "Auto Mode Classifier",
            category: "Tools",
            requiresRestart: true,
            default: {},
            description: "Runtime controls for the AUTO approval mode classifier.",
            showInDialog: false,
            properties: {
              timeouts: {
                type: "object",
                label: "Auto Mode Classifier Timeouts",
                category: "Tools",
                requiresRestart: true,
                default: {},
                description: "Timeouts for the two AUTO classifier stages, in milliseconds.",
                showInDialog: false,
                properties: {
                  stage1Ms: {
                    type: "number",
                    label: "Auto Mode Stage 1 Timeout",
                    category: "Tools",
                    requiresRestart: true,
                    default: void 0,
                    description: "Timeout in milliseconds for the fast stage-1 AUTO classifier.",
                    showInDialog: false
                  },
                  stage2Ms: {
                    type: "number",
                    label: "Auto Mode Stage 2 Timeout",
                    category: "Tools",
                    requiresRestart: true,
                    default: void 0,
                    description: "Timeout in milliseconds for the stage-2 AUTO classifier review.",
                    showInDialog: false
                  }
                }
              },
              thinking: {
                type: "object",
                label: "Auto Mode Classifier Thinking",
                category: "Tools",
                requiresRestart: true,
                default: {},
                description: "Provider/API-level thinking controls for the AUTO classifier.",
                showInDialog: false,
                properties: {
                  stage2Enabled: {
                    type: "boolean",
                    label: "Auto Mode Stage 2 Thinking",
                    category: "Tools",
                    requiresRestart: true,
                    default: false,
                    description: "Whether stage 2 may use provider/API-level thinking. Stage 1 always keeps thinking disabled.",
                    showInDialog: false
                  }
                }
              }
            }
          },
          hints: {
            type: "object",
            label: "Classifier Hints",
            category: "Tools",
            requiresRestart: true,
            default: {},
            description: "Natural-language hints injected into the classifier system prompt.",
            showInDialog: false,
            properties: {
              allow: {
                type: "array",
                label: "Auto Mode Allow Hints",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Natural-language descriptions of actions AUTO mode should allow.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              },
              softDeny: {
                type: "array",
                label: "Auto Mode Soft-Deny Hints",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Natural-language descriptions of destructive / irreversible actions AUTO mode should block unless the user explicitly authorised that exact action and scope.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              },
              hardDeny: {
                type: "array",
                label: "Auto Mode Hard-Deny Hints",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Natural-language descriptions of security-boundary actions the AUTO classifier must block even when an autoMode allow hint or recent user request would normally authorise them. Does not override permissions.allow; use permissions.deny for deterministic hard permission rules.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              },
              deny: {
                type: "array",
                label: "Auto Mode Deny Hints (legacy)",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Deprecated alias for `softDeny`. Entries here are merged into the SOFT BLOCK user section so existing settings keep working; new configurations should use `softDeny` or `hardDeny` instead.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              }
            }
          },
          environment: {
            type: "array",
            label: "Auto Mode Environment",
            category: "Tools",
            requiresRestart: true,
            default: void 0,
            description: "Environment / context lines injected into the classifier system prompt.",
            showInDialog: false,
            mergeStrategy: "union" /* UNION */
          },
          classifyAllShell: {
            type: "boolean",
            label: "Classify All Shell Commands",
            category: "Tools",
            requiresRestart: true,
            default: false,
            description: "Route ALL shell commands through the auto-mode classifier, including read-only commands that would otherwise be auto-approved. Provides defense-in-depth for production environments.",
            showInDialog: false
          }
        }
      }
    }
  },
  tools: {
    type: "object",
    label: "Tools",
    category: "Tools",
    requiresRestart: true,
    default: {},
    description: "Settings for built-in and custom tools.",
    showInDialog: false,
    properties: {
      sandbox: {
        type: "object",
        label: "Sandbox",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Sandbox execution environment (can be a boolean or a path string).",
        showInDialog: false,
        jsonSchemaOverride: {
          anyOf: [{ type: "boolean" }, { type: "string" }]
        }
      },
      sandboxImage: {
        type: "string",
        label: "Sandbox Image",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Sandbox image URI used by Docker/Podman when --sandbox-image and QWEN_SANDBOX_IMAGE are not set.",
        showInDialog: false
      },
      toolSearch: {
        type: "object",
        label: "Tool Search",
        category: "Tools",
        requiresRestart: true,
        default: {},
        description: "Settings for the ToolSearch discovery mechanism.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Enable ToolSearch",
            category: "Tools",
            requiresRestart: true,
            default: true,
            description: "When enabled, MCP tools are loaded on-demand via ToolSearch to reduce prompt size. Disable this for models that rely on prefix-based KV caching (e.g. DeepSeek) to keep the prompt prefix stable and maximize cache hit rates.",
            showInDialog: true
          }
        }
      },
      shell: {
        type: "object",
        label: "Shell",
        category: "Tools",
        requiresRestart: false,
        default: {},
        description: "Settings for shell execution.",
        showInDialog: false,
        properties: {
          enableInteractiveShell: {
            type: "boolean",
            label: "Interactive Shell (PTY)",
            category: "Tools",
            requiresRestart: true,
            default: true,
            description: "Use node-pty for an interactive shell experience. Falls back to child_process if PTY is unavailable.",
            showInDialog: true
          },
          pager: {
            type: "string",
            label: "Pager",
            category: "Tools",
            requiresRestart: false,
            default: void 0,
            description: "The pager command to use for shell output. Defaults to `cat` on non-Windows platforms and unset on Windows. Set to an empty string to disable pager environment variables.",
            showInDialog: false
          },
          showColor: {
            type: "boolean",
            label: "Show Color",
            category: "Tools",
            requiresRestart: false,
            default: false,
            description: "Show color in shell output.",
            showInDialog: false
          },
          defaultTimeoutMs: {
            type: "integer",
            minimum: 0,
            maximum: 6e5,
            label: "Default Command Timeout (ms)",
            category: "Tools",
            requiresRestart: true,
            default: void 0,
            description: "Default timeout, in milliseconds, for foreground shell commands started by the agent. A per-call timeout on the shell tool overrides this. When unset, foreground commands time out after 120000 ms (2 minutes). Set to 0 to disable the timeout.",
            showInDialog: false
          },
          heartbeatIntervalMs: {
            type: "integer",
            minimum: 0,
            maximum: 6e5,
            label: "Silent Command Heartbeat Interval (ms)",
            category: "Tools",
            requiresRestart: true,
            default: void 0,
            description: "Interval, in milliseconds, between liveness heartbeats emitted while a foreground shell command produces no output. Heartbeats are forwarded to ACP clients and stream-json consumers so they can tell a silent command from a dead session. When unset, heartbeats fire every 10000 ms (10 seconds). Set to 0 to disable heartbeats.",
            showInDialog: false
          }
        }
      },
      // Legacy tool permission fields – kept for backward compatibility.
      // Use permissions.{allow,ask,deny} instead.
      core: {
        type: "array",
        label: "Core Tools (deprecated)",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.allow instead.",
        showInDialog: false
      },
      allowed: {
        type: "array",
        label: "Allowed Tools (deprecated)",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.allow instead.",
        showInDialog: false
      },
      exclude: {
        type: "array",
        label: "Exclude Tools (deprecated)",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.deny instead.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      disabled: {
        type: "array",
        label: "Disabled Tools",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Tool names hidden from the registry. Differs from permissions.deny: disabled tools are not registered at all, so they never appear in /tools and cannot be discovered by the model. Managed by the daemon mutation route POST /workspace/tools/:name/enable.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      visible: {
        type: "array",
        label: "Visible Deferred Tools",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Deferred tool names made visible at startup without requiring tool_search. Listed tools appear alongside core tools in the initial session.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      approvalMode: {
        type: "enum",
        label: "Tool Approval Mode",
        category: "Tools",
        requiresRestart: false,
        default: "auto" /* AUTO */,
        description: "Approval mode for tool usage. Controls how tools are approved before execution.",
        showInDialog: true,
        options: [
          { value: "plan" /* PLAN */, label: "Plan" },
          { value: "default" /* DEFAULT */, label: "Ask permissions" },
          { value: "auto-edit" /* AUTO_EDIT */, label: "Auto Edit" },
          { value: "auto" /* AUTO */, label: "Auto" },
          { value: "yolo" /* YOLO */, label: "YOLO" }
        ]
      },
      autoAccept: {
        type: "boolean",
        label: "Auto Accept",
        category: "Tools",
        requiresRestart: false,
        default: false,
        description: "Automatically accept and execute tool calls that are considered safe (e.g., read-only operations) without explicit user confirmation.",
        showInDialog: false
      },
      discoveryCommand: {
        type: "string",
        label: "Tool Discovery Command",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Command to run for tool discovery.",
        showInDialog: false
      },
      callCommand: {
        type: "string",
        label: "Tool Call Command",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Command to run for tool calls.",
        showInDialog: false
      },
      useRipgrep: {
        type: "boolean",
        label: "Use Ripgrep",
        category: "Tools",
        requiresRestart: false,
        default: true,
        description: "Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance.",
        showInDialog: false
      },
      useBuiltinRipgrep: {
        type: "boolean",
        label: "Use Builtin Ripgrep",
        category: "Tools",
        requiresRestart: false,
        default: true,
        description: 'Use the bundled ripgrep binary. When set to false, the system-level "rg" command will be used instead. This setting is only effective when useRipgrep is true.',
        showInDialog: false
      },
      truncateToolOutputThreshold: {
        type: "number",
        label: "Tool Output Truncation Threshold",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
        description: "Truncate tool output if it is larger than this many characters. Set to -1 to disable.",
        showInDialog: false
      },
      truncateToolOutputLines: {
        type: "number",
        label: "Tool Output Truncation Lines",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,
        description: "The number of lines to keep when truncating tool output.",
        showInDialog: false
      },
      toolOutputBatchBudget: {
        type: "number",
        label: "Tool Output Batch Budget",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TOOL_OUTPUT_BATCH_BUDGET,
        description: "Per-message budget (characters) for the combined output of one batch of tool calls; the largest results are offloaded to disk when exceeded. Set to -1 to disable.",
        showInDialog: false
      },
      computerUse: {
        type: "object",
        label: "Computer Use",
        category: "Tools",
        requiresRestart: true,
        default: {},
        description: "Cross-platform desktop automation via the cua-driver native driver (trycua/cua). On first invocation a pinned, signed + notarized binary (~20MB) is downloaded into ~/.qwen/computer-use/ and the user is walked through macOS Accessibility / Screen Recording permissions if needed. Exposes cua-driver's full tool surface (click, type_text, scroll, drag, press_key, get_window_state, page, launch_app, and more).",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Enable Computer Use",
            category: "Tools",
            requiresRestart: true,
            default: true,
            description: "When enabled (default), the cua-driver computer_use__* tools are registered as deferred built-ins. Set to false to prevent the driver from being downloaded or spawned.",
            showInDialog: true
          },
          idleTimeoutMs: {
            type: "number",
            label: "Idle Timeout",
            category: "Tools",
            requiresRestart: true,
            default: 3e5,
            minimum: 0,
            maximum: 2147483647,
            description: "Milliseconds to keep the cua-driver process alive after the last computer_use__* call. The default is 300000 (5 minutes). Set to 0 to keep it running until qwen-code exits.",
            showInDialog: false
          },
          maxImageDimension: {
            type: "number",
            label: "Max Screenshot Dimension",
            category: "Tools",
            requiresRestart: true,
            default: -1,
            description: "Longest-edge pixel cap applied to cua-driver screenshots (via set_config's max_image_dimension). -1 (default) keeps cua-driver's built-in default (1568); 0 disables resizing (full resolution); a positive value caps the longest edge. Lower caps cut vision-token cost at the expense of fine detail. Overridable via the QWEN_COMPUTER_USE_MAX_IMAGE_DIMENSION env var.",
            showInDialog: false
          }
        }
      }
    }
  },
  policy: {
    type: "object",
    label: "Daemon Policy",
    category: "Daemon",
    requiresRestart: true,
    default: {},
    description: "Daemon multi-client coordination policies. Tool-level allow/deny rules live under `permissions`; this section is for runtime mediation behavior between concurrent HTTP clients sharing one `qwen serve` daemon.",
    showInDialog: false,
    properties: {
      permissionStrategy: {
        type: "enum",
        label: "Permission Mediation Policy",
        category: "Daemon",
        requiresRestart: true,
        default: "first-responder",
        description: 'How permission requests resolve when multiple clients are attached. `first-responder` (default) = any client decides, first wins. `designated` = only the prompt originator decides; falls back to first-responder if originator is anonymous. NOTE: client identity comes from self-declared X-Qwen-Client-Id with no proof-of-possession (pair-token identity is not implemented yet), so any client observing originatorClientId on SSE frames can register with the same id and impersonate the originator. `consensus` = N-of-M voters must agree. Default N=floor(M/2)+1, which means UNANIMITY for M=2 (quorum=2, both must agree) and supermajority for larger even M (M=4 \u2192 quorum=3; M=6 \u2192 quorum=4). For M=2 specifically, split votes resolve only via permissionTimeoutMs. `local-only` = only loopback clients can RESOLVE; remote clients can still ABORT a pending permission via the cancel sentinel ({outcome:"cancelled"}) \u2014 cancel stays cross-policy for consistency. Strict-cancel-too deployments need a dedicated loopback-bound daemon. Requires daemon restart \u2014 read once at boot.',
        showInDialog: true,
        options: [
          { value: "first-responder", label: "First Responder" },
          { value: "designated", label: "Designated Originator" },
          { value: "consensus", label: "Consensus Quorum" },
          { value: "local-only", label: "Local Only" }
        ]
      },
      consensusQuorum: {
        type: "number",
        label: "Consensus Quorum Override",
        category: "Daemon",
        requiresRestart: true,
        default: void 0,
        description: "Optional fixed quorum size for consensus policy. Capped at M (count of registered voters at request issue time) to prevent unreachable quorum. Unset = floor(M/2)+1. Requires daemon restart \u2014 read once at boot.",
        showInDialog: false,
        // run-qwen-serve.ts validates `Number.isInteger(n) && n >= 1` and
        // refuses to boot otherwise. Override the generated schema so IDE
        // (VSCode, JetBrains via JSON Schema) flags `0`, `-1`, `1.5`
        // BEFORE the user restarts the daemon. The bare `type:'number'`
        // mapping accepts all of these.
        jsonSchemaOverride: {
          type: "integer",
          minimum: 1,
          description: "Optional fixed quorum size for consensus policy. Capped at M (count of registered voters at request issue time) to prevent unreachable quorum. Unset = floor(M/2)+1. Requires daemon restart \u2014 read once at boot."
        }
      }
    }
  },
  mcp: {
    type: "object",
    label: "MCP",
    category: "MCP",
    requiresRestart: true,
    default: {},
    description: "Settings for Model Context Protocol (MCP) servers.",
    showInDialog: false,
    properties: {
      serverCommand: {
        type: "string",
        label: "MCP Server Command",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "Command to start an MCP server.",
        showInDialog: false
      },
      allowed: {
        type: "array",
        label: "Allow MCP Servers",
        category: "MCP",
        // Hot-reloadable (sub-task 3): read by mcpGatingEqual and re-applied
        // live during reconcile. See mcpServers above for why this must not be
        // restart-required.
        requiresRestart: false,
        default: void 0,
        description: 'A list of MCP servers to allow. Supports glob patterns (e.g. "*puppeteer*").',
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      },
      excluded: {
        type: "array",
        label: "Exclude MCP Servers",
        category: "MCP",
        // Hot-reloadable (sub-task 3): read by mcpGatingEqual and re-applied
        // live during reconcile. See mcpServers above for why this must not be
        // restart-required.
        requiresRestart: false,
        default: void 0,
        description: 'A list of MCP servers to exclude. Supports glob patterns (e.g. "*puppeteer*"). Takes precedence over mcp.allowed.',
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      },
      toolIdleTimeoutMs: {
        type: "number",
        label: "MCP Tool Idle Timeout (ms)",
        category: "MCP",
        requiresRestart: false,
        default: 3e5,
        minimum: 1e4,
        maximum: 36e5,
        description: "Idle timeout in milliseconds for MCP tool calls. If the MCP server does not produce any response or progress update within this time, the call is aborted. Default: 300000 (5 minutes). Can be overridden via QWEN_CODE_MCP_TOOL_IDLE_TIMEOUT_MS environment variable.",
        showInDialog: false
      }
    }
  },
  security: {
    type: "object",
    label: "Security",
    category: "Security",
    requiresRestart: true,
    default: {},
    description: "Security-related settings.",
    showInDialog: false,
    properties: {
      folderTrust: {
        type: "object",
        label: "Folder Trust",
        category: "Security",
        requiresRestart: false,
        default: {},
        description: "Settings for folder trust.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Folder Trust",
            category: "Security",
            requiresRestart: true,
            default: false,
            description: "Setting to track whether Folder trust is enabled.",
            showInDialog: false
          }
        }
      },
      auth: {
        type: "object",
        label: "Authentication",
        category: "Security",
        requiresRestart: true,
        default: {},
        description: "Authentication settings.",
        showInDialog: false,
        properties: {
          selectedType: {
            type: "string",
            label: "Selected Auth Type",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "The currently selected authentication type.",
            showInDialog: false
          },
          enforcedType: {
            type: "string",
            label: "Enforced Auth Type",
            category: "Advanced",
            requiresRestart: true,
            default: void 0,
            description: "The required auth type. If this does not match the selected auth type, the user will be prompted to re-authenticate.",
            showInDialog: false
          },
          useExternal: {
            type: "boolean",
            label: "Use External Auth",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "Whether to use an external authentication flow.",
            showInDialog: false
          },
          apiKey: {
            type: "string",
            label: "API Key",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "API key for OpenAI compatible authentication.",
            showInDialog: false
          },
          baseUrl: {
            type: "string",
            label: "Base URL",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "Base URL for OpenAI compatible API.",
            showInDialog: false
          }
        }
      },
      allowedHttpHookUrls: {
        type: "array",
        label: "Allowed HTTP Hook URLs",
        category: "Security",
        requiresRestart: false,
        default: [],
        description: "Whitelist of URL patterns for HTTP hooks. Supports * wildcard. If empty, all URLs are allowed (subject to SSRF protection).",
        showInDialog: false,
        items: {
          type: "string",
          description: "URL pattern (supports * wildcard)"
        }
      }
    }
  },
  advanced: {
    type: "object",
    label: "Advanced",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Advanced settings for power users.",
    showInDialog: false,
    properties: {
      autoConfigureMemory: {
        type: "boolean",
        label: "Auto Configure Max Old Space Size",
        category: "Advanced",
        requiresRestart: true,
        default: false,
        description: "Automatically configure Node.js memory limits",
        showInDialog: false
      },
      dnsResolutionOrder: {
        type: "enum",
        label: "DNS Resolution Order",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "The DNS resolution order.",
        showInDialog: false,
        options: [
          { value: "ipv4first", label: "IPv4 First" },
          { value: "verbatim", label: "Verbatim" }
        ]
      },
      excludedEnvVars: {
        type: "array",
        label: "Excluded Project Environment Variables",
        category: "Advanced",
        requiresRestart: false,
        default: ["DEBUG", "DEBUG_MODE"],
        description: "Environment variables to exclude from project context.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      bugCommand: {
        type: "object",
        label: "Bug Command",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "Configuration for the bug report command.",
        showInDialog: false
      },
      runtimeOutputDir: {
        type: "string",
        label: "Runtime Output Directory",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "Custom directory for runtime output (temp files, debug logs, session data, todos, etc.). Config files remain at ~/.qwen (or QWEN_HOME if set). Env var QWEN_RUNTIME_DIR takes priority.",
        showInDialog: false
      }
    }
  },
  agents: {
    type: "object",
    label: "Agents",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Settings for built-in agents and multi-agent collaboration features (Arena, Team, Swarm).",
    showInDialog: false,
    properties: {
      builtin: {
        type: "object",
        label: "Built-in Agents",
        category: "Advanced",
        requiresRestart: true,
        default: {},
        description: "Settings for built-in subagents.",
        showInDialog: false,
        properties: {
          exploreModel: {
            type: "string",
            label: "Explore Model",
            category: "Model",
            requiresRestart: true,
            default: "inherit",
            description: 'Model selector for the built-in Explore subagent. Use "inherit" for the main session model, "fast" for fastModel, a model ID, or an authType:model-id selector. Custom same-name agents are unaffected.',
            showInDialog: false
          }
        }
      },
      maxParallelAgents: {
        type: "number",
        label: "Max Parallel Agents",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        minimum: 1,
        description: "Global maximum number of background sub-agents that can run concurrently. Additional background agents wait in a queue until a slot is available. Per-model limits are not supported yet.",
        showInDialog: false,
        jsonSchemaOverride: {
          type: "integer",
          minimum: 1
        }
      },
      displayMode: {
        type: "enum",
        label: "Display Mode",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: 'Display mode for multi-agent sessions. Currently only "in-process" is supported.',
        showInDialog: false,
        options: [
          { value: "in-process", label: "In-process" }
          // { value: 'tmux', label: 'tmux' },
          // { value: 'iterm2', label: 'iTerm2' },
        ]
      },
      arena: {
        type: "object",
        label: "Arena",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Arena (multi-model competitive execution).",
        showInDialog: false,
        properties: {
          worktreeBaseDir: {
            type: "string",
            label: "Worktree Base Directory",
            category: "Advanced",
            requiresRestart: true,
            default: void 0,
            description: "Custom base directory for Arena worktrees. Defaults to ~/.qwen/arena.",
            showInDialog: false
          },
          preserveArtifacts: {
            type: "boolean",
            label: "Preserve Arena Artifacts",
            category: "Advanced",
            requiresRestart: false,
            default: false,
            description: "When enabled, Arena worktrees and session state files are preserved after the session ends or the main agent exits.",
            showInDialog: true
          },
          maxRoundsPerAgent: {
            type: "number",
            label: "Max Rounds Per Agent",
            category: "Advanced",
            requiresRestart: false,
            default: void 0,
            description: "Maximum number of rounds (turns) each agent can execute. No limit if unset.",
            showInDialog: false
          },
          timeoutSeconds: {
            type: "number",
            label: "Timeout (seconds)",
            category: "Advanced",
            requiresRestart: false,
            default: void 0,
            description: "Total timeout in seconds for the Arena session. No limit if unset.",
            showInDialog: false
          }
        }
      },
      team: {
        type: "object",
        label: "Team",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Agent Team (role-based collaborative execution). Reserved for future use.",
        showInDialog: false
      },
      swarm: {
        type: "object",
        label: "Swarm",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Agent Swarm (parallel sub-agent execution). Reserved for future use.",
        showInDialog: false
      }
    }
  },
  disableAllHooks: {
    type: "boolean",
    label: "Disable All Hooks",
    category: "Advanced",
    requiresRestart: true,
    // Future enhancement: consider supporting mid-session toggle for better UX
    default: false,
    description: "Temporarily disable all hooks without deleting configurations. Default is false (hooks enabled).",
    showInDialog: false
  },
  stopHookBlockingCap: {
    type: "number",
    label: "Stop Hook Blocking Cap",
    category: "Advanced",
    requiresRestart: true,
    default: DEFAULT_STOP_HOOK_BLOCK_CAP,
    description: "Maximum consecutive blocking Stop/SubagentStop hook decisions before Qwen Code overrides the hook loop and ends the turn. Can be overridden by QWEN_CODE_STOP_HOOK_BLOCK_CAP.",
    // This is an advanced safety valve for runaway hook loops, not a common
    // interactive preference.
    showInDialog: false,
    jsonSchemaOverride: {
      type: "integer",
      minimum: 1,
      default: DEFAULT_STOP_HOOK_BLOCK_CAP
    }
  },
  hooks: {
    type: "object",
    label: "Hooks",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Hook event configurations for extending CLI behavior at various lifecycle points.",
    showInDialog: false,
    properties: {
      UserPromptSubmit: {
        type: "array",
        label: "Before Agent Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before agent processing. Can modify prompts or inject context.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      UserPromptExpansion: {
        type: "array",
        label: "Prompt Expansion Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a slash command expands into a prompt.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      Stop: {
        type: "array",
        label: "After Agent Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute after agent processing. Can post-process responses or log interactions.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      MessageDisplay: {
        type: "array",
        label: "Message Display Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute repeatedly as the assistant reply streams, before the After Agent (Stop) hooks fire.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      Notification: {
        type: "array",
        label: "Notification Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when notifications are sent.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PreToolUse: {
        type: "array",
        label: "Pre Tool Use Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before tool execution.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolUse: {
        type: "array",
        label: "Post Tool Use Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute after successful tool execution.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolUseFailure: {
        type: "array",
        label: "Post Tool Use Failure Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when tool execution fails. ",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolBatch: {
        type: "array",
        label: "Post Tool Batch Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute once after all tool calls in a batch resolve.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SessionStart: {
        type: "array",
        label: "Session Start Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a new session starts or resumes.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SessionEnd: {
        type: "array",
        label: "Session End Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a session ends.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PreCompact: {
        type: "array",
        label: "Pre Compact Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before conversation compaction.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SubagentStart: {
        type: "array",
        label: "Subagent Start Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a subagent (Task tool call) is started.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SubagentStop: {
        type: "array",
        label: "Subagent Stop Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute right before a subagent (Task tool call) concludes its response.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PermissionRequest: {
        type: "array",
        label: "Permission Request Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a permission dialog is displayed.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      }
    }
  },
  experimental: {
    type: "object",
    label: "Experimental",
    category: "Experimental",
    requiresRestart: true,
    default: {},
    description: "Settings to enable experimental features.",
    showInDialog: false,
    properties: {
      cron: {
        type: "boolean",
        label: "Enable Cron/Loop Tools",
        category: "Experimental",
        requiresRestart: true,
        default: true,
        description: "Enable in-session cron/loop tools. When enabled, the model can create recurring prompts using cron_create, cron_list, and cron_delete tools. Can be disabled via QWEN_CODE_DISABLE_CRON=1 environment variable.",
        showInDialog: true
      },
      cronRecurringMaxAgeDays: {
        type: "number",
        label: "Recurring Cron Max Age (Days)",
        category: "Experimental",
        requiresRestart: true,
        default: 7,
        description: "Days a recurring cron/loop job lives before auto-expiring (it fires one final time, then is deleted). Set to 0 to disable expiry so jobs run until deleted \u2014 useful for long-running daemon deployments. Can be overridden via the QWEN_CODE_CRON_MAX_AGE_DAYS environment variable.",
        // A deployment-time knob (cloud daemons, containers), not a common
        // interactive preference.
        showInDialog: false,
        jsonSchemaOverride: {
          type: "number",
          minimum: 0,
          default: 7
        }
      },
      agentTeam: {
        type: "boolean",
        label: "Enable Agent Team",
        category: "Experimental",
        requiresRestart: true,
        default: false,
        description: "Enable agent team collaboration tools (experimental). When enabled, the model can create agent teams and coordinate work using team_create, team_delete, send_message, task_create, task_update, and task_list tools. Can also be enabled via QWEN_CODE_ENABLE_AGENT_TEAM=1 environment variable.",
        showInDialog: true
      },
      artifact: {
        type: "boolean",
        label: "Enable Artifacts",
        category: "Experimental",
        requiresRestart: true,
        default: false,
        description: "Enable the Artifact tool (experimental). When enabled, the model can publish a self-contained HTML page as an interactive Artifact and open it in the browser. Interactive, non-SDK sessions only. QWEN_CODE_ENABLE_ARTIFACT=1 enables the metadata-only record_artifact tool for non-SDK daemon sessions, and also enables the Artifact tool in interactive sessions. QWEN_CODE_DISABLE_ARTIFACT=1 hard-disables both.",
        showInDialog: true
      },
      emitToolUseSummaries: {
        type: "boolean",
        label: "Tool Use Summaries",
        category: "Experimental",
        requiresRestart: false,
        default: true,
        description: "Generate a short LLM-based label after each tool batch completes. For a completed tool group the label replaces the generic `Tool \xD7 N` header; when the group is force-expanded it appears as a dim `\u25CF <label>` line below the tool group. Requires a fast model to be configured; runs in parallel with the next API call so latency is hidden. Currently affects interactive CLI rendering only \u2014 SDK / non-interactive emission of the `tool_use_summary` message is not yet wired (the message factory is exported for a follow-up PR). Can be overridden with QWEN_CODE_EMIT_TOOL_USE_SUMMARIES=0 or =1.",
        showInDialog: true
      }
    }
  },
  artifact: {
    type: "object",
    label: "Artifacts",
    category: "Experimental",
    requiresRestart: true,
    default: {},
    description: "Configuration for the experimental Artifact tool (enable it via experimental.artifact). Selects the publish backend and, for the host backend, the upload command and shareable URL template.",
    showInDialog: false,
    properties: {
      autoOpen: {
        type: "boolean",
        label: "Auto-open Artifacts",
        category: "Experimental",
        requiresRestart: true,
        default: true,
        description: "Open published artifacts in the browser automatically. Set to false to publish without launching a browser. QWEN_ARTIFACT_NO_AUTO_OPEN=1 overrides this setting.",
        showInDialog: false
      },
      publisher: {
        type: "enum",
        label: "Artifact Publisher",
        category: "Experimental",
        requiresRestart: true,
        default: "local",
        description: "Where artifacts are published: 'local' (a file:// page on disk, the default), 'host' (upload via artifact.host.uploadCommand and return a shareable link), or 'oss' (native Aliyun OSS upload).",
        showInDialog: false,
        options: [
          { value: "local", label: "Local (file://)" },
          { value: "host", label: "Host (shareable link)" },
          { value: "oss", label: "Aliyun OSS" }
        ]
      },
      host: {
        type: "object",
        label: "Artifact Host",
        category: "Experimental",
        requiresRestart: true,
        default: {},
        description: 'Host-backend config, used when artifact.publisher is "host".',
        showInDialog: false,
        properties: {
          uploadCommand: {
            type: "string",
            label: "Upload Command",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'Command that uploads the artifact, run with execFile (no shell). {file} = local HTML path, {key} = remote object key. e.g. "aws s3 cp {file} s3://bucket/{key} --content-type text/html".',
            showInDialog: false
          },
          urlTemplate: {
            type: "string",
            label: "URL Template",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'Shareable URL template; {key} is substituted. e.g. "https://bucket.example.com/{key}".',
            showInDialog: false
          },
          keyPrefix: {
            type: "string",
            label: "Key Prefix",
            category: "Experimental",
            requiresRestart: true,
            default: "artifacts",
            description: 'Remote key prefix; the object key is "{prefix}/{id}/index.html".',
            showInDialog: false
          }
        }
      },
      oss: {
        type: "object",
        label: "Artifact OSS",
        category: "Experimental",
        requiresRestart: true,
        default: {},
        description: 'Native Aliyun OSS backend, used when artifact.publisher is "oss". Credentials are read from OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_*), never from settings.',
        showInDialog: false,
        properties: {
          bucket: {
            type: "string",
            label: "OSS Bucket",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: "OSS bucket name.",
            showInDialog: false
          },
          endpoint: {
            type: "string",
            label: "OSS Endpoint",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'OSS endpoint host, e.g. "oss-cn-hangzhou.aliyuncs.com".',
            showInDialog: false
          },
          keyPrefix: {
            type: "string",
            label: "Key Prefix",
            category: "Experimental",
            requiresRestart: true,
            default: "artifacts",
            description: 'Remote key prefix; the object key is "{prefix}/{id}/index.html".',
            showInDialog: false
          },
          acl: {
            type: "string",
            label: "Object ACL",
            category: "Experimental",
            requiresRestart: true,
            default: "public-read",
            description: 'Object ACL applied on upload. "public-read" (default) makes the link shareable.',
            showInDialog: false
          },
          publicBaseUrl: {
            type: "string",
            label: "Public Base URL",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'Optional CDN / custom-domain base for the returned URL. Upload still goes through endpoint. e.g. "https://cdn.example.com".',
            showInDialog: false
          }
        }
      }
    }
  },
  worktree: {
    type: "object",
    label: "Worktree",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: 'Configuration for general-purpose git worktrees created by the CLI (the `enter_worktree` tool, the `agent isolation: "worktree"` parameter, and the startup `--worktree` flag). Does NOT affect Agent Arena worktrees \u2014 see `agents.arena.worktreeBaseDir` for those.',
    showInDialog: false,
    properties: {
      symlinkDirectories: {
        type: "array",
        label: "Symlink Directories Into Worktrees",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "Directories under the main repository to symlink into every general-purpose worktree on creation. Useful for sharing large opt-in dirs like `node_modules` so the model can run tests / builds inside the worktree without a fresh install. Paths must be relative to the repo root; absolute paths, anything containing `..`, and any path inside `.git` or `.qwen` (the CLI-managed metadata tree, which contains the worktrees directory itself) are rejected. Missing source dirs and existing destination paths are silently skipped (no overwrite, no failure).",
        showInDialog: false
      }
    }
  }
};
function getSettingsSchema() {
  const schema = SETTINGS_SCHEMA;
  if (schema["general"]?.properties?.["language"]) {
    schema["general"].properties["language"].options = getLanguageSettingsOptions();
  }
  return SETTINGS_SCHEMA;
}
__name(getSettingsSchema, "getSettingsSchema");

// packages/cli/src/utils/settingsUtils.ts
init_esbuild_shims();
import * as fs2 from "node:fs";

// packages/cli/src/utils/languageUtils.ts
init_esbuild_shims();
import * as fs from "node:fs";
import * as path from "node:path";
var LLM_OUTPUT_LANGUAGE_RULE_FILENAME = "output-language.md";
var LLM_OUTPUT_LANGUAGE_MARKER_PREFIX = "qwen-code:llm-output-language:";
var OUTPUT_LANGUAGE_AUTO = "auto";
function isAutoLanguage(value) {
  return !value || value.toLowerCase() === OUTPUT_LANGUAGE_AUTO;
}
__name(isAutoLanguage, "isAutoLanguage");
function normalizeOutputLanguage(language) {
  const normalized = language.trim().replace(/_/g, "-").toLowerCase();
  const knownLanguageName = SUPPORTED_LANGUAGES.find(
    (supportedLanguage) => supportedLanguage.fullName.toLowerCase() === normalized
  );
  if (knownLanguageName) {
    return knownLanguageName.fullName;
  }
  const knownLocaleCode = SUPPORTED_LANGUAGES.some((supportedLanguage) => {
    const code = supportedLanguage.code.toLowerCase();
    const id = supportedLanguage.id.toLowerCase();
    return normalized === code || normalized === id || normalized.startsWith(`${code}-`) || normalized.startsWith(`${id}-`) || normalized.startsWith(`${code}.`) || normalized.startsWith(`${id}.`) || normalized.startsWith(`${code}@`) || normalized.startsWith(`${id}@`);
  });
  if (!knownLocaleCode) {
    return language;
  }
  return getLanguageNameFromLocale(normalized);
}
__name(normalizeOutputLanguage, "normalizeOutputLanguage");
function resolveOutputLanguage(value) {
  if (isAutoLanguage(value)) {
    const detectedLocale = detectSystemLanguage();
    return getLanguageNameFromLocale(detectedLocale);
  }
  return normalizeOutputLanguage(value);
}
__name(resolveOutputLanguage, "resolveOutputLanguage");
function getOutputLanguageFilePath() {
  return path.join(
    Storage.getGlobalQwenDir(),
    LLM_OUTPUT_LANGUAGE_RULE_FILENAME
  );
}
__name(getOutputLanguageFilePath, "getOutputLanguageFilePath");
function sanitizeForMarker(language) {
  return language.replace(/[\r\n]/g, " ").replace(/--!?>/g, "").replace(/--/g, "");
}
__name(sanitizeForMarker, "sanitizeForMarker");
function generateOutputLanguageFileContent(language) {
  const safeLanguage = sanitizeForMarker(language);
  return `# Output language preference: ${language}
<!-- ${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX} ${safeLanguage} -->

## Rule
You MUST always respond in **${language}** regardless of the user's input language.
This is a mandatory requirement, not a preference.

## Exception
If the user **explicitly** requests a response in a specific language (e.g., "please reply in English", "\u7528\u4E2D\u6587\u56DE\u7B54"), switch to the user's requested language for the remainder of the conversation.

## Keep technical artifacts unchanged
Do **not** translate or rewrite:
- Code blocks, CLI commands, file paths, stack traces, logs, JSON keys, identifiers
- Exact quoted text from the user (keep quotes verbatim)

## Tool / system outputs
Raw tool/system outputs may contain fixed-format English. Preserve them verbatim, and if needed, add a short **${language}** explanation below.
`;
}
__name(generateOutputLanguageFileContent, "generateOutputLanguageFileContent");
function parseOutputLanguageFromContent(content) {
  const markerRegex = new RegExp(
    String.raw`<!--\s*${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX}\s*(.*?)\s*-->`,
    "i"
  );
  const markerMatch = content.match(markerRegex);
  if (markerMatch?.[1]?.trim()) {
    return markerMatch[1].trim();
  }
  const headingMatch = content.match(
    /^#.*?CRITICAL:\s*(.*?)\s+Output Language Rule\b/im
  );
  if (headingMatch?.[1]?.trim()) {
    return headingMatch[1].trim();
  }
  return null;
}
__name(parseOutputLanguageFromContent, "parseOutputLanguageFromContent");
function readOutputLanguageFromFile() {
  const filePath = getOutputLanguageFilePath();
  if (!fs.existsSync(filePath)) {
    return null;
  }
  try {
    const content = fs.readFileSync(filePath, "utf-8");
    return parseOutputLanguageFromContent(content);
  } catch {
    return null;
  }
}
__name(readOutputLanguageFromFile, "readOutputLanguageFromFile");
function writeOutputLanguageFile(language, targetPath) {
  const filePath = targetPath ?? getOutputLanguageFilePath();
  const content = generateOutputLanguageFileContent(language);
  const dir = path.dirname(filePath);
  fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(filePath, content, "utf-8");
}
__name(writeOutputLanguageFile, "writeOutputLanguageFile");
function updateOutputLanguageFile(settingValue, targetPath) {
  const resolved = resolveOutputLanguage(settingValue);
  writeOutputLanguageFile(resolved, targetPath);
}
__name(updateOutputLanguageFile, "updateOutputLanguageFile");
function writeOutputLanguageAndRegisterPath(settingValue, config) {
  const targetPath = config?.getOutputLanguageFilePath();
  updateOutputLanguageFile(settingValue, targetPath);
  if (!targetPath) {
    config?.setOutputLanguageFilePath(getOutputLanguageFilePath());
  }
}
__name(writeOutputLanguageAndRegisterPath, "writeOutputLanguageAndRegisterPath");
function initializeLlmOutputLanguage(outputLanguage) {
  const currentFileLanguage = readOutputLanguageFromFile();
  if (currentFileLanguage) {
    return;
  }
  const resolved = resolveOutputLanguage(outputLanguage);
  writeOutputLanguageFile(resolved);
}
__name(initializeLlmOutputLanguage, "initializeLlmOutputLanguage");

// packages/cli/src/utils/settingsUtils.ts
function flattenSchema(schema, prefix = "") {
  let result = {};
  for (const key in schema) {
    const newKey = prefix ? `${prefix}.${key}` : key;
    const definition = schema[key];
    result[newKey] = { ...definition, key: newKey };
    if (definition.properties) {
      result = { ...result, ...flattenSchema(definition.properties, newKey) };
    }
  }
  return result;
}
__name(flattenSchema, "flattenSchema");
var _FLATTENED_SCHEMA;
function getFlattenedSchema() {
  return _FLATTENED_SCHEMA ?? (_FLATTENED_SCHEMA = flattenSchema(getSettingsSchema()));
}
__name(getFlattenedSchema, "getFlattenedSchema");
function getSettingDefinition(key) {
  return getFlattenedSchema()[key];
}
__name(getSettingDefinition, "getSettingDefinition");
function requiresRestart(key) {
  return getFlattenedSchema()[key]?.requiresRestart ?? false;
}
__name(requiresRestart, "requiresRestart");
function getDefaultValue(key) {
  return getFlattenedSchema()[key]?.default;
}
__name(getDefaultValue, "getDefaultValue");
function getNestedValue(obj, path3) {
  const [first, ...rest] = path3;
  if (!first || !(first in obj)) {
    return void 0;
  }
  const value = obj[first];
  if (rest.length === 0) {
    return value;
  }
  if (value && typeof value === "object" && value !== null) {
    return getNestedValue(value, rest);
  }
  return void 0;
}
__name(getNestedValue, "getNestedValue");
function getNestedProperty(obj, path3) {
  return getNestedValue(obj, path3.split("."));
}
__name(getNestedProperty, "getNestedProperty");
function getEffectiveValue(key, settings, mergedSettings) {
  const definition = getSettingDefinition(key);
  if (!definition) {
    return void 0;
  }
  const path3 = key.split(".");
  let value = getNestedValue(settings, path3);
  if (value !== void 0) {
    return value;
  }
  value = getNestedValue(mergedSettings, path3);
  if (value !== void 0) {
    return value;
  }
  return definition.default;
}
__name(getEffectiveValue, "getEffectiveValue");
function getAllSettingKeys() {
  return Object.keys(getFlattenedSchema());
}
__name(getAllSettingKeys, "getAllSettingKeys");
var SETTINGS_DIALOG_ORDER = [
  // Workflow Control - most impactful setting
  "tools.approvalMode",
  // Localization - users often set this first
  "general.language",
  "general.outputLanguage",
  // Theme
  "ui.theme",
  // Editor/Shell Experience
  "general.vimMode",
  "tools.shell.enableInteractiveShell",
  // Display Preferences
  "general.preferredEditor",
  "ide.enabled",
  "ui.showLineNumbers",
  "ui.hideTips",
  "general.terminalBell",
  "ui.enableWelcomeBack",
  // Git Behavior
  "general.gitCoAuthor.commit",
  "general.gitCoAuthor.pr",
  // File Filtering
  "context.fileFiltering.respectGitIgnore",
  "context.fileFiltering.respectQwenIgnore",
  // System Settings - rarely changed
  "general.disableAutoUpdate",
  // Privacy
  "privacy.usageStatisticsEnabled"
];
var MAX_SETTING_STRING_VALUE_LENGTH = 1024;
function validateSettingValue(def, value) {
  switch (def.type) {
    case "boolean":
      if (typeof value !== "boolean") return "Value must be a boolean";
      break;
    case "number":
      if (typeof value !== "number" || !Number.isFinite(value))
        return "Value must be a finite number";
      if (def.minimum !== void 0 && value < def.minimum)
        return `Value must be >= ${def.minimum}`;
      if (def.maximum !== void 0 && value > def.maximum)
        return `Value must be <= ${def.maximum}`;
      break;
    case "integer":
      if (typeof value !== "number" || !Number.isFinite(value))
        return "Value must be a finite integer";
      if (!Number.isInteger(value)) return "Value must be an integer";
      if (def.minimum !== void 0 && value < def.minimum)
        return `Value must be >= ${def.minimum}`;
      if (def.maximum !== void 0 && value > def.maximum)
        return `Value must be <= ${def.maximum}`;
      break;
    case "string":
      if (typeof value !== "string") return "Value must be a string";
      if (value.length > MAX_SETTING_STRING_VALUE_LENGTH)
        return `Value exceeds ${MAX_SETTING_STRING_VALUE_LENGTH}-character limit`;
      break;
    case "enum":
      if (!def.options?.some((opt) => opt.value === value)) {
        const allowed = def.options?.map((o) => o.value).join(", ") ?? "";
        return `Value must be one of: ${allowed}`;
      }
      break;
    case "object":
      if (!value || typeof value !== "object" || Array.isArray(value)) {
        return "Value must be an object";
      }
      break;
    default:
      return `Settings of type '${def.type}' cannot be modified via this API`;
  }
  return void 0;
}
__name(validateSettingValue, "validateSettingValue");
function getDialogSettingKeys() {
  const dialogSettings = Object.values(getFlattenedSchema()).filter((definition) => definition.showInDialog === true).map((definition) => definition.key);
  return dialogSettings.sort((a, b) => {
    const indexA = SETTINGS_DIALOG_ORDER.indexOf(a);
    const indexB = SETTINGS_DIALOG_ORDER.indexOf(b);
    if (indexA !== -1 && indexB !== -1) {
      return indexA - indexB;
    }
    if (indexA !== -1) return -1;
    if (indexB !== -1) return 1;
    return 0;
  });
}
__name(getDialogSettingKeys, "getDialogSettingKeys");
function settingExistsInScope(key, scopeSettings) {
  const path3 = key.split(".");
  const value = getNestedValue(scopeSettings, path3);
  return value !== void 0;
}
__name(settingExistsInScope, "settingExistsInScope");
function pathHasUnsafeSegment(keys) {
  for (const key of keys) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      return true;
    }
  }
  return false;
}
__name(pathHasUnsafeSegment, "pathHasUnsafeSegment");
function setNestedPropertyForce(obj, path3, value) {
  const keys = path3.split(".");
  if (pathHasUnsafeSegment(keys)) return;
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    if (!current[key] || typeof current[key] !== "object") {
      current[key] = {};
    }
    current = current[key];
  }
  current[lastKey] = value;
}
__name(setNestedPropertyForce, "setNestedPropertyForce");
function setNestedPropertySafe(obj, path3, value) {
  const keys = path3.split(".");
  if (pathHasUnsafeSegment(keys)) return;
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    if (current[key] === void 0) {
      current[key] = {};
    }
    const next = current[key];
    if (typeof next === "object" && next !== null) {
      current = next;
    } else {
      return;
    }
  }
  current[lastKey] = value;
}
__name(setNestedPropertySafe, "setNestedPropertySafe");
function deleteNestedPropertySafe(obj, path3) {
  const keys = path3.split(".");
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    const next = current[key];
    if (typeof next !== "object" || next === null) {
      return;
    }
    current = next;
  }
  delete current[lastKey];
}
__name(deleteNestedPropertySafe, "deleteNestedPropertySafe");
function setPendingSettingValue(key, value, pendingSettings) {
  const newSettings = JSON.parse(JSON.stringify(pendingSettings));
  setNestedPropertyForce(newSettings, key, value);
  return newSettings;
}
__name(setPendingSettingValue, "setPendingSettingValue");
function setPendingSettingValueAny(key, value, pendingSettings) {
  const newSettings = structuredClone(pendingSettings);
  setNestedPropertyForce(newSettings, key, value);
  return newSettings;
}
__name(setPendingSettingValueAny, "setPendingSettingValueAny");
function getRestartRequiredFromModified(modifiedSettings) {
  return Array.from(modifiedSettings).filter((key) => requiresRestart(key));
}
__name(getRestartRequiredFromModified, "getRestartRequiredFromModified");
function saveModifiedSettings(modifiedSettings, pendingSettings, loadedSettings, scope) {
  modifiedSettings.forEach((settingKey) => {
    const path3 = settingKey.split(".");
    const value = getNestedValue(
      pendingSettings,
      path3
    );
    const existsInOriginalFile = settingExistsInScope(
      settingKey,
      loadedSettings.forScope(scope).settings
    );
    if (value === void 0) {
      if (existsInOriginalFile) {
        loadedSettings.setValue(scope, settingKey, void 0);
      }
      return;
    }
    const isDefaultValue2 = value === getDefaultValue(settingKey);
    if (existsInOriginalFile || !isDefaultValue2) {
      loadedSettings.setValue(scope, settingKey, value);
    }
  });
}
__name(saveModifiedSettings, "saveModifiedSettings");
function getDisplayValue(key, settings, _mergedSettings, modifiedSettings, pendingSettings) {
  const definition = getSettingDefinition(key);
  let value;
  if (pendingSettings && settingExistsInScope(key, pendingSettings)) {
    value = getEffectiveValue(key, pendingSettings, {});
  } else if (settingExistsInScope(key, settings)) {
    value = getEffectiveValue(key, settings, {});
  } else {
    value = getDefaultValue(key);
  }
  let valueString = String(value);
  if (key === "general.outputLanguage" && isAutoLanguage(value)) {
    valueString = t("Auto (detect from system)");
  } else if (definition?.type === "enum" && definition.options) {
    const option = definition.options?.find((option2) => option2.value === value);
    if (option?.label) {
      valueString = t(option.label) || option.label;
    } else {
      valueString = `${value}`;
    }
  }
  const defaultValue = getDefaultValue(key);
  const isChangedFromDefault = value !== defaultValue;
  const isInModifiedSettings = modifiedSettings.has(key);
  if (settingExistsInScope(key, settings) || isInModifiedSettings) {
    return `${valueString}*`;
  }
  if (isChangedFromDefault || isInModifiedSettings) {
    return `${valueString}*`;
  }
  return valueString;
}
__name(getDisplayValue, "getDisplayValue");
function isDefaultValue(key, settings) {
  return !settingExistsInScope(key, settings);
}
__name(isDefaultValue, "isDefaultValue");
function backupSettingsFile(filePath) {
  try {
    if (fs2.existsSync(filePath)) {
      const backupPath = `${filePath}.orig`;
      fs2.copyFileSync(filePath, backupPath);
      return true;
    }
  } catch (_e) {
  }
  return false;
}
__name(backupSettingsFile, "backupSettingsFile");
function restoreSettingsFromBackup(filePath) {
  try {
    const backupPath = `${filePath}.orig`;
    if (fs2.existsSync(backupPath)) {
      fs2.copyFileSync(backupPath, filePath);
      fs2.unlinkSync(backupPath);
      return true;
    }
  } catch (err) {
    console.error(
      `[settingsUtils] restoreSettingsFromBackup(${filePath}) failed:`,
      err
    );
  }
  return false;
}
__name(restoreSettingsFromBackup, "restoreSettingsFromBackup");
function cleanupSettingsBackup(filePath) {
  try {
    const backupPath = `${filePath}.orig`;
    if (fs2.existsSync(backupPath)) {
      fs2.unlinkSync(backupPath);
    }
  } catch (_e) {
  }
}
__name(cleanupSettingsBackup, "cleanupSettingsBackup");

// packages/cli/src/utils/deepMerge.ts
init_esbuild_shims();
function isPlainObject(item) {
  return !!item && typeof item === "object" && !Array.isArray(item);
}
__name(isPlainObject, "isPlainObject");
function mergeRecursively(target, source, getMergeStrategyForPath2, path3 = []) {
  for (const key of Object.keys(source)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      continue;
    }
    const newPath = [...path3, key];
    const srcValue = source[key];
    const objValue = target[key];
    const mergeStrategy = getMergeStrategyForPath2(newPath);
    if (mergeStrategy === "shallow_merge" /* SHALLOW_MERGE */ && objValue && srcValue) {
      const obj1 = typeof objValue === "object" && objValue !== null ? objValue : {};
      const obj2 = typeof srcValue === "object" && srcValue !== null ? srcValue : {};
      target[key] = { ...obj1, ...obj2 };
      continue;
    }
    if (Array.isArray(objValue)) {
      const srcArray = Array.isArray(srcValue) ? srcValue : [srcValue];
      if (mergeStrategy === "concat" /* CONCAT */) {
        target[key] = objValue.concat(srcArray);
        continue;
      }
      if (mergeStrategy === "union" /* UNION */) {
        target[key] = [...new Set(objValue.concat(srcArray))];
        continue;
      }
    }
    if (isPlainObject(objValue) && isPlainObject(srcValue)) {
      mergeRecursively(objValue, srcValue, getMergeStrategyForPath2, newPath);
    } else if (isPlainObject(srcValue)) {
      target[key] = {};
      mergeRecursively(
        target[key],
        srcValue,
        getMergeStrategyForPath2,
        newPath
      );
    } else {
      target[key] = srcValue;
    }
  }
  return target;
}
__name(mergeRecursively, "mergeRecursively");
function customDeepMerge(getMergeStrategyForPath2, ...sources) {
  const result = {};
  for (const source of sources) {
    if (source) {
      mergeRecursively(result, source, getMergeStrategyForPath2);
    }
  }
  return result;
}
__name(customDeepMerge, "customDeepMerge");

// packages/cli/src/config/migration/index.ts
init_esbuild_shims();

// packages/cli/src/config/migration/scheduler.ts
init_esbuild_shims();
var debugLogger = createDebugLogger("SETTINGS_MIGRATION");
function formatScope(scope) {
  if (scope === "SystemDefaults") {
    return "system default";
  }
  return scope.toLowerCase();
}
__name(formatScope, "formatScope");
var MigrationScheduler = class {
  /**
   * Creates a new MigrationScheduler with the given migrations.
   *
   * @param migrations - Array of migrations in execution order (typically ascending version)
   * @param scope - The scope of settings being migrated
   */
  constructor(migrations, scope) {
    this.migrations = migrations;
    this.scope = scope;
  }
  static {
    __name(this, "MigrationScheduler");
  }
  /**
   * Executes the migration chain on the given settings.
   *
   * Iterates through all registered migrations in order. For each migration:
   * 1. Calls `shouldMigrate` with the current settings
   * 2. If true, calls `migrate` to transform the settings
   * 3. Records the execution
   *
   * The scheduler itself has no version awareness - all version detection
   * is delegated to the individual migrations.
   *
   * @param settings - The settings object to migrate
   * @returns MigrationResult containing the final settings, version, and execution log
   */
  migrate(settings) {
    debugLogger.debug("MigrationScheduler: Starting migration chain");
    let current = settings;
    const executed = [];
    const allWarnings = [];
    for (const migration of this.migrations) {
      try {
        if (migration.shouldMigrate(current)) {
          debugLogger.debug(
            `MigrationScheduler: Executing migration ${migration.fromVersion} \u2192 ${migration.toVersion}`
          );
          const formattedScope = formatScope(this.scope);
          const result = migration.migrate(current, formattedScope);
          current = result.settings;
          allWarnings.push(...result.warnings);
          executed.push({
            fromVersion: migration.fromVersion,
            toVersion: migration.toVersion
          });
          debugLogger.debug(
            `MigrationScheduler: Migration ${migration.fromVersion} \u2192 ${migration.toVersion} completed successfully`
          );
        }
      } catch (error) {
        debugLogger.error(
          `MigrationScheduler: Migration ${migration.fromVersion} \u2192 ${migration.toVersion} failed:`,
          error
        );
        throw error;
      }
    }
    const finalVersion = current["$version"] ?? 1;
    debugLogger.debug(
      `MigrationScheduler: Migration chain complete. Final version: ${finalVersion}, Executed: ${executed.length} migrations`
    );
    return {
      settings: current,
      finalVersion,
      executedMigrations: executed,
      warnings: allWarnings
    };
  }
};

// packages/cli/src/config/migration/versions/v1-to-v2.ts
init_esbuild_shims();
var V1ToV2Migration = class {
  static {
    __name(this, "V1ToV2Migration");
  }
  fromVersion = 1;
  toVersion = 2;
  /**
   * Determines whether this migration should execute.
   *
   * Decision strategy:
   * - Hard-stop when `$version` is a number >= 2 (already V2+).
   * - Otherwise, scan indicator keys and trigger only when at least one indicator is
   *   still in legacy top-level shape (primitive/array/null).
   *
   * Mixed-shape tolerance:
   * - Files that are partially migrated are supported; V2-like object-valued indicators
   *   are ignored while legacy-shaped indicators can still trigger migration.
   */
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    const version = s["$version"];
    if (typeof version === "number" && version >= 2) {
      return false;
    }
    return V1_INDICATOR_KEYS.some((key) => {
      if (!(key in s)) {
        return false;
      }
      const value = s[key];
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        return false;
      }
      return true;
    });
  }
  /**
   * Performs non-destructive V1 -> V2 transformation.
   *
   * Detailed strategy:
   * 1) Relocate known V1 keys using `V1_TO_V2_MIGRATION_MAP`.
   *    - If a source value is already an object and maps to a child path of itself
   *      (partial V2 shape), merge child properties into target path.
   * 2) Relocate disable* keys into V2 disable* locations.
   *    - Consolidated keys (`disableAutoUpdate`, `disableUpdateNag`): normalize to
   *      boolean with stable-compatible presence semantics (`value === true`).
   *    - Other disable* keys: migrate only boolean values.
   * 3) Preserve `mcpServers` top-level placement.
   * 4) Carry over remaining keys:
   *    - If a key is parent of migrated nested paths, merge unprocessed object children.
   *    - If parent value is non-object, preserve that scalar/array/null as-is.
   *    - Otherwise copy untouched key/value.
   * 5) Stamp `$version = 2`.
   *
   * The method is pure with respect to input mutation.
   */
  migrate(settings, _scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const source = settings;
    const result = {};
    const processedKeys = /* @__PURE__ */ new Set();
    const warnings = [];
    for (const [v1Key, v2Path] of Object.entries(V1_TO_V2_MIGRATION_MAP)) {
      if (v1Key in source) {
        const value = source[v1Key];
        if (V2_CONTAINER_KEYS.has(v1Key) && typeof value === "object" && value !== null && !Array.isArray(value)) {
          result[v1Key] = value;
          processedKeys.add(v1Key);
          continue;
        }
        if (typeof value === "object" && value !== null && !Array.isArray(value) && v2Path.startsWith(v1Key + ".")) {
          for (const [nestedKey, nestedValue] of Object.entries(value)) {
            setNestedPropertySafe(
              result,
              `${v2Path}.${nestedKey}`,
              nestedValue
            );
          }
        } else {
          setNestedPropertySafe(result, v2Path, value);
        }
        processedKeys.add(v1Key);
      }
    }
    for (const [v1Key, v2Path] of Object.entries(
      V1_TO_V2_PRESERVE_DISABLE_MAP
    )) {
      if (v1Key in source) {
        const value = source[v1Key];
        if (CONSOLIDATED_DISABLE_KEYS.has(v1Key)) {
          setNestedPropertySafe(result, v2Path, value === true);
        } else if (typeof value === "boolean") {
          setNestedPropertySafe(result, v2Path, value);
        }
        processedKeys.add(v1Key);
      }
    }
    if ("mcpServers" in source) {
      result["mcpServers"] = source["mcpServers"];
      processedKeys.add("mcpServers");
    }
    for (const key of Object.keys(source)) {
      if (!processedKeys.has(key)) {
        const isParentOfMigratedPath = Array.from(processedKeys).some(
          (processedKey) => {
            const v2Path = V1_TO_V2_MIGRATION_MAP[processedKey] || V1_TO_V2_PRESERVE_DISABLE_MAP[processedKey];
            if (!v2Path) return false;
            return v2Path.startsWith(key + ".");
          }
        );
        if (isParentOfMigratedPath) {
          const existingValue = source[key];
          if (typeof existingValue === "object" && existingValue !== null && !Array.isArray(existingValue)) {
            for (const [nestedKey, nestedValue] of Object.entries(
              existingValue
            )) {
              const fullNestedPath = `${key}.${nestedKey}`;
              const wasProcessed = Array.from(processedKeys).some(
                (processedKey) => {
                  const v2Path = V1_TO_V2_MIGRATION_MAP[processedKey] || V1_TO_V2_PRESERVE_DISABLE_MAP[processedKey];
                  return v2Path === fullNestedPath;
                }
              );
              if (!wasProcessed) {
                setNestedPropertySafe(result, fullNestedPath, nestedValue);
              }
            }
          } else {
            result[key] = source[key];
          }
        } else {
          result[key] = source[key];
        }
      }
    }
    result["$version"] = 2;
    return { settings: result, warnings };
  }
};
var v1ToV2Migration = new V1ToV2Migration();

// packages/cli/src/config/migration/versions/v2-to-v3.ts
init_esbuild_shims();
var V2_TO_V3_BOOLEAN_MAP = {
  "general.disableAutoUpdate": "general.enableAutoUpdate",
  "general.disableUpdateNag": "general.enableAutoUpdate",
  "ui.accessibility.disableLoadingPhrases": "ui.accessibility.enableLoadingPhrases",
  "context.fileFiltering.disableFuzzySearch": "context.fileFiltering.enableFuzzySearch",
  "model.generationConfig.disableCacheControl": "model.generationConfig.enableCacheControl"
};
var CONSOLIDATED_V2_PATHS = {
  "general.enableAutoUpdate": [
    "general.disableAutoUpdate",
    "general.disableUpdateNag"
  ]
};
function normalizeDisableValue(value) {
  if (value === void 0) {
    return { isPresent: false, isValid: false };
  }
  if (typeof value === "boolean") {
    return { isPresent: true, isValid: true, booleanValue: value };
  }
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (normalized === "true") {
      return { isPresent: true, isValid: true, booleanValue: true };
    }
    if (normalized === "false") {
      return { isPresent: true, isValid: true, booleanValue: false };
    }
  }
  return { isPresent: true, isValid: false };
}
__name(normalizeDisableValue, "normalizeDisableValue");
var V2ToV3Migration = class {
  static {
    __name(this, "V2ToV3Migration");
  }
  fromVersion = 2;
  toVersion = 3;
  /**
   * Migration trigger rule.
   *
   * Execute only when `$version === 2`.
   * This includes V2 files with no migratable disable* booleans so that version
   * metadata still advances to 3.
   */
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    return s["$version"] === 2;
  }
  /**
   * Applies V2 -> V3 transformation with deterministic deprecated-key cleanup.
   *
   * Detailed strategy:
   * 1) Clone input.
   * 2) Process consolidated paths first:
   *    - Inspect each source path.
   *    - Normalize each present value (boolean / coercible string / invalid).
   *    - Always delete present deprecated source key.
   *    - Valid normalized values contribute to aggregate.
   *    - Invalid values emit warnings.
   *    - Emit consolidated target when at least one valid source was consumed.
   * 3) Process remaining one-to-one mappings:
   *    - For each unmapped source, normalize value.
   *    - If valid -> delete old key and write inverted target.
   *    - If invalid -> delete old key and emit warning.
   * 4) Set `$version = 3`.
   *
   * Guarantees:
   * - Input object is not mutated.
   * - Valid migration and invalid cleanup are deterministic.
   * - Deprecated disable* keys are not retained after migration.
   */
  migrate(settings, scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const result = structuredClone(settings);
    const processedPaths = /* @__PURE__ */ new Set();
    const warnings = [];
    for (const [newPath, oldPaths] of Object.entries(CONSOLIDATED_V2_PATHS)) {
      let hasAnyDisable = false;
      let hasAnyBooleanValue = false;
      for (const oldPath of oldPaths) {
        const oldValue = getNestedProperty(result, oldPath);
        const normalized = normalizeDisableValue(oldValue);
        if (!normalized.isPresent) {
          continue;
        }
        deleteNestedPropertySafe(result, oldPath);
        processedPaths.add(oldPath);
        if (normalized.isValid) {
          hasAnyBooleanValue = true;
          if (normalized.booleanValue === true) {
            hasAnyDisable = true;
          }
        } else {
          warnings.push(
            `Removed deprecated setting '${oldPath}' from ${scope} settings because the value is invalid. Expected boolean.`
          );
        }
      }
      if (hasAnyBooleanValue) {
        setNestedPropertySafe(result, newPath, !hasAnyDisable);
      }
    }
    for (const [oldPath, newPath] of Object.entries(V2_TO_V3_BOOLEAN_MAP)) {
      if (processedPaths.has(oldPath)) {
        continue;
      }
      const oldValue = getNestedProperty(result, oldPath);
      const normalized = normalizeDisableValue(oldValue);
      if (!normalized.isPresent) {
        continue;
      }
      deleteNestedPropertySafe(result, oldPath);
      if (normalized.isValid) {
        setNestedPropertySafe(result, newPath, !normalized.booleanValue);
      } else {
        warnings.push(
          `Removed deprecated setting '${oldPath}' from ${scope} settings because the value is invalid. Expected boolean or string "true"/"false".`
        );
      }
    }
    result["$version"] = 3;
    return { settings: result, warnings };
  }
};
var v2ToV3Migration = new V2ToV3Migration();

// packages/cli/src/config/migration/versions/v3-to-v4.ts
init_esbuild_shims();
var GIT_CO_AUTHOR_PATH = "general.gitCoAuthor";
var V3ToV4Migration = class {
  static {
    __name(this, "V3ToV4Migration");
  }
  fromVersion = 3;
  toVersion = 4;
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    if (s["$version"] === 3) {
      return true;
    }
    if (s["$version"] === void 0) {
      const value = getNestedProperty(s, GIT_CO_AUTHOR_PATH);
      if (value === void 0) return false;
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        return false;
      }
      return true;
    }
    return false;
  }
  migrate(settings, scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const result = structuredClone(settings);
    const warnings = [];
    const value = getNestedProperty(result, GIT_CO_AUTHOR_PATH);
    if (typeof value === "boolean") {
      setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
        commit: value,
        pr: value
      });
    } else if (typeof value === "string") {
      const lowered = value.trim().toLowerCase();
      const disableIntent = ["false", "no", "off", "0", "disabled", ""];
      const enableIntent = ["true", "yes", "on", "1", "enabled"];
      if (enableIntent.includes(lowered)) {
        setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
          commit: true,
          pr: true
        });
      } else if (disableIntent.includes(lowered)) {
        setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
          commit: false,
          pr: false
        });
      } else {
        setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
          commit: false,
          pr: false
        });
        warnings.push(
          `Reset '${GIT_CO_AUTHOR_PATH}' in ${scope} settings to {commit: false, pr: false} because the stored string '${value}' was not a recognized boolean form.`
        );
      }
    } else if (value !== void 0 && (typeof value !== "object" || value === null || Array.isArray(value))) {
      setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
        commit: false,
        pr: false
      });
      warnings.push(
        `Reset '${GIT_CO_AUTHOR_PATH}' in ${scope} settings to {commit: false, pr: false} because the stored value was not a boolean or object.`
      );
    }
    result["$version"] = 4;
    return { settings: result, warnings };
  }
};
var v3ToV4Migration = new V3ToV4Migration();

// packages/cli/src/config/migration/versions/v5-to-v4.ts
init_esbuild_shims();
var PROVIDER_KEY_TO_PROTOCOL = {
  openai: "openai",
  "qwen-oauth": "qwen-oauth",
  gemini: "gemini",
  "vertex-ai": "gemini",
  anthropic: "anthropic"
};
function isWrappedProviderConfig(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isWrappedProviderConfig, "isWrappedProviderConfig");
var V5ToV4Migration = class {
  static {
    __name(this, "V5ToV4Migration");
  }
  fromVersion = 5;
  toVersion = 4;
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    if (s["$version"] === 5) {
      return true;
    }
    if (s["$version"] !== void 0) {
      return false;
    }
    const modelProviders = s["modelProviders"];
    if (typeof modelProviders !== "object" || modelProviders === null) {
      return false;
    }
    return Object.values(modelProviders).some(
      (v) => isWrappedProviderConfig(v)
    );
  }
  migrate(settings, _scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const result = structuredClone(settings);
    const warnings = [];
    const modelProviders = result["modelProviders"];
    if (typeof modelProviders === "object" && modelProviders !== null) {
      const providers = modelProviders;
      for (const [key, value] of Object.entries(providers)) {
        if (Array.isArray(value)) {
          continue;
        }
        if (!isWrappedProviderConfig(value)) {
          continue;
        }
        const derivedProtocol = Object.hasOwn(PROVIDER_KEY_TO_PROTOCOL, key) ? PROVIDER_KEY_TO_PROTOCOL[key] : void 0;
        if (typeof value.protocol === "string" && derivedProtocol !== void 0 && value.protocol !== derivedProtocol) {
          warnings.push(
            `Provider "${key}" declared protocol "${value.protocol}", but V4 derives protocol "${derivedProtocol}" from the provider key. The explicit protocol has been dropped.`
          );
        }
        providers[key] = Array.isArray(value.models) ? value.models : [];
      }
    }
    result["$version"] = 4;
    return { settings: result, warnings };
  }
};
var v5ToV4Migration = new V5ToV4Migration();

// packages/cli/src/config/migration/index.ts
var ALL_MIGRATIONS = [
  v1ToV2Migration,
  v2ToV3Migration,
  v3ToV4Migration
];
var DOWNGRADE_MIGRATIONS = [v5ToV4Migration];
var CONVERGENCE_MIGRATIONS = [
  ...ALL_MIGRATIONS,
  ...DOWNGRADE_MIGRATIONS
];
function runMigrations(settings, scope) {
  const scheduler = new MigrationScheduler([...CONVERGENCE_MIGRATIONS], scope);
  return scheduler.migrate(settings);
}
__name(runMigrations, "runMigrations");
function needsMigration(settings) {
  if (typeof settings !== "object" || settings === null) {
    return false;
  }
  const s = settings;
  const version = s["$version"];
  const hasApplicableMigration = CONVERGENCE_MIGRATIONS.some(
    (migration) => migration.shouldMigrate(settings)
  );
  if (typeof version === "number") {
    if (version === SETTINGS_VERSION) {
      return false;
    }
    return hasApplicableMigration;
  }
  return hasApplicableMigration;
}
__name(needsMigration, "needsMigration");

// packages/cli/src/config/settings.ts
var debugLogger2 = createDebugLogger("SETTINGS");
function getMergeStrategyForPath(path3) {
  let current = void 0;
  let currentSchema = getSettingsSchema();
  for (const key of path3) {
    if (!currentSchema || !currentSchema[key]) {
      return void 0;
    }
    current = currentSchema[key];
    currentSchema = current.properties;
  }
  return current?.mergeStrategy;
}
__name(getMergeStrategyForPath, "getMergeStrategyForPath");
function getUserSettingsPath() {
  return Storage.getGlobalSettingsPath();
}
__name(getUserSettingsPath, "getUserSettingsPath");
function getUserSettingsDir() {
  return path2.dirname(getUserSettingsPath());
}
__name(getUserSettingsDir, "getUserSettingsDir");
var SETTINGS_VERSION = 4;
var SETTINGS_VERSION_KEY = "$version";
function migrateLegacyPermissions(settings) {
  const tools = settings["tools"];
  if (!tools) return null;
  const hasLegacy = Array.isArray(tools["core"]) || Array.isArray(tools["allowed"]) || Array.isArray(tools["exclude"]);
  if (!hasLegacy) return null;
  const result = structuredClone(settings);
  const resultTools = result["tools"];
  const permissions = result["permissions"] ?? {};
  result["permissions"] = permissions;
  const mergeInto = /* @__PURE__ */ __name((key, items) => {
    const existing = Array.isArray(permissions[key]) ? permissions[key] : [];
    const merged = Array.from(/* @__PURE__ */ new Set([...existing, ...items]));
    permissions[key] = merged;
  }, "mergeInto");
  if (Array.isArray(resultTools["allowed"])) {
    mergeInto("allow", resultTools["allowed"]);
    delete resultTools["allowed"];
  }
  if (Array.isArray(resultTools["exclude"])) {
    mergeInto("deny", resultTools["exclude"]);
    delete resultTools["exclude"];
  }
  if (Array.isArray(resultTools["core"])) {
    mergeInto("allow", resultTools["core"]);
    delete resultTools["core"];
  }
  return result;
}
__name(migrateLegacyPermissions, "migrateLegacyPermissions");
var SettingScope = /* @__PURE__ */ ((SettingScope2) => {
  SettingScope2["User"] = "User";
  SettingScope2["Workspace"] = "Workspace";
  SettingScope2["System"] = "System";
  SettingScope2["SystemDefaults"] = "SystemDefaults";
  return SettingScope2;
})(SettingScope || {});
function getSettingsFileKeyWarnings(settings, settingsFilePath) {
  const version = settings[SETTINGS_VERSION_KEY];
  if (typeof version !== "number" || version < SETTINGS_VERSION) {
    return [];
  }
  const warnings = [];
  const ignoredLegacyKeys = /* @__PURE__ */ new Set();
  for (const [oldKey, newPath] of Object.entries(V1_TO_V2_MIGRATION_MAP)) {
    if (oldKey === newPath) {
      continue;
    }
    if (!(oldKey in settings)) {
      continue;
    }
    const oldValue = settings[oldKey];
    if (V2_CONTAINER_KEYS.has(oldKey) && typeof oldValue === "object" && oldValue !== null && !Array.isArray(oldValue)) {
      continue;
    }
    ignoredLegacyKeys.add(oldKey);
    warnings.push(
      `Warning: Legacy setting '${oldKey}' will be ignored in ${settingsFilePath}. Please use '${newPath}' instead.`
    );
  }
  const schemaKeys = new Set(Object.keys(getSettingsSchema()));
  for (const key of Object.keys(settings)) {
    if (key === SETTINGS_VERSION_KEY) {
      continue;
    }
    if (ignoredLegacyKeys.has(key)) {
      continue;
    }
    if (schemaKeys.has(key)) {
      continue;
    }
    debugLogger2.warn(
      `Unknown setting '${key}' will be ignored in ${settingsFilePath}.`
    );
  }
  return warnings;
}
__name(getSettingsFileKeyWarnings, "getSettingsFileKeyWarnings");
function isPlainObject2(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isPlainObject2, "isPlainObject");
function hasAnyProviderEntries(modelProviders) {
  if (!isPlainObject2(modelProviders)) {
    return false;
  }
  return Object.values(modelProviders).some(
    (providerModels) => Array.isArray(providerModels) && providerModels.length > 0
  );
}
__name(hasAnyProviderEntries, "hasAnyProviderEntries");
function getModelProvidersOverrideWarnings(loadedSettings) {
  if (!loadedSettings.isTrusted) {
    return [];
  }
  const userOriginal = loadedSettings.user.originalSettings;
  const workspaceOriginal = loadedSettings.workspace.originalSettings;
  if (!hasOwnModelProviders(userOriginal) || !hasOwnModelProviders(workspaceOriginal)) {
    return [];
  }
  const userModelProviders = userOriginal["modelProviders"];
  const workspaceModelProviders = workspaceOriginal["modelProviders"];
  const workspaceIsEmptyModelProviders = isPlainObject2(workspaceModelProviders) && Object.keys(workspaceModelProviders).length === 0;
  if (!workspaceIsEmptyModelProviders || !hasAnyProviderEntries(userModelProviders)) {
    return [];
  }
  return [
    `Warning: '${loadedSettings.workspace.path}' defines an empty 'modelProviders' object. This has no effect with current merge behavior, but may indicate a configuration error. If REPLACE semantics are introduced for 'modelProviders' in the future, this would override user-level model providers in '${loadedSettings.user.path}'.`
  ];
}
__name(getModelProvidersOverrideWarnings, "getModelProvidersOverrideWarnings");
function getSettingsWarnings(loadedSettings) {
  const warningSet = /* @__PURE__ */ new Set();
  for (const warning of loadedSettings.migrationWarnings) {
    warningSet.add(`Warning: ${warning}`);
  }
  for (const scope of ["User" /* User */, "Workspace" /* Workspace */]) {
    const settingsFile = loadedSettings.forScope(scope);
    if (settingsFile.rawJson === void 0) {
      continue;
    }
    const settingsObject = settingsFile.originalSettings;
    for (const warning of getSettingsFileKeyWarnings(
      settingsObject,
      settingsFile.path
    )) {
      warningSet.add(warning);
    }
  }
  for (const warning of getModelProvidersOverrideWarnings(loadedSettings)) {
    warningSet.add(warning);
  }
  return [...warningSet];
}
__name(getSettingsWarnings, "getSettingsWarnings");
function tagMcpServerScope(settings, scope) {
  const servers = settings.mcpServers;
  if (!servers || Object.keys(servers).length === 0) {
    return settings;
  }
  const tagged = {};
  for (const [name, config] of Object.entries(servers)) {
    tagged[name] = { ...config, scope };
  }
  return { ...settings, mcpServers: tagged };
}
__name(tagMcpServerScope, "tagMcpServerScope");
function mergeSettings(system, systemDefaults, user, workspace, isTrusted) {
  const safeWorkspace = isTrusted ? tagMcpServerScope(workspace, "workspace") : {};
  return customDeepMerge(
    getMergeStrategyForPath,
    {},
    // Start with an empty object
    systemDefaults,
    user,
    safeWorkspace,
    tagMcpServerScope(system, "system")
  );
}
__name(mergeSettings, "mergeSettings");
var LoadedSettings = class {
  static {
    __name(this, "LoadedSettings");
  }
  constructor(system, systemDefaults, user, workspace, isTrusted, migratedInMemorScopes, migrationWarnings = [], corruptedPath = void 0, wasRecovered = false, workspaceSettingsActive = true) {
    this.system = system;
    this.systemDefaults = systemDefaults;
    this.user = user;
    this.workspace = workspace;
    this.isTrusted = isTrusted;
    this.migratedInMemorScopes = migratedInMemorScopes;
    this.migrationWarnings = migrationWarnings;
    this.corruptedPath = corruptedPath;
    this.wasRecovered = wasRecovered;
    this.workspaceSettingsActive = workspaceSettingsActive;
    this._merged = this.computeMergedSettings();
  }
  system;
  systemDefaults;
  user;
  workspace;
  isTrusted;
  migratedInMemorScopes;
  migrationWarnings;
  corruptedPath;
  wasRecovered;
  workspaceSettingsActive;
  corruptionDialogDismissed = false;
  _merged;
  get merged() {
    return this._merged;
  }
  computeMergedSettings() {
    return mergeSettings(
      this.system.settings,
      this.systemDefaults.settings,
      this.user.settings,
      this.workspace.settings,
      this.isTrusted
    );
  }
  forScope(scope) {
    switch (scope) {
      case "User" /* User */:
        return this.user;
      case "Workspace" /* Workspace */:
        return this.workspace;
      case "System" /* System */:
        return this.system;
      case "SystemDefaults" /* SystemDefaults */:
        return this.systemDefaults;
      default:
        throw new Error(`Invalid scope: ${scope}`);
    }
  }
  setValue(scope, key, value) {
    if (key === "model.name" && typeof value === "string") {
      value = stripRuntimeSnapshotPrefix(value);
    }
    const settingsFile = this.forScope(scope);
    setNestedPropertySafe(settingsFile.settings, key, value);
    setNestedPropertySafe(settingsFile.originalSettings, key, value);
    this._merged = this.computeMergedSettings();
    const replacePath = key === "mcpServers" ? key.split(".") : [];
    saveSettings(settingsFile, createSettingsUpdate(key, value), replacePath);
  }
  setValues(writes, onScopeCommitted) {
    const scopes = /* @__PURE__ */ new Set();
    for (const write of writes) {
      const value = write.key === "model.name" && typeof write.value === "string" ? stripRuntimeSnapshotPrefix(write.value) : write.value;
      const settingsFile = this.forScope(write.scope);
      setNestedPropertySafe(settingsFile.settings, write.key, value);
      setNestedPropertySafe(settingsFile.originalSettings, write.key, value);
      scopes.add(write.scope);
    }
    this._merged = this.computeMergedSettings();
    const scopeList = Array.from(scopes);
    for (let i = 0; i < scopeList.length; i++) {
      const scope = scopeList[i];
      try {
        saveSettings(this.forScope(scope), void 0, void 0, {
          throwOnWriteFailure: true
        });
      } catch (err) {
        for (const uncommittedScope of scopeList.slice(i)) {
          this.reloadScopeFromDisk(uncommittedScope);
        }
        throw err;
      }
      onScopeCommitted?.(scope);
    }
  }
  recomputeMerged() {
    this._merged = this.computeMergedSettings();
  }
  reloadScopeFromDisk(scope) {
    const file = this.forScope(scope);
    try {
      if (!fs3.existsSync(file.path)) {
        file.settings = {};
        file.originalSettings = {};
        file.rawJson = void 0;
        this._merged = this.computeMergedSettings();
        return;
      }
      const content = fs3.readFileSync(file.path, "utf-8");
      const parsed = JSON.parse((0, import_strip_json_comments.default)(content));
      if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
        const resolved = resolveEnvVarsInObject(
          parsed,
          getHomeEnvFallbackVars((message) => debugLogger2.warn(message))
        );
        file.settings = resolved;
        file.originalSettings = structuredClone(parsed);
        file.rawJson = content;
      }
    } catch (err) {
      debugLogger2.warn(
        `reloadScopeFromDisk(${scope}): ${getErrorMessage(err)}`
      );
    }
    this._merged = this.computeMergedSettings();
  }
  /**
   * Get user-level hooks from user settings (not merged with workspace).
   * These hooks should always be loaded regardless of folder trust.
   */
  getUserHooks() {
    return this.user.settings.hooks;
  }
  /**
   * Get project-level hooks from workspace settings (not merged).
   * Returns undefined if workspace is not trusted (hooks filtered out).
   */
  getProjectHooks() {
    if (!this.isTrusted) {
      return void 0;
    }
    return this.workspace.settings.hooks;
  }
};
function createMinimalSettings() {
  const emptySettingsFile = {
    path: "",
    settings: {},
    originalSettings: {},
    rawJson: "{}"
  };
  return new LoadedSettings(
    emptySettingsFile,
    emptySettingsFile,
    emptySettingsFile,
    emptySettingsFile,
    false,
    /* @__PURE__ */ new Set(),
    [],
    void 0,
    false
  );
}
__name(createMinimalSettings, "createMinimalSettings");
function detectQwenHomeRedirectWithoutMigration(activeUserSettingsPath) {
  if (!process.env["QWEN_HOME"]) {
    return null;
  }
  const activeQwenDir = Storage.getGlobalQwenDir();
  const savedQwenHome = process.env["QWEN_HOME"];
  delete process.env["QWEN_HOME"];
  let legacyQwenDir;
  try {
    legacyQwenDir = Storage.getGlobalQwenDir();
  } finally {
    process.env["QWEN_HOME"] = savedQwenHome;
  }
  if (path2.resolve(activeQwenDir) === path2.resolve(legacyQwenDir)) {
    return null;
  }
  if (fs3.existsSync(activeUserSettingsPath)) {
    return null;
  }
  const legacyUserSettings = path2.join(legacyQwenDir, "settings.json");
  if (!fs3.existsSync(legacyUserSettings)) {
    return null;
  }
  return `QWEN_HOME points to "${activeQwenDir}" but no settings.json was found there. Existing config remains at "${legacyQwenDir}" \u2014 OAuth tokens, settings, memory, extensions, and skills are not auto-migrated. Copy them manually if you want them to apply at the new location.`;
}
__name(detectQwenHomeRedirectWithoutMigration, "detectQwenHomeRedirectWithoutMigration");
var CORRUPTED_SUFFIX = ".corrupted";
function loadSettings(workspaceDir = process.cwd(), consumeCorruptionEnvVars = true) {
  const opts = typeof consumeCorruptionEnvVars === "object" ? consumeCorruptionEnvVars : { consumeCorruptionEnvVars };
  preResolveHomeEnvOverrides();
  const userSettingsPath = getUserSettingsPath();
  const qwenHomeRedirectWarning = detectQwenHomeRedirectWithoutMigration(userSettingsPath);
  let systemSettings = {};
  let systemDefaultSettings = {};
  let userSettings = {};
  let workspaceSettings = {};
  const settingsErrors = [];
  const systemSettingsPath = getSystemSettingsPath();
  const systemDefaultsPath = getSystemDefaultsPath();
  const migratedInMemorScopes = /* @__PURE__ */ new Set();
  const resolvedWorkspaceDir = path2.resolve(workspaceDir);
  const resolvedHomeDir = path2.resolve(homedir());
  let realWorkspaceDir = resolvedWorkspaceDir;
  try {
    realWorkspaceDir = fs3.realpathSync(resolvedWorkspaceDir);
  } catch (_e) {
  }
  const realHomeDir = fs3.realpathSync(resolvedHomeDir);
  const workspaceSettingsPath = new Storage(
    workspaceDir
  ).getWorkspaceSettingsPath();
  const loadAndMigrate = /* @__PURE__ */ __name((filePath, scope) => {
    try {
      if (fs3.existsSync(filePath)) {
        const content = fs3.readFileSync(filePath, "utf-8");
        let rawSettings;
        const corruptedPath = `${filePath}${CORRUPTED_SUFFIX}`;
        let corruptedSaved = false;
        let recoveredFromEnvVar = null;
        try {
          rawSettings = JSON.parse((0, import_strip_json_comments.default)(content));
        } catch (parseError) {
          debugLogger2.warn(
            `Settings file ${filePath} has invalid JSON (${getErrorMessage(parseError)}). Resetting to empty settings.`
          );
          try {
            fs3.copyFileSync(filePath, corruptedPath);
            corruptedSaved = true;
          } catch (copyError) {
            debugLogger2.warn(
              `Failed to copy corrupted file: ${getErrorMessage(copyError)}`
            );
          }
          if (!rawSettings) {
            const warningMsg = `Settings file ${filePath} has invalid JSON. Your settings have been reset.`;
            debugLogger2.warn(warningMsg);
            if (corruptedSaved) {
              try {
                fs3.writeFileSync(filePath, "{}", "utf-8");
              } catch {
              }
            }
            return {
              settings: {},
              migrationWarnings: [],
              corruptedPath: corruptedSaved ? corruptedPath : void 0,
              wasRecovered: false
            };
          }
        }
        const envCorruptedPath = process.env[ENV_CORRUPTED_PATH];
        if ((opts.consumeCorruptionEnvVars ?? true) && envCorruptedPath && envCorruptedPath === corruptedPath && scope === "User" /* User */) {
          corruptedSaved = true;
          recoveredFromEnvVar = process.env[ENV_WAS_RECOVERED] === "1";
          delete process.env[ENV_CORRUPTED_PATH];
          delete process.env[ENV_WAS_RECOVERED];
        }
        if (typeof rawSettings !== "object" || rawSettings === null || Array.isArray(rawSettings)) {
          settingsErrors.push({
            message: "Settings file is not a valid JSON object.",
            path: filePath
          });
          return { settings: {} };
        }
        let settingsObject = rawSettings;
        const hasVersionKey = SETTINGS_VERSION_KEY in settingsObject;
        const versionValue = settingsObject[SETTINGS_VERSION_KEY];
        const hasInvalidVersion = hasVersionKey && typeof versionValue !== "number";
        const hasLegacyNumericVersion = typeof versionValue === "number" && versionValue < SETTINGS_VERSION;
        let migrationWarnings;
        const persistSettingsObject = /* @__PURE__ */ __name((warningPrefix) => {
          try {
            const written = updateSettingsFilePreservingFormat(
              filePath,
              settingsObject,
              true
            );
            if (!written) {
              debugLogger2.error(
                `${warningPrefix}: updateSettingsFilePreservingFormat returned false for ${filePath}`
              );
            }
          } catch (e) {
            debugLogger2.error(`${warningPrefix}: ${getErrorMessage(e)}`);
          }
        }, "persistSettingsObject");
        if (needsMigration(settingsObject)) {
          const migrationResult = runMigrations(settingsObject, scope);
          if (migrationResult.executedMigrations.length > 0) {
            settingsObject = migrationResult.settings;
            migrationWarnings = migrationResult.warnings;
            persistSettingsObject("Error migrating settings file on disk");
          } else if ((hasLegacyNumericVersion || hasInvalidVersion) && !corruptedSaved) {
            settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
            debugLogger2.warn(
              `Settings version metadata in ${filePath} could not be migrated by any registered migration. Normalizing ${SETTINGS_VERSION_KEY} to ${SETTINGS_VERSION}.`
            );
            persistSettingsObject("Error normalizing settings version on disk");
          }
        } else if ((!hasVersionKey || hasInvalidVersion || hasLegacyNumericVersion) && !corruptedSaved) {
          settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
          persistSettingsObject("Error normalizing settings version on disk");
        }
        const result = {
          settings: settingsObject,
          rawJson: content,
          migrationWarnings: migrationWarnings ?? []
        };
        if (corruptedSaved) {
          result.corruptedPath = corruptedPath;
          result.wasRecovered = recoveredFromEnvVar ?? false;
        }
        return result;
      }
    } catch (error) {
      settingsErrors.push({
        message: getErrorMessage(error),
        path: filePath
      });
    }
    return { settings: {} };
  }, "loadAndMigrate");
  const systemResult = loadAndMigrate(systemSettingsPath, "System" /* System */);
  const systemDefaultsResult = loadAndMigrate(
    systemDefaultsPath,
    "SystemDefaults" /* SystemDefaults */
  );
  const userResult = loadAndMigrate(userSettingsPath, "User" /* User */);
  let workspaceResult = {
    settings: {},
    rawJson: void 0
  };
  const workspaceSettingsActive = realWorkspaceDir !== realHomeDir;
  if (workspaceSettingsActive) {
    workspaceResult = loadAndMigrate(
      workspaceSettingsPath,
      "Workspace" /* Workspace */
    );
  }
  const systemOriginalSettings = structuredClone(systemResult.settings);
  const systemDefaultsOriginalSettings = structuredClone(
    systemDefaultsResult.settings
  );
  const userOriginalSettings = structuredClone(userResult.settings);
  const workspaceOriginalSettings = structuredClone(workspaceResult.settings);
  const homeEnvFallback = getHomeEnvFallbackVars(
    (message) => debugLogger2.warn(message)
  );
  systemSettings = resolveEnvVarsInObject(
    systemResult.settings,
    homeEnvFallback
  );
  systemDefaultSettings = resolveEnvVarsInObject(
    systemDefaultsResult.settings,
    homeEnvFallback
  );
  userSettings = resolveEnvVarsInObject(userResult.settings, homeEnvFallback);
  workspaceSettings = resolveEnvVarsInObject(
    workspaceResult.settings,
    homeEnvFallback
  );
  if (userSettings.ui?.theme === "VS") {
    userSettings.ui.theme = DEFAULT_LIGHT_THEME_NAME;
  } else if (userSettings.ui?.theme === "VS2015") {
    userSettings.ui.theme = DEFAULT_DARK_THEME_NAME;
  }
  if (workspaceSettings.ui?.theme === "VS") {
    workspaceSettings.ui.theme = DEFAULT_LIGHT_THEME_NAME;
  } else if (workspaceSettings.ui?.theme === "VS2015") {
    workspaceSettings.ui.theme = DEFAULT_DARK_THEME_NAME;
  }
  const initialTrustCheckSettings = customDeepMerge(
    getMergeStrategyForPath,
    {},
    systemSettings,
    userSettings
  );
  const isTrusted = isWorkspaceTrusted(
    initialTrustCheckSettings,
    void 0,
    realWorkspaceDir
  ).isTrusted ?? true;
  const tempMergedSettings = mergeSettings(
    systemSettings,
    systemDefaultSettings,
    userSettings,
    workspaceSettings,
    isTrusted
  );
  if (!opts.skipLoadEnvironment) {
    loadEnvironment(tempMergedSettings, workspaceDir);
  }
  if (settingsErrors.length > 0) {
    const errorMessages = settingsErrors.map(
      (error) => `Error in ${error.path}: ${error.message}`
    );
    throw new FatalConfigError(
      `${errorMessages.join("\n")}
Please fix the configuration file(s) and try again.`
    );
  }
  const allMigrationWarnings = [
    ...qwenHomeRedirectWarning ? [qwenHomeRedirectWarning] : [],
    ...systemResult.migrationWarnings ?? [],
    ...systemDefaultsResult.migrationWarnings ?? [],
    ...userResult.migrationWarnings ?? [],
    ...workspaceResult.migrationWarnings ?? []
  ];
  return new LoadedSettings(
    {
      path: systemSettingsPath,
      settings: systemSettings,
      originalSettings: systemOriginalSettings,
      rawJson: systemResult.rawJson
    },
    {
      path: systemDefaultsPath,
      settings: systemDefaultSettings,
      originalSettings: systemDefaultsOriginalSettings,
      rawJson: systemDefaultsResult.rawJson
    },
    {
      path: userSettingsPath,
      settings: userSettings,
      originalSettings: userOriginalSettings,
      rawJson: userResult.rawJson
    },
    {
      path: workspaceSettingsPath,
      settings: workspaceSettings,
      originalSettings: workspaceOriginalSettings,
      rawJson: workspaceResult.rawJson
    },
    isTrusted,
    migratedInMemorScopes,
    allMigrationWarnings,
    userResult.corruptedPath,
    userResult.wasRecovered ?? false,
    workspaceSettingsActive
  );
}
__name(loadSettings, "loadSettings");
function createSettingsUpdate(key, value) {
  const root = {};
  setNestedPropertySafe(root, key, value);
  return root;
}
__name(createSettingsUpdate, "createSettingsUpdate");
function saveSettings(settingsFile, updates = settingsFile.originalSettings, replacePath = [], opts = {}) {
  try {
    const dirPath = path2.dirname(settingsFile.path);
    if (!fs3.existsSync(dirPath)) {
      fs3.mkdirSync(dirPath, { recursive: true });
    }
    const written = updateSettingsFilePreservingFormat(
      settingsFile.path,
      updates,
      false,
      replacePath
    );
    if (!written) {
      const message = `saveSettings: updateSettingsFilePreservingFormat returned false for ${settingsFile.path}`;
      if (opts.throwOnWriteFailure) {
        throw new Error(message);
      }
      debugLogger2.error(message);
    }
  } catch (error) {
    debugLogger2.error("Error saving user settings file.");
    debugLogger2.error(error instanceof Error ? error.message : String(error));
    throw error;
  }
}
__name(saveSettings, "saveSettings");

export {
  getModelProvidersOwnerScope,
  getPersistScopeForModelSelection,
  getWritableScopes,
  getOwnKeyScope,
  TOGGLE_TYPES,
  OUTPUT_LANGUAGE_AUTO,
  isAutoLanguage,
  resolveOutputLanguage,
  getOutputLanguageFilePath,
  updateOutputLanguageFile,
  writeOutputLanguageAndRegisterPath,
  initializeLlmOutputLanguage,
  getFlattenedSchema,
  getSettingDefinition,
  requiresRestart,
  getDefaultValue,
  getNestedValue,
  getNestedProperty,
  getEffectiveValue,
  getAllSettingKeys,
  validateSettingValue,
  getDialogSettingKeys,
  settingExistsInScope,
  setPendingSettingValue,
  setPendingSettingValueAny,
  getRestartRequiredFromModified,
  saveModifiedSettings,
  getDisplayValue,
  isDefaultValue,
  backupSettingsFile,
  restoreSettingsFromBackup,
  cleanupSettingsBackup,
  getUserSettingsPath,
  getUserSettingsDir,
  SETTINGS_VERSION,
  SETTINGS_VERSION_KEY,
  migrateLegacyPermissions,
  SettingScope,
  getSettingsWarnings,
  LoadedSettings,
  createMinimalSettings,
  CORRUPTED_SUFFIX,
  loadSettings,
  saveSettings
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen team
 * SPDX-License-Identifier: Apache-2.0
 */
