* refactor(core): rewrite compression prompt to 9-section claude-code-style format
Replaces the <state_snapshot> XML template with a numbered 9-section
structure that mandates verbatim preservation of user messages, including
the historical chronological list (section 6). The new format is
designed to pair with post-compact file/image restoration (separate work)
so the agent can resume long single-turn tasks without losing intent.
* refactor(core): align compaction trigger string with new 9-section prompt
The user-turn trigger injected after the system prompt still said
'generate the <state_snapshot>' from the old XML prompt era. Updated to
'produce the 9-section summary' to match Task 1's new prompt format.
Also tightens the prompt test to assert the specific user-message
verbatim mandate (not just the word 'verbatim' anywhere) so a future
regression that drops the mandate won't silently pass.
* feat(core): add postCompactAttachments module with file path extractor
extractRecentFilePaths walks history newest-first and returns the top N
unique file paths touched by read_file/write_file/edit/replace tool calls.
Pure function, no side effects, no state cache — readiness for the next
compaction-rewrite tasks.
* refactor(core): simplify extractRecentFilePaths internals
Three small cleanups from code review:
- Map<string, number> -> Set<string> (the index value was never read)
- Guard against maxFiles <= 0 explicitly (avoids returning 1 result
when caller passes 0 as a 'disable' sentinel)
- Document 'replace' as a legacy alias for 'edit' so a future cleanup
pass does not delete it as apparent dead code
Adds one test covering the maxFiles=0 path.
* feat(core): add image extractor with source-tool metadata
extractRecentImages walks history newest-first, collects up to N image
inlineData parts, and attributes each one to the model+functionCall that
preceded it (when one exists). Returns chronological order so callers
can render a meaningful 'last visual state ends here' strip.
* feat(core): add size-adaptive file reader for post-compact restore
readFileSizeAdaptive reads a file and returns one of: embed (full content
for files ≤ maxTokens × 4 chars), reference (path-only for large files),
missing (deleted since last touch), or binary (non-text content). The
embed/reference distinction mirrors claude-code's compact_file_reference
vs file attachment behavior, but without introducing new message types.
* refactor(core): harden readFileSizeAdaptive size accounting
Three corrections from code review:
- Import CHARS_PER_TOKEN from tokenEstimation.ts (canonical) instead of
redeclaring locally, preventing silent drift between modules.
- Compare decoded character length, not raw byte length, against the
cap. Otherwise a 10k-char Chinese file would be ~30k bytes and would
be mis-classified as 'reference' despite fitting the budget.
- Rename FileReadResult -> FileEmbedResult to avoid a name collision
with the unrelated FileReadResult interface in fileUtils.ts.
Adds a CJK-text test that catches the byte/char regression.
* feat(core): add file restoration block composer
buildFileRestorationBlocks reads each candidate file, classifies it as
embed/reference/missing/binary, and emits one consolidated reference
block (path-only list) plus one user message per embedded small file.
Total embed size is capped at POST_COMPACT_TOKEN_BUDGET; over-budget
files downgrade to reference.
* test(core): make budget test actually exercise the downgrade path
The previous version of this test wrote 3 files totalling 9k chars
against a 200k char budget. The assertions trivially passed regardless
of whether the budget check existed in the implementation.
The new version writes 11 files of 20k chars (each at the per-file cap)
so the budget is exhausted by the 10th and the 11th must downgrade
from embed to reference. Asserts both: file 11 appears in the reference
block, and file 11's content does NOT appear in any embed block.
* feat(core): add image restoration block composer
buildImageRestorationBlock emits a single user message whose first part
is a metadata header (turn index + source tool name + args per image),
followed by the inlineData parts themselves. Handles user-paste images
(no source tool) by labeling them as 'user-provided'.
* feat(core): add composePostCompactHistory orchestrator
Assembles the full post-compact history in order:
summary → model ack → file references → file embeds → image block.
Each section is built by the per-concern extractors and builders added
in previous tasks. This is the single integration point that
chatCompressionService.compress() will call once the wire-up task lands.
* feat(core)!: rewrite compress() to claude-code-style full-history model
Replaces the split-point + tail-preservation model with full-history
compression + composePostCompactHistory. The entire curated history is
sent to the summary side-query, and the post-compact history is
assembled by the new composer (summary + ack + file restores + image
restore).
BREAKING: the previously-exported findCompressSplitPoint,
splitPointRetainingTrailingPairs, COMPRESSION_PRESERVE_THRESHOLD, and
TOOL_ROUND_RETAIN_COUNT will be removed in the next commit. Tests that
exercise them remain failing temporarily.
* chore(core): remove obsolete split-point compression infrastructure
Deletes findCompressSplitPoint, splitPointRetainingTrailingPairs,
COMPRESSION_PRESERVE_THRESHOLD, MIN_COMPRESSION_FRACTION, and
TOOL_ROUND_RETAIN_COUNT, plus the tests that exercised them. The new
behavior is covered by composePostCompactHistory and its unit tests.
Also cleans up:
- Stale orphan-strip comment in compress() that described the deleted
manual-trigger orphan-funcCall handling.
- TEST_ONLY.COMPRESSION_PRESERVE_THRESHOLD hatch in client.ts.
- Docstring references in config.ts and compactionInputSlimming.ts.
* test(core): add single-turn computer-use compaction regression
Reproduces the scenario the rewrite targets: one user prompt kicks off
many screenshot tool calls. Asserts that (a) the user prompt is carried
into the summary verbatim and (b) the 3 most recent screenshots are
restored as an image block with source-tool metadata. This is the canary
test for the computer-use UX claim made in the design discussion.
* docs(core): remove stale "split point" references in tokenEstimation comments
Aligns the docstrings with the new compose-based compression flow. The
"split point" and "splitter" concepts no longer exist after the rewrite.
* fix(core): iterate parts reverse so parallel tool calls keep the last N
Real-session E2E surfaced a bug: a model that issues N parallel ReadFile
calls puts all N functionCall parts in ONE model+fc content. The
extractor's outer history walk is newest-first, but the inner parts
walk was forward — so for a 6-parallel batch hitting the cap of 5,
the FIRST 5 parts won and the actually-most-recent (last-listed) file
was dropped.
Fix: walk parts in reverse within each content. Applied symmetrically
to extractRecentImages (same shape, even rarer trigger).
Adds a regression test that hits a 6-parallel batch.
* fix(core): code-review fixes — fence escape, path sanitize, alias removal
- CommonMark-safe fence in file embed blocks. The old 3-backtick fence
closed prematurely when a file's content contained a triple-backtick
run (Markdown, CLAUDE.md, JSDoc with code examples) — leaking the
remainder as unfenced text. Now uses a fence one longer than the
longest backtick run in the content.
- Strip control characters (\r, \n, \t) from file paths before
rendering into attachment markdown. Paths come from model-controlled
history; a \n could inject markdown structure. The actual path stays
intact for tool calls — only the displayed string is sanitized.
- Remove the historyForCompression alias for curatedHistory in
compress(). The alias was added as a comment anchor during the
rewrite but didn't carry semantic information.
* refactor(core): rewrite compression prompt to <state_snapshot> XML with 9 claude-aligned sections
Replaces the 9-section numbered-text prompt with qwen-code's original
<state_snapshot> XML envelope, but with the 9 inner section tags
content-aligned to claude-code:
<primary_request_and_intent>
<key_technical_concepts>
<files_and_code_sections>
<errors_and_fixes>
<problem_solving>
<all_user_messages>
<pending_tasks>
<current_work>
<next_step>
Also:
- <scratchpad> -> <analysis>, stripped by postProcessSummary (saves
~600-800 tokens of CoT noise per compaction).
- "Resume directly..." trailer moved out of the prompt body and into
postProcessSummary (no longer re-generated by the model every
compaction; lives once in code with our own wording).
- Section 6 verbatim-policed mandate relaxed to "chronological, include
short messages like 'ok' / 'continue'" — matches claude-code intent
without forcing the model to literally copy long user messages.
E2E (qwen3.6-plus, 6 substantial .ts files + thorough analysis):
raw history 6508 -> summary 1513 (after strip ~947), 38% history
compression. Overall context 24642 -> 20647 reported (-16%), with
another ~664 tokens actually saved by the post-strip but not
reflected in the conservative token-math heuristic.
* docs(core): code-review polish on XML prompt rewrite
Four small follow-ups from review of 641a0eadd:
- prompts.ts: rewrite getCompressionPrompt's stale JSDoc — it still
described the deleted 9-section numbered-text format and the
verbatim mandate that was relaxed.
- chatCompressionService.ts: clarify the token-math comment so it's
obvious the ~1000 token deduction covers the full compression
system prompt + kick-off user turn (not any single instruction)
and that newTokenCount slightly over-counts because <analysis>
gets stripped by postProcessSummary downstream.
- postCompactAttachments.ts: add a NOTE comment on the <analysis>
strip regex covering its strict-tag-match assumption and
multi-block / non-greedy semantics.
- postCompactAttachments.test.ts: replace the four lazy
`await import('./postCompactAttachments.js')` calls inside the
postProcessSummary describe block with one top-level static import
— consistent with how every other describe in the file imports.
* docs(core): drop stale duplicate sentence left in token-math comment
* fix(core): address wenshao review on PR #4599 (correctness + security + ergonomics)
Seven follow-ups from wenshao's review of the compaction rewrite.
Critical:
- newTokenCount now includes restoration-block tokens via
estimateContentChars over extraHistory[2..]. Previously the formula
only counted side-query output, so up to 5 × 5K (files) + 3 × image
tokens were missing — letting the inflation guard miss and the
cheap-gate under-estimate the next prompt size (Finding 1).
- composePostCompactHistory now merges every file restoration block
and the image block into a single user Content following the model
ack. The previous output had consecutive user roles, which
geminiChat.test.ts:6289 enforces against and Gemini providers
reject with 400 "consecutive same-role content" (Finding 2).
- Preserve a trailing model+functionCall through compaction so a
pending functionResponse (sitting in sendMessageStream's
pendingUserMessage) has a matching call. Without this, hard-rescue
auto-compaction mid tool-use loop produces a user+functionResponse
with no preceding model+functionCall → API 400. This restores the
protection the split-point in-flight fallback used to provide.
When the funcCall lands without attachments it folds into the
ack's own model Content to avoid model→model adjacency (Finding 3).
- composePostCompactHistory now takes an optional workspaceRoot and
silently skips file paths that resolve outside it.
extractRecentFilePaths picks up paths from model functionCall args
regardless of whether the tool execution succeeded; without a
boundary check, an adversarial model that issued
read_file('/etc/passwd') — denied by the permission system —
would still have its path extracted and re-read into the next
prompt. compress() passes config.getTargetDir() as the boundary
(Finding 4).
Suggestions:
- composePostCompactHistory + buildFileRestorationBlocks +
readFileSizeAdaptive all take optional AbortSignal and short-
circuit / pass it to readFile's { signal } option. Cancelled
compactions stop on the next file read (Finding 5).
- postProcessSummary fallback no longer re-injects the raw
<analysis> block when the strip leaves nothing. The new
stripAnalysisBlock helper runs the closed-tag strip AND an
unclosed-tag strip (handles 'model ran out of output tokens
before closing'). If both leave nothing, postProcessSummary
emits '[Summary unavailable]' rather than leaking scratchpad
(Finding 6).
- firePostCompactEvent now receives stripAnalysisBlock(summary) so
hook consumers see the same text that lands in history. The
resume trailer stays out of the hook payload — that's wrapper
decoration for the next agent turn, not state for consumers
(Finding 8a).
Docs:
- Update the geminiChat.ts comment around `trigger: 'auto'` to
describe what the trigger actually does post-refactor (hook event
categorization) rather than the deleted manual-only orphan-strip
it used to guard against (Finding 8b).
Regression tests cover all six fixable code-path changes
(role alternation, trailing funcCall preservation, workspace
boundary, abort propagation, closed-tag fallback strip, unclosed-tag
fallback strip).
* fix(core): add getTargetDir to geminiChat auto-compression test mock
The R3.4 end-to-end auto-compression test drives the real
ChatCompressionService, which reads config.getTargetDir() for the
post-compact file-restoration workspace boundary. The geminiChat mock
config lacked getTargetDir, so the test threw "config.getTargetDir is
not a function" on CI. Add the mock to unblock the failing Test jobs.
* feat(core): configurable compaction retention + computer-use screenshot trigger
Add four env-overridable chatCompression settings (priority env >
settings > default):
- maxRecentFilesToRetain (QWEN_COMPACT_MAX_RECENT_FILES, default 5)
- maxRecentImagesToRetain (QWEN_COMPACT_MAX_RECENT_IMAGES, default 3)
- enableScreenshotTrigger (QWEN_COMPACT_SCREENSHOT_TRIGGER, default true)
- screenshotTriggerThreshold(QWEN_COMPACT_SCREENSHOT_THRESHOLD, default 50)
The screenshot trigger fires auto-compaction once tool-returned images
accumulate to the threshold even when token usage is below the auto tier,
so computer-use sessions don't drown the model in stale screenshots. It
counts only images nested in functionResponse.parts (tool results), not
user pastes, and runs only in the would-be-NOOP path when enabled.
Fix a latent bug surfaced while wiring the trigger: extractRecentImages
only inspected top-level inlineData parts, but convertToFunctionResponse
nests tool media under functionResponse.parts — so post-compact
restoration recovered ZERO tool screenshots in real sessions, while unit
tests stayed green against a fabricated top-level shape. It now walks both
shapes; the image counter and tests use the real nested shape.
Remove the now-defunct contextPercentageThreshold deprecation warning (the
field was already dropped from ChatCompressionSettings) and its tests, and
document the four new settings.
* test(core): assert screenshot trigger can't re-fire post-compaction; fix misleading docs
Code-review follow-up. The screenshot trigger counts only images nested in
functionResponse.parts. Compaction replaces those with the summary and
re-embeds survivors as TOP-LEVEL parts in the restoration block, which the
counter ignores — so the tool-image count always resets to ~0 and the
trigger cannot immediately re-fire, independent of maxRecentImages.
The resolveCompactionTuning JSDoc and the settings.md note previously warned
of a non-existent "maxRecentImages near threshold => compact every turn"
loop. Correct both, and add a regression test asserting
countToolResponseImages() is 0 on composePostCompactHistory output.
* fix(core): guard readFileSizeAdaptive against multi-GB reads; cover composer 4-entry branch
wenshao review round 2 on PR #4599.
- readFileSizeAdaptive now stats the file first and short-circuits to a
reference when its byte size exceeds maxChars*4 (the safe UTF-8 upper
bound — a file larger than that cannot fit within maxChars chars). This
stops a multi-GB file the agent previously touched from being slurped
into a Buffer and exhausting the heap mid-compaction, exactly when we're
trying to reduce memory. A large binary file now references rather than
reading to binary-detect.
- Add a test for composePostCompactHistory's 4-entry branch (attachments +
trailing model+functionCall) producing [user(summary), model(ack),
user(attachments), model(fc)]. This is the common mid-tool-loop
compaction case; a model->model adjacency here is a provider 400. Prior
tests only covered the 2-entry fold (no attachments) and 3-entry (no
trailing fc) shapes.
* fix(core): resolve symlinks in workspace boundary; guard compose against throws
wenshao review round 3 on PR #4599 (two Criticals).
- isInsideWorkspace now resolves symlinks via realpathSync (safeRealpath,
with a lexical fallback for non-existent paths). A symlink living inside
the workspace but pointing outside (e.g. workspace/.env -> ~/.ssh/id_rsa)
previously passed the lexical boundary check and had its target read and
embedded into the post-compact history sent to the provider. Added a
RED-verified security regression test (secret embedded under the old
lexical check; rejected under realpath).
- Wrap composePostCompactHistory in try/catch inside compress(). The
summary side-query has already succeeded at that point, so a
restoration-assembly throw (disk I/O / malformed history) previously
escaped to sendMessageStream, crashing the active turn AND bypassing the
COMPRESSION_FAILED breaker. It now degrades to summary + ack.
* fix(core): close 4 compaction Criticals from review round 4
wenshao review round 4 on PR #4599.
- isSummaryEmpty now checks the STRIPPED summary: a response that is only an
<analysis> block (no <state_snapshot>) strips to empty, so it takes the
COMPRESSION_FAILED_EMPTY_SUMMARY path instead of "succeeding" with
`[Summary unavailable]` as the agent's only context (silent amnesia).
- Manual /compress strips a trailing ORPHANED model+functionCall before
composing — it has no pending functionResponse, so preserving it would
emit model[fc] then the next user text turn -> API 400. Auto-compaction
still keeps it (the pending response pairs with it).
- The restoration-failure catch fallback now folds a trailing
model+functionCall into the ack turn, so a pending functionResponse
(auto mid-tool-loop) keeps its matching call even on the degraded path.
- extractRecentFilePaths skips file paths whose tool call FAILED (an error
functionResponse), so a denied read_file is never re-read off disk during
compaction — closing a permission-bypass side channel.
RED-verified regression tests for the empty-summary, orphan-strip, and
permission-bypass fixes. Corrected the postProcessSummary comment.
* test(core): cover composePostCompactHistory catch-fallback; document fold text drop
wenshao review round 5 on PR #4599.
- Regression test for the restoration-failure catch fallback: mock
composePostCompactHistory to reject and assert compaction still returns
COMPRESSED (no escape to sendMessageStream / breaker bypass) with the
trailing functionCall folded into the ack and the trailing text dropped.
- Document that the fold branch intentionally keeps only functionCall parts
(the trailing turn's text is already captured in the summary); the
asymmetry with the with-attachments branch is deliberate.
153 KiB
Qwen Code Configuration
Tip
Authentication / API keys: Authentication (API Key, Alibaba Cloud Coding Plan) and auth-related environment variables (like
OPENAI_API_KEY) are documented in Authentication.
Note
Note on New Configuration Format: The format of the
settings.jsonfile has been updated to a new, more organized structure. The old format will be migrated automatically. Qwen Code offers several ways to configure its behavior, including environment variables, command-line arguments, and settings files. This document outlines the different configuration methods and available settings.
Configuration layers
Configuration is applied in the following order of precedence (lower numbers are overridden by higher numbers):
| Level | Configuration Source | Description |
|---|---|---|
| 1 | Default values | Hardcoded defaults within the application |
| 2 | System defaults file | System-wide default settings that can be overridden by other settings files |
| 3 | User settings file | Global settings for the current user |
| 4 | Project settings file | Project-specific settings |
| 5 | System settings file | System-wide settings that override all other settings files |
| 6 | Environment variables | System-wide or session-specific variables, potentially loaded from .env files |
| 7 | Command-line arguments | Values passed when launching the CLI |
Settings files
Qwen Code uses JSON settings files for persistent configuration. There are four locations for these files:
| File Type | Location | Scope |
|---|---|---|
| System defaults file | Linux: /etc/qwen-code/system-defaults.jsonWindows: C:\ProgramData\qwen-code\system-defaults.jsonmacOS: /Library/Application Support/QwenCode/system-defaults.json The path can be overridden using the QWEN_CODE_SYSTEM_DEFAULTS_PATH environment variable. |
Provides a base layer of system-wide default settings. These settings have the lowest precedence and are intended to be overridden by user, project, or system override settings. |
| User settings file | ~/.qwen/settings.json (where ~ is your home directory). |
Applies to all Qwen Code sessions for the current user. |
| Project settings file | .qwen/settings.json within your project's root directory. |
Applies only when running Qwen Code from that specific project. Project settings override user settings. |
| System settings file | Linux: /etc/qwen-code/settings.json Windows: C:\ProgramData\qwen-code\settings.json macOS: /Library/Application Support/QwenCode/settings.jsonThe path can be overridden using the QWEN_CODE_SYSTEM_SETTINGS_PATH environment variable. |
Applies to all Qwen Code sessions on the system, for all users. System settings override user and project settings. May be useful for system administrators at enterprises to have controls over users' Qwen Code setups. |
Note
Note on environment variables in settings: String values within your
settings.jsonfiles can reference environment variables using either$VAR_NAMEor${VAR_NAME}syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variableMY_API_TOKEN, you could use it insettings.jsonlike this:"apiKey": "$MY_API_TOKEN".
The .qwen directory in your project
In addition to a project settings file, a project's .qwen directory can contain other project-specific files related to Qwen Code's operation, such as:
- Custom sandbox profiles (e.g.
.qwen/sandbox-macos-custom.sb,.qwen/sandbox.Dockerfile). - Agent Skills under
.qwen/skills/(each Skill is a directory containing aSKILL.md).
Configuration migration
Qwen Code automatically migrates legacy configuration settings to the new format. Old settings files are backed up before migration. The following settings have been renamed from negative (disable*) to positive (enable*) naming:
| Old Setting | New Setting | Notes |
|---|---|---|
disableAutoUpdate + disableUpdateNag |
general.enableAutoUpdate |
Consolidated into a single setting |
disableLoadingPhrases |
ui.accessibility.enableLoadingPhrases |
|
disableFuzzySearch |
context.fileFiltering.enableFuzzySearch |
|
disableCacheControl |
model.generationConfig.enableCacheControl |
Note
Boolean value inversion: When migrating, boolean values are inverted (e.g.,
disableAutoUpdate: truebecomesenableAutoUpdate: false).
Consolidation policy for disableAutoUpdate and disableUpdateNag
When both legacy settings are present with different values, the migration follows this policy: if either disableAutoUpdate or disableUpdateNag is true, then enableAutoUpdate becomes false:
disableAutoUpdate |
disableUpdateNag |
Migrated enableAutoUpdate |
|---|---|---|
false |
false |
true |
false |
true |
false |
true |
false |
false |
true |
true |
false |
Available settings in settings.json
Settings are organized into categories. Most settings should be placed within their corresponding top-level category object in your settings.json file. A few top-level settings like proxy and plansDirectory remain direct root keys for compatibility.
general
| Setting | Type | Description | Default |
|---|---|---|---|
general.preferredEditor |
string | The preferred editor to open files in. | undefined |
general.vimMode |
boolean | Enable Vim keybindings. | false |
general.enableAutoUpdate |
boolean | Enable automatic update checks and installations on startup. | true |
general.showSessionRecap |
boolean | 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. |
false |
general.sessionRecapAwayThresholdMinutes |
number | Minutes the terminal must be blurred before an auto-recap fires on focus-in. Only used when showSessionRecap is enabled. |
5 |
general.gitCoAuthor.commit |
boolean | 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. |
true |
general.gitCoAuthor.pr |
boolean | Append a Qwen Code attribution line to pull request descriptions when running gh pr create. |
true |
general.checkpointing.enabled |
boolean | Enable session checkpointing for recovery. | false |
general.defaultFileEncoding |
string | 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. |
"utf-8" |
output
| Setting | Type | Description | Default | Possible Values |
|---|---|---|---|---|
output.format |
string | The format of the CLI output. | "text" |
"text", "json" |
ui
| Setting | Type | Description | Default |
|---|---|---|---|
ui.theme |
string | The color theme for the UI. See Themes for available options. | undefined |
ui.customThemes |
object | Custom theme definitions. | {} |
ui.statusLine |
object | Custom status line configuration. A shell command whose output is shown in the footer's left section. See Status Line. | undefined |
ui.hideWindowTitle |
boolean | Hide the window title bar. | false |
ui.hideTips |
boolean | Hide all tips (startup and post-response) in the UI. See Contextual Tips. | false |
ui.hideBanner |
boolean | Hide the startup ASCII logo and info panel. Tips and chat input still render unless ui.hideTips is also set. |
false |
ui.customBannerTitle |
string | Replace the default >_ Qwen Code title in the banner info panel. The (vX.Y.Z) version suffix is always appended; auth, model, and path lines are not affected. Sanitized; capped at 80 characters. |
"" |
ui.customBannerSubtitle |
string | Optional subtitle line rendered between the banner title and the auth/model line, in place of the blank spacer row. Sanitized; capped at 160 characters. Empty (default) keeps the original blank spacer. | "" |
ui.customAsciiArt |
string | object | Replace the QWEN ASCII logo in the banner. Accepts an inline string (used for both width tiers), { "path": "./brand.txt" } (relative paths resolve against the owning settings file's directory; read once at startup with O_NOFOLLOW on POSIX, capped at 64 KB), or { "small": ..., "large": ... } for width-aware selection. Sanitized; capped at 200 lines × 200 columns per tier. |
undefined |
ui.hideFooter |
boolean | Hide the footer from the UI. | false |
ui.showMemoryUsage |
boolean | Display memory usage information in the UI. | false |
ui.showLineNumbers |
boolean | Show line numbers in code blocks in the CLI output. | true |
ui.renderMode |
string | 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. See Markdown Rendering. |
"render" |
ui.showCitations |
boolean | Show citations for generated text in the chat. | true |
ui.compactMode |
boolean | Hide tool output and thinking for a cleaner view. Toggle with Ctrl+O during a session or via the Settings dialog. Tool approval prompts are never hidden, even in compact mode. The setting persists across sessions. |
false |
ui.shellOutputMaxLines |
number | Max number of shell output lines shown inline. Set to 0 to disable the cap and show full output. Hidden lines are surfaced via the +N lines indicator. Errors, !-prefix user-initiated commands, confirming tools, and focused embedded shells always show full output. |
5 |
enableWelcomeBack |
boolean | Show welcome back dialog when returning to a project with conversation history. When enabled, Qwen Code will automatically detect if you're returning to a project with a previously generated project summary (.qwen/PROJECT_SUMMARY.md) and show a dialog allowing you to continue your previous conversation or start fresh. If you choose Start new chat session, that choice is remembered for the current project until the project summary changes. This feature integrates with the /summary command and quit confirmation dialog. |
true |
ui.accessibility.enableLoadingPhrases |
boolean | Enable loading phrases (disable for accessibility). | true |
ui.accessibility.screenReader |
boolean | Enables screen reader mode, which adjusts the TUI for better compatibility with screen readers. | false |
ui.customWittyPhrases |
array of strings | A list of custom phrases to display during loading states. When provided, the CLI will cycle through these phrases instead of the default ones. | [] |
ui.enableFollowupSuggestions |
boolean | Enable followup suggestions that predict what you want to type next after the model responds. Suggestions appear as ghost text and can be accepted with Tab, Enter, or Right Arrow. | true |
ui.enableCacheSharing |
boolean | Use cache-aware forked queries for suggestion generation. Reduces cost on providers that support prefix caching (experimental). | true |
ui.enableSpeculation |
boolean | Speculatively execute accepted suggestions before submission. Results appear instantly when you accept (experimental). | false |
experimental.emitToolUseSummaries |
boolean | Generate short LLM-based labels summarizing each tool-call batch. See Tool-Use Summaries. Requires fastModel to be configured; silently skipped otherwise. Can be overridden per-session with QWEN_CODE_EMIT_TOOL_USE_SUMMARIES=0 or =1. |
true |
ide
| Setting | Type | Description | Default |
|---|---|---|---|
ide.enabled |
boolean | Enable IDE integration mode. | false |
ide.hasSeenNudge |
boolean | Whether the user has seen the IDE integration nudge. | false |
privacy
| Setting | Type | Description | Default |
|---|---|---|---|
privacy.usageStatisticsEnabled |
boolean | Enable collection of usage statistics. | true |
model
| Setting | Type | Description | Default |
|---|---|---|---|
model.name |
string | The Qwen model to use for conversations. | undefined |
model.maxSessionTurns |
number | Maximum number of user/model/tool turns to keep in a session. -1 means unlimited. | -1 |
model.maxWallTimeSeconds |
number | Wall-clock budget for headless / unattended runs, in seconds. -1 means unlimited. Overridable per-invocation via --max-wall-time, which requires a positive duration (90, 30s, 5m, 1h, 1.5h); the minimum is 1 second — sub-second values (500ms, 0.5) are rejected as typos. Omit the flag to fall back to this setting. Aborts with exit code 55 when exceeded. |
-1 |
model.maxToolCalls |
number | 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". Capped at 1,000,000 to catch typos. Overridable via --max-tool-calls. Aborts with exit code 55 when exceeded. |
-1 |
model.generationConfig |
object | Advanced overrides passed to the underlying content generator. Supports request controls such as timeout, maxRetries, enableCacheControl, splitToolMedia (set true for strict OpenAI-compatible servers like LM Studio that reject non-text content on role: "tool" messages — splits media into a follow-up user message), contextWindowSize (override model's context window size), modalities (override auto-detected input modalities), customHeaders (custom HTTP headers for API requests), and extra_body (additional body parameters for OpenAI-compatible API requests only), along with fine-tuning knobs under samplingParams (for example temperature, top_p, max_tokens). Leave unset to rely on provider defaults. |
undefined |
model.chatCompression.contextPercentageThreshold |
number | REMOVED. Auto-compaction now uses a three-tier threshold ladder (warn / auto / hard) computed internally from the model's context window via the computeThresholds() function — no longer user-configurable. Setting this field in settings.json is silently ignored (no startup warning). There is currently no replacement for "disable compression entirely" — reactive overflow recovery remains the safety net at the API layer if compression itself fails. (See PR #4345 / docs/design/auto-compaction-threshold-redesign.md for the redesign rationale.) |
N/A |
model.chatCompression.maxRecentFilesToRetain |
number | Number of most-recently-touched files whose current content is restored (embedded if small, otherwise referenced by path) into history after auto-compaction. 0 restores none. Env override: QWEN_COMPACT_MAX_RECENT_FILES. |
5 |
model.chatCompression.maxRecentImagesToRetain |
number | Number of most-recent images (tool screenshots / user pastes) restored into history after auto-compaction. 0 restores none. Env override: QWEN_COMPACT_MAX_RECENT_IMAGES. |
3 |
model.chatCompression.enableScreenshotTrigger |
boolean | When true, auto-compaction also fires once the number of tool-returned images accumulated in history reaches screenshotTriggerThreshold, independent of token usage — aimed at computer-use sessions where frequent screenshots dilute model attention. Counts only images returned inside tool results, not user-pasted images. Env override: QWEN_COMPACT_SCREENSHOT_TRIGGER (1/true/0/false). |
true |
model.chatCompression.screenshotTriggerThreshold |
number | Tool-returned image count at or above which the screenshot trigger fires (only when enableScreenshotTrigger). Compaction resets the count — surviving images are re-embedded as top-level parts, which the trigger doesn't count — so it won't immediately re-fire. Env override: QWEN_COMPACT_SCREENSHOT_THRESHOLD. |
50 |
model.skipNextSpeakerCheck |
boolean | Skip the next speaker check. | false |
model.skipLoopDetection |
boolean | Disables streaming loop detection checks. Defaults to true (loop detection is skipped) to avoid false positives interrupting legitimate workflows. Set to false to re-enable streaming loop detection — useful as a guardrail in headless / non-interactive runs where stuck repetition can otherwise waste budget. |
true |
model.skipStartupContext |
boolean | Skips sending the startup workspace context (environment summary and acknowledgement) at the beginning of each session. Enable this if you prefer to provide context manually or want to save tokens on startup. | false |
model.enableOpenAILogging |
boolean | Enables logging of OpenAI API calls for debugging and analysis. When enabled, API requests and responses are logged to JSON files. | false |
model.openAILoggingDir |
string | Custom directory path for OpenAI API logs. If not specified, defaults to logs/openai in the current working directory. Supports absolute paths, relative paths (resolved from current working directory), and ~ expansion (home directory). |
undefined |
Example model.generationConfig:
{
"model": {
"generationConfig": {
"timeout": 60000,
"contextWindowSize": 128000,
"modalities": {
"image": true
},
"enableCacheControl": true,
"customHeaders": {
"X-Client-Request-ID": "req-123"
},
"extra_body": {
"enable_thinking": true
},
"samplingParams": {
"temperature": 0.2,
"top_p": 0.8,
"max_tokens": 1024
}
}
}
}
max_tokens (adaptive output tokens):
When samplingParams.max_tokens is not set, Qwen Code uses an adaptive output token strategy to optimize GPU resource usage:
- Requests start with a default limit of 8K output tokens
- If the response is truncated (the model hits the limit), Qwen Code automatically retries with 64K tokens
- The partial output is discarded and replaced with the full response from the retry
This is transparent to users — you may briefly see a retry indicator if escalation occurs. Since 99% of responses are under 5K tokens, the retry happens rarely (<1% of requests).
To override this behavior, either set samplingParams.max_tokens in your settings or use the QWEN_CODE_MAX_OUTPUT_TOKENS environment variable.
contextWindowSize:
Overrides the default context window size for the selected model. Qwen Code determines the context window using built-in defaults based on model name matching, with a constant fallback value. 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.
When the selected model is defined in modelProviders, set
contextWindowSize in that provider entry's generationConfig instead of the
top-level model.generationConfig. Provider model entries are sealed, so
top-level generation settings do not fill missing provider fields.
modalities:
Overrides the auto-detected input modalities for the selected model. Qwen Code automatically detects supported modalities (image, PDF, audio, video) based on model name pattern matching. Use this setting when the auto-detection is incorrect — for example, to enable pdf for a model that supports it but isn't recognized. Format: { "image": true, "pdf": true, "audio": true, "video": true }. Omit a key or set it to false for unsupported types.
customHeaders:
Allows you to add custom HTTP headers to all API requests. This is useful for request tracing, monitoring, API gateway routing, or when different models require different headers. For provider models, define customHeaders in modelProviders[].generationConfig.customHeaders. For runtime models without a matching provider entry, define it in model.generationConfig.customHeaders. No merging occurs between the two levels.
The extra_body field allows you to add custom parameters to the request body sent to the API. This is useful for provider-specific options that are not covered by the standard configuration fields. Note: This field is only supported for OpenAI-compatible providers (openai, qwen-oauth). It is ignored for Anthropic and Gemini providers. For provider models, define extra_body in modelProviders[].generationConfig.extra_body. For runtime models without a matching provider entry, define it in model.generationConfig.extra_body.
model.openAILoggingDir examples:
"~/qwen-logs"- Logs to~/qwen-logsdirectory"./custom-logs"- Logs to./custom-logsrelative to current directory"/tmp/openai-logs"- Logs to absolute path/tmp/openai-logs
fastModel
| Setting | Type | Description | Default |
|---|---|---|---|
fastModel |
string | 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. Can also be set via /model --fast. |
"" |
context
| Setting | Type | Description | Default |
|---|---|---|---|
context.fileName |
string or array of strings | The name of the context file(s). | undefined |
context.importFormat |
string | The format to use when importing memory. | undefined |
context.includeDirectories |
array | Additional directories to include in the workspace context. Specifies an array of additional absolute or relative paths to include in the workspace context. Missing directories will be skipped with a warning by default. Paths can use ~ to refer to the user's home directory. This setting can be combined with the --include-directories command-line flag. |
[] |
context.loadFromIncludeDirectories |
boolean | Controls the behavior of the /memory refresh command. If set to true, QWEN.md files should be loaded from all directories that are added. If set to false, QWEN.md should only be loaded from the current directory. |
false |
context.fileFiltering.respectGitIgnore |
boolean | Respect .gitignore files when searching. | true |
context.fileFiltering.respectQwenIgnore |
boolean | Respect .qwenignore files when searching. | true |
context.fileFiltering.enableRecursiveFileSearch |
boolean | Whether to enable searching recursively for filenames under the current tree when completing @ prefixes in the prompt. |
true |
context.fileFiltering.enableFuzzySearch |
boolean | When true, enables fuzzy search capabilities when searching for files. Set to false to improve performance on projects with a large number of files. |
true |
context.clearContextOnIdle.toolResultsThresholdMinutes |
number | Minutes of inactivity before clearing old tool result content. Use -1 to disable. |
60 |
context.clearContextOnIdle.toolResultsNumToKeep |
number | Number of most-recent compactable tool results to preserve when clearing. Floor at 1. | 5 |
Troubleshooting File Search Performance
If you are experiencing performance issues with file searching (e.g., with @ completions), especially in projects with a very large number of files, here are a few things you can try in order of recommendation:
- Use
.qwenignore: Create a.qwenignorefile in your project root to exclude directories that contain a large number of files that you don't need to reference (e.g., build artifacts, logs,node_modules). Reducing the total number of files crawled is the most effective way to improve performance. - Disable Fuzzy Search: If ignoring files is not enough, you can disable fuzzy search by setting
enableFuzzySearchtofalsein yoursettings.jsonfile. This will use a simpler, non-fuzzy matching algorithm, which can be faster. - Disable Recursive File Search: As a last resort, you can disable recursive file search entirely by setting
enableRecursiveFileSearchtofalse. This will be the fastest option as it avoids a recursive crawl of your project. However, it means you will need to type the full path to files when using@completions.
tools
| Setting | Type | Description | Default | Notes |
|---|---|---|---|---|
tools.sandbox |
boolean or string | Sandbox execution environment (can be a boolean or a path string). | undefined |
|
tools.sandboxImage |
string | Sandbox image URI used by Docker/Podman when --sandbox-image and QWEN_SANDBOX_IMAGE are not set. |
undefined |
|
tools.shell.enableInteractiveShell |
boolean | Use node-pty for an interactive shell experience. Fallback to child_process still applies. |
false |
|
tools.core |
array of strings | Deprecated. Will be removed in next version. Use permissions.allow + permissions.deny instead. Restricts built-in tools to an allowlist. All tools not in the list are disabled. |
undefined |
|
tools.exclude |
array of strings | Deprecated. Use permissions.deny instead. Tool names to exclude from discovery. Automatically migrated to the permissions format on first load. |
undefined |
|
tools.allowed |
array of strings | Deprecated. Use permissions.allow instead. Tool names that bypass the confirmation dialog. Automatically migrated to the permissions format on first load. |
undefined |
|
tools.approvalMode |
string | Sets the default approval mode for tool usage. | default |
Possible values: plan (analyze only, do not modify files or execute commands), default (require approval before file edits or shell commands run), auto-edit (automatically approve file edits), yolo (automatically approve all tool calls) |
tools.discoveryCommand |
string | Command to run for tool discovery. | undefined |
|
tools.callCommand |
string | Defines a custom shell command for calling a specific tool that was discovered using tools.discoveryCommand. The shell command must meet the following criteria: It must take function name (exactly as in function declaration) as first command line argument. It must read function arguments as JSON on stdin, analogous to functionCall.args. It must return function output as JSON on stdout, analogous to functionResponse.response.content. |
undefined |
|
tools.useRipgrep |
boolean | Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance. | true |
|
tools.useBuiltinRipgrep |
boolean | Use the bundled ripgrep binary. When set to false, the system-level rg command will be used instead. This setting is only effective when tools.useRipgrep is true. |
true |
|
tools.truncateToolOutputThreshold |
number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | 25000 |
Requires restart: Yes |
tools.truncateToolOutputLines |
number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | 1000 |
Requires restart: Yes |
Note
Migrating from
tools.core/tools.exclude/tools.allowed: These legacy settings are deprecated and automatically migrated to the newpermissionsformat on first load. Prefer configuringpermissions.allow/permissions.denydirectly. Use/permissionsto manage rules interactively.
memory
| Setting | Type | Description | Default |
|---|---|---|---|
memory.enableManagedAutoMemory |
boolean | Enable background extraction of memories from conversations. | true |
memory.enableManagedAutoDream |
boolean | Enable automatic consolidation (deduplication and cleanup) of collected memories. | true |
memory.enableAutoSkill |
boolean | Enable background review for reusable project skills after tool-heavy sessions. | true |
See Memory for details on how auto-memory works and how to use the /memory, /remember, and /dream commands.
permissions
The permissions system provides fine-grained control over which tools can run, which require confirmation, and which are blocked.
Decision priority (highest first): deny > ask > allow > (default/interactive mode)
The first matching rule wins. Rules use the format "ToolName" or "ToolName(specifier)".
| Setting | Type | Description | Default |
|---|---|---|---|
permissions.allow |
array of strings | Rules for auto-approved tool calls (no confirmation needed). Merged across all scopes (user + project + system). | undefined |
permissions.ask |
array of strings | Rules for tool calls that always require user confirmation. Takes priority over allow. |
undefined |
permissions.deny |
array of strings | Rules for blocked tool calls. Highest priority — overrides both allow and ask. |
undefined |
Tool name aliases (any of these work in rules):
| Alias | Canonical tool | Notes |
|---|---|---|
Bash, Shell |
run_shell_command |
|
Read, ReadFile |
read_file |
Meta-category — see below |
Edit, EditFile |
edit |
Meta-category — see below |
Write, WriteFile |
write_file |
|
NotebookEdit |
notebook_edit |
|
NotebookEditTool |
notebook_edit |
|
Grep, SearchFiles |
grep_search |
|
Glob, FindFiles |
glob |
|
ListFiles |
list_directory |
|
WebFetch |
web_fetch |
|
Agent |
task |
|
Skill |
skill |
Meta-categories:
Some rule names automatically cover multiple tools:
| Rule name | Tools covered |
|---|---|
Read |
read_file, grep_search, glob, list_directory |
Edit |
edit, write_file, notebook_edit |
Important
Read(/path/**)matches all four read tools (file read, grep, glob, and directory listing). To restrict only file reading, useReadFile(/path/**)orread_file(/path/**).
Rule syntax examples:
| Rule | Meaning |
|---|---|
"Bash" |
All shell commands |
"Bash(git *)" |
Shell commands starting with git (word boundary: NOT gitk) |
"Bash(git push *)" |
Shell commands like git push origin main |
"Bash(npm run *)" |
Any npm run script |
"Read" |
All file read operations (read, grep, glob, list) |
"Read(./secrets/**)" |
Read any file under ./secrets/ recursively |
"Edit(/src/**/*.ts)" |
Edit TypeScript files under project root /src/ |
"WebFetch(api.example.com)" |
Fetch from api.example.com and all its subdomains |
"mcp__puppeteer" |
All tools from the puppeteer MCP server |
Path pattern prefixes:
| Prefix | Meaning | Example |
|---|---|---|
// |
Absolute path from filesystem root | //etc/passwd |
~/ |
Relative to home directory | ~/Documents/*.pdf |
/ |
Relative to project root | /src/**/*.ts |
./ |
Relative to current working directory | ./secrets/** |
| (none) | Same as ./ |
secrets/** |
Shell command bypass prevention:
Permission rules for Read, Edit, and WebFetch are also enforced when the agent runs equivalent shell commands. For example, if Read(./.env) is in deny, the agent cannot bypass it via cat .env in a shell command. Supported shell commands include cat, grep, curl, wget, cp, mv, rm, chmod, and many more. Unknown/safe commands (e.g. git) are unaffected by file/network rules.
Migrating from legacy settings:
| Legacy setting | Equivalent permissions rule |
Notes |
|---|---|---|
tools.allowed |
permissions.allow |
Auto-migrated on first load |
tools.exclude |
permissions.deny |
Auto-migrated on first load |
tools.core |
permissions.allow (allowlist) |
Auto-migrated; unlisted tools are disabled at registry level |
Example configuration:
{
"permissions": {
"allow": ["Bash(git *)", "Bash(npm run *)", "Read(//Users/alice/code/**)"],
"ask": ["Bash(git push *)", "Edit"],
"deny": ["Bash(rm -rf *)", "Read(.env)", "WebFetch(malicious.com)"]
}
}
Tip
Use
/permissionsin the interactive CLI to view, add, and remove rules without editingsettings.jsondirectly.
slashCommands
Controls which slash commands are available in the CLI. Useful for locking down the command surface in multi-tenant or enterprise deployments.
| Setting | Type | Description | Default |
|---|---|---|---|
slashCommands.disabled |
array of strings | 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 scopes, so workspace settings can add to but not remove entries defined in user or system settings. |
undefined |
The same denylist can also be provided via the --disabled-slash-commands CLI
flag (comma-separated or repeated) and the QWEN_DISABLED_SLASH_COMMANDS
environment variable; values from all three sources are unioned together.
Example — lock down built-ins for a sandboxed deployment:
{
"slashCommands": {
"disabled": ["auth", "mcp", "extensions", "ide", "quit"]
}
}
With these values in a system-level settings.json (/etc/qwen-code/settings.json
or QWEN_CODE_SYSTEM_SETTINGS_PATH), users cannot shrink the denylist from
their own scope, and the disabled commands will not appear in autocomplete or
execute when typed.
Note
This setting only gates slash commands (e.g.
/auth,/mcp). It does not affect tool permissions — seepermissions.denyfor that. It also does not intercept keyboard shortcuts such asCtrl+CorEsc.
mcp
| Setting | Type | Description | Default |
|---|---|---|---|
mcp.serverCommand |
string | Command to start an MCP server. | undefined |
mcp.allowed |
array of strings | An allowlist of MCP servers to allow. Allows you to specify a list of MCP server names that should be made available to the model. This can be used to restrict the set of MCP servers to connect to. Note that this will be ignored if --allowed-mcp-server-names is set. |
undefined |
mcp.excluded |
array of strings | A denylist of MCP servers to exclude. A server listed in both mcp.excluded and mcp.allowed is excluded. Note that this will be ignored if --allowed-mcp-server-names is set. |
undefined |
Note
Security Note for MCP servers: These settings use simple string matching on MCP server names, which can be modified. If you're a system administrator looking to prevent users from bypassing this, consider configuring the
mcpServersat the system settings level such that the user will not be able to configure any MCP servers of their own. This should not be used as an airtight security mechanism.
lsp
Warning
Experimental Feature: LSP support is currently experimental and disabled by default. Enable it using the
--experimental-lspcommand line flag.
Language Server Protocol (LSP) provides code intelligence features like go-to-definition, find references, and diagnostics.
LSP server configuration is done through .lsp.json files in your project root directory, not through settings.json. See the LSP documentation for configuration details and examples.
security
| Setting | Type | Description | Default |
|---|---|---|---|
security.folderTrust.enabled |
boolean | Setting to track whether Folder trust is enabled. | false |
security.auth.selectedType |
string | The currently selected authentication type. | undefined |
security.auth.enforcedType |
string | The required auth type (useful for enterprises). | undefined |
security.auth.useExternal |
boolean | Whether to use an external authentication flow. | undefined |
advanced
| Setting | Type | Description | Default |
|---|---|---|---|
advanced.autoConfigureMemory |
boolean | Automatically configure Node.js memory limits. | false |
advanced.dnsResolutionOrder |
string | The DNS resolution order. | undefined |
advanced.excludedEnvVars |
array of strings | Environment variables to exclude from project context. Specifies environment variables that should be excluded from being loaded from project .env files. This prevents project-specific environment variables (like DEBUG=true) from interfering with the CLI behavior. Variables from .qwen/.env files are never excluded. |
["DEBUG","DEBUG_MODE"] |
advanced.bugCommand |
object | Configuration for the bug report command. Overrides the default URL for the /bug command. Properties: urlTemplate (string): A URL that can contain {title} and {info} placeholders. Example: "bugCommand": { "urlTemplate": "https://bug.example.com/new?title={title}&info={info}" } |
undefined |
plansDirectory |
string | 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. If unset, plan files are stored in ~/.qwen/plans. Requires restart. If the directory is inside the project root, add it to .gitignore to avoid committing plan files. |
undefined |
mcpServers
Configures connections to one or more Model-Context Protocol (MCP) servers for discovering and using custom tools. Qwen Code attempts to connect to each configured MCP server to discover available tools. If multiple MCP servers expose a tool with the same name, the tool names will be prefixed with the server alias you defined in the configuration (e.g., serverAlias__actualToolName) to avoid conflicts. Note that the system might strip certain schema properties from MCP tool definitions for compatibility. At least one of command, url, or httpUrl must be provided. If multiple are specified, the order of precedence is httpUrl, then url, then command.
| Property | Type | Description | Optional |
|---|---|---|---|
mcpServers.<SERVER_NAME>.command |
string | The command to execute to start the MCP server via standard I/O. | Yes |
mcpServers.<SERVER_NAME>.args |
array of strings | Arguments to pass to the command. | Yes |
mcpServers.<SERVER_NAME>.env |
object | Environment variables to set for the server process. | Yes |
mcpServers.<SERVER_NAME>.cwd |
string | The working directory in which to start the server. | Yes |
mcpServers.<SERVER_NAME>.url |
string | The URL of an MCP server that uses Server-Sent Events (SSE) for communication. | Yes |
mcpServers.<SERVER_NAME>.httpUrl |
string | The URL of an MCP server that uses streamable HTTP for communication. | Yes |
mcpServers.<SERVER_NAME>.headers |
object | A map of HTTP headers to send with requests to url or httpUrl. |
Yes |
mcpServers.<SERVER_NAME>.timeout |
number | Timeout in milliseconds for requests to this MCP server. | Yes |
mcpServers.<SERVER_NAME>.trust |
boolean | Trust this server and bypass all tool call confirmations. | Yes |
mcpServers.<SERVER_NAME>.description |
string | A brief description of the server, which may be used for display purposes. | Yes |
mcpServers.<SERVER_NAME>.includeTools |
array of strings | List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (allowlist behavior). If not specified, all tools from the server are enabled by default. | Yes |
mcpServers.<SERVER_NAME>.excludeTools |
array of strings | List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. Note: excludeTools takes precedence over includeTools - if a tool is in both lists, it will be excluded. |
Yes |
telemetry
Configures logging and metrics collection for Qwen Code. For more information, see telemetry.
| Setting | Type | Description | Default |
|---|---|---|---|
telemetry.enabled |
boolean | Whether or not telemetry is enabled. | |
telemetry.target |
string | Informational label for the telemetry destination (local or gcp). Does not control exporter routing; set telemetry.otlpEndpoint or telemetry.outfile to configure where data is sent. |
|
telemetry.otlpEndpoint |
string | The endpoint for the OTLP Exporter. | |
telemetry.otlpProtocol |
string | The protocol for the OTLP Exporter (grpc or http). |
|
telemetry.logPrompts |
boolean | Whether or not to include the content of user prompts in the logs. | |
telemetry.includeSensitiveSpanAttributes |
boolean | When enabled, attaches verbatim user prompts, system prompts, tool inputs/outputs, and model responses to native OTel span attributes (in addition to log-to-span bridge spans). ⚠️ Streams sensitive data — file contents, shell commands, conversation history — to your OTLP backend. | false |
telemetry.outfile |
string | Path to write telemetry to a file. When set, overrides OTLP export. |
Example settings.json
Here is an example of a settings.json file with the nested structure, new as of v0.3.0:
{
"proxy": "http://localhost:7890",
"plansDirectory": "./.qwen/plans",
"general": {
"vimMode": true,
"preferredEditor": "code"
},
"ui": {
"theme": "GitHub",
"hideTips": false,
"customWittyPhrases": [
"You forget a thousand things every day. Make sure this is one of 'em",
"Connecting to AGI"
]
},
"tools": {
"approvalMode": "yolo",
"sandbox": "docker",
"sandboxImage": "ghcr.io/qwenlm/qwen-code:0.14.1",
"discoveryCommand": "bin/get_tools",
"callCommand": "bin/call_tool",
"exclude": ["write_file"]
},
"mcpServers": {
"mainServer": {
"command": "bin/mcp_server.py"
},
"anotherServer": {
"command": "node",
"args": ["mcp_server.js", "--verbose"]
}
},
"telemetry": {
"enabled": true,
"target": "local",
"otlpEndpoint": "http://localhost:4317",
"logPrompts": true,
"includeSensitiveSpanAttributes": false
},
"privacy": {
"usageStatisticsEnabled": true
},
"model": {
"name": "qwen3-coder-plus",
"maxSessionTurns": 10,
"enableOpenAILogging": false,
"openAILoggingDir": "~/qwen-logs",
},
"context": {
"fileName": ["CONTEXT.md", "QWEN.md"],
"includeDirectories": ["path/to/dir1", "~/path/to/dir2", "../path/to/dir3"],
"loadFromIncludeDirectories": true,
"fileFiltering": {
"respectGitIgnore": false
}
},
"advanced": {
"excludedEnvVars": ["DEBUG", "DEBUG_MODE", "NODE_ENV"]
}
}
Shell History
The CLI keeps a history of shell commands you run. To avoid conflicts between different projects, this history is stored in a project-specific directory within your user's home folder.
- Location:
~/.qwen/tmp/<project_hash>/shell_history<project_hash>is a unique identifier generated from your project's root path.- The history is stored in a file named
shell_history.
Environment Variables & .env Files
Environment variables are a common way to configure applications, especially for sensitive information (like tokens) or for settings that might change between environments.
Qwen Code can automatically load environment variables from .env files.
For authentication-related variables (like OPENAI_*) and the recommended .qwen/.env approach, see Authentication.
Tip
Environment Variable Exclusion: Some environment variables (like
DEBUGandDEBUG_MODE) are automatically excluded from project.envfiles by default to prevent interference with the CLI behavior. Variables from.qwen/.envfiles are never excluded. You can customize this behavior using theadvanced.excludedEnvVarssetting in yoursettings.jsonfile.
Environment Variables Table
| Variable | Description | Notes |
|---|---|---|
QWEN_HOME |
Customizes the global configuration directory (default: ~/.qwen). Accepts an absolute or relative path (relative paths are resolved from the current working directory). Leading ~ is expanded to the user's home directory. |
Stores credentials, settings, memory, skills, and other global state. When set, project-level .qwen/ directories are unaffected. An empty string is treated as unset. |
QWEN_RUNTIME_DIR |
Overrides the runtime output directory (conversations, logs, todos). When unset, defaults to the QWEN_HOME directory. |
Use this to separate ephemeral runtime data from persistent config. Useful when QWEN_HOME is on a shared/slow filesystem. |
QWEN_TELEMETRY_ENABLED |
Set to true or 1 to enable telemetry. Any other value is treated as disabling it. |
Overrides the telemetry.enabled setting. |
QWEN_TELEMETRY_TARGET |
Sets an informational label for the telemetry destination (local or gcp). Does not control routing; use QWEN_TELEMETRY_OTLP_ENDPOINT or QWEN_TELEMETRY_OUTFILE to configure where data is sent. |
Overrides the telemetry.target setting. |
QWEN_TELEMETRY_OTLP_ENDPOINT |
Sets the OTLP endpoint for telemetry. | Overrides the telemetry.otlpEndpoint setting. |
QWEN_TELEMETRY_OTLP_PROTOCOL |
Sets the OTLP protocol (grpc or http). |
Overrides the telemetry.otlpProtocol setting. |
QWEN_TELEMETRY_LOG_PROMPTS |
Set to true or 1 to enable or disable logging of user prompts. Any other value is treated as disabling it. |
Overrides the telemetry.logPrompts setting. |
QWEN_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES |
Set to true or 1 to attach verbatim user prompts, system prompts, tool I/O, and model responses to native OTel span attributes (and keep prompt / function_args / response_text on log-to-span bridge spans). Any other value disables it. |
Overrides the telemetry.includeSensitiveSpanAttributes setting. ⚠️ Streams sensitive data to your OTLP backend. |
QWEN_TELEMETRY_OUTFILE |
Sets the file path to write telemetry to. When set, overrides OTLP export. | Overrides the telemetry.outfile setting. |
QWEN_SANDBOX |
Alternative to the sandbox setting in settings.json. |
Accepts true, false, docker, podman, or a custom command string. |
QWEN_SANDBOX_IMAGE |
Overrides sandbox image selection for Docker/Podman. | Takes precedence over tools.sandboxImage. |
SEATBELT_PROFILE |
(macOS specific) Switches the Seatbelt (sandbox-exec) profile on macOS. |
permissive-open: (Default) Restricts writes to the project folder (and a few other folders, see packages/cli/src/utils/sandbox-macos-permissive-open.sb) but allows other operations. strict: Uses a strict profile that declines operations by default. <profile_name>: Uses a custom profile. To define a custom profile, create a file named sandbox-macos-<profile_name>.sb in your project's .qwen/ directory (e.g., my-project/.qwen/sandbox-macos-custom.sb). |
DEBUG or DEBUG_MODE |
(often used by underlying libraries or the CLI itself) Set to true or 1 to enable verbose debug logging, which can be helpful for troubleshooting. |
Note: These variables are automatically excluded from project .env files by default to prevent interference with the CLI behavior. Use .qwen/.env files if you need to set these for Qwen Code specifically. |
NO_COLOR |
Set to any value to disable all color output in the CLI. | |
FORCE_HYPERLINK |
Override the OSC 8 clickable-link detection in the markdown renderer. Set to 1 (or any non-zero value, or empty string) to force-enable, 0 to force-disable. Honors NO_COLOR / QWEN_DISABLE_HYPERLINKS opt-outs above it. |
Use this to opt into OSC 8 inside tmux / GNU screen (auto-detection refuses by default because the host terminal's capabilities are hidden behind the multiplexer). Requires set -g allow-passthrough on on tmux 3.3+. Also enables Hyper, which isn't auto-detected. |
QWEN_DISABLE_HYPERLINKS |
Set to 1 to hard-disable OSC 8 clickable hyperlinks in the markdown renderer even on terminals that auto-detect as capable. |
Useful when a terminal advertises support but breaks on long URLs, or when piping output through an intermediary that mangles escape sequences. The renderer falls back to plain label (url) rendering. |
CLI_TITLE |
Set to a string to customize the title of the CLI. | |
CODE_ASSIST_ENDPOINT |
Specifies the endpoint for the code assist server. | This is useful for development and testing. |
QWEN_CODE_MAX_OUTPUT_TOKENS |
Overrides the default maximum output tokens per response. When not set, Qwen Code uses an adaptive strategy: starts with 8K tokens and automatically retries with 64K if the response is truncated. Set this to a specific value (e.g., 16000) to use a fixed limit instead. |
Takes precedence over the capped default (8K) but is overridden by samplingParams.max_tokens in settings. Disables automatic escalation when set. Example: export QWEN_CODE_MAX_OUTPUT_TOKENS=16000 |
QWEN_CODE_UNATTENDED_RETRY |
Set to true or 1 to enable persistent retry mode. When enabled, transient API capacity errors (HTTP 429 Rate Limit and 529 Overloaded) are retried indefinitely with exponential backoff (capped at 5 minutes per retry) and heartbeat keepalives every 30 seconds on stderr. |
Designed for CI/CD pipelines and background automation where long-running tasks should survive temporary API outages. Must be set explicitly — CI=true alone does not activate this mode. See Headless Mode for details. Example: export QWEN_CODE_UNATTENDED_RETRY=1 |
QWEN_CODE_PROFILE_STARTUP |
Set to 1 to enable startup performance profiling. Writes a JSON timing report to ~/.qwen/startup-perf/ with per-phase durations. |
Only active inside the sandbox child process (or with QWEN_CODE_PROFILE_STARTUP_OUTER=1). Zero overhead when not set. Example: export QWEN_CODE_PROFILE_STARTUP=1 |
QWEN_CODE_PROFILE_STARTUP_OUTER |
Set to 1 together with QWEN_CODE_PROFILE_STARTUP=1 to also collect a startup profile in the outer (pre-sandbox) process. Outer-process reports get an outer- filename prefix to keep them distinct from the sandbox child's report. |
Off by default — only the sandbox child collects, to avoid duplicate reports. Useful for local development where the cli isn't relaunched into a sandbox. |
QWEN_CODE_PROFILE_STARTUP_NO_HEAP |
Set to 1 together with QWEN_CODE_PROFILE_STARTUP=1 to skip the per-checkpoint process.memoryUsage() snapshots. Useful when measuring the profiler's own Heisenberg overhead. |
Off by default. Heap snapshots cost ~50 µs each (well below 1% of total startup) so most users should leave this alone. |
QWEN_CODE_LEGACY_MCP_BLOCKING |
Set to 1 to restore the pre-progressive-MCP behavior where Config.initialize() waits synchronously for every configured MCP server's discover handshake before returning. |
Off by default. Modern qwen-code lets MCP servers come online in the background while the UI is already interactive; the model sees each batch of new tools within ~16 ms of the server settling. This flag is kept as a rollback escape hatch for ≥ 1 release. Example: export QWEN_CODE_LEGACY_MCP_BLOCKING=1 |
When both user-level .env files define the same variable, the Qwen-specific
file wins: <QWEN_HOME>/.env (or ~/.qwen/.env when QWEN_HOME is unset) is
loaded before ~/.env, and existing environment values are not overwritten.
Command-Line Arguments
Arguments passed directly when running the CLI can override other configurations for that specific session.
For sandbox image selection, precedence is:
--sandbox-image > QWEN_SANDBOX_IMAGE > tools.sandboxImage > built-in default image.
Command-Line Arguments Table
| Argument | Alias | Description | Possible Values | Notes |
|---|---|---|---|---|
--model |
-m |
Specifies the Qwen model to use for this session. | Model name | Example: npm start -- --model qwen3-coder-plus |
--prompt |
-p |
Used to pass a prompt directly to the command. This invokes Qwen Code in a non-interactive mode. | Your prompt text | For scripting examples, use the --output-format json flag to get structured output. |
--prompt-interactive |
-i |
Starts an interactive session with the provided prompt as the initial input. | Your prompt text | The prompt is processed within the interactive session, not before it. Cannot be used when piping input from stdin. Example: qwen -i "explain this code" |
--system-prompt |
Overrides the built-in main session system prompt for this run. | Your prompt text | Loaded context files such as QWEN.md are still appended after this override. Can be combined with --append-system-prompt. |
|
--append-system-prompt |
Appends extra instructions to the main session system prompt for this run. | Your prompt text | Applied after the built-in prompt and loaded context files. Can be combined with --system-prompt. See Headless Mode for examples. |
|
--output-format |
-o |
Specifies the format of the CLI output for non-interactive mode. | text, json, stream-json |
text: (Default) The standard human-readable output. json: A machine-readable JSON output emitted at the end of execution. stream-json: Streaming JSON messages emitted as they occur during execution. For structured output and scripting, use the --output-format json or --output-format stream-json flag. See Headless Mode for detailed information. |
--input-format |
Specifies the format consumed from standard input. | text, stream-json |
text: (Default) Standard text input from stdin or command-line arguments. stream-json: JSON message protocol via stdin for bidirectional communication. Requirement: --input-format stream-json requires --output-format stream-json to be set. When using stream-json, stdin is reserved for protocol messages. See Headless Mode for detailed information. |
|
--include-partial-messages |
Include partial assistant messages when using stream-json output format. When enabled, emits stream events (message_start, content_block_delta, etc.) as they occur during streaming. |
Default: false. Requirement: Requires --output-format stream-json to be set. See Headless Mode for detailed information about stream events. |
||
--sandbox |
-s |
Enables sandbox mode for this session. | ||
--sandbox-image |
Sets the sandbox image URI. | |||
--debug |
-d |
Enables debug mode for this session, providing more verbose output. | ||
--all-files |
-a |
If set, recursively includes all files within the current directory as context for the prompt. | ||
--help |
-h |
Displays help information about command-line arguments. | ||
--show-memory-usage |
Displays the current memory usage. | |||
--yolo |
Enables YOLO mode, which automatically approves all tool calls. | |||
--approval-mode |
Sets the approval mode for tool calls. | plan, default, auto-edit, yolo |
Supported modes: plan: Analyze only—do not modify files or execute commands. default: Require approval for file edits or shell commands (default behavior). auto-edit: Automatically approve edit tools (edit, write_file, notebook_edit) while prompting for others. yolo: Automatically approve all tool calls (equivalent to --yolo). Cannot be used together with --yolo. Use --approval-mode=yolo instead of --yolo for the new unified approach. Example: qwen --approval-mode auto-editSee more about Approval Mode. |
|
--allowed-tools |
A comma-separated list of tool names that will bypass the confirmation dialog. | Tool names | Example: qwen --allowed-tools "Shell(git status)" |
|
--disabled-slash-commands |
Slash command names to hide/disable (comma-separated or repeated). Unioned with the slashCommands.disabled setting and the QWEN_DISABLED_SLASH_COMMANDS environment variable. Matched case-insensitively against the final command name. |
Command names | Example: qwen --disabled-slash-commands "auth,mcp,extensions" |
|
--telemetry |
Enables telemetry. | |||
--telemetry-target |
Sets the telemetry target. | See telemetry for more information. | ||
--telemetry-otlp-endpoint |
Sets the OTLP endpoint for telemetry. | See telemetry for more information. | ||
--telemetry-otlp-protocol |
Sets the OTLP protocol for telemetry (grpc or http). |
Defaults to grpc. See telemetry for more information. |
||
--telemetry-log-prompts |
Enables logging of prompts for telemetry. | See telemetry for more information. | ||
--checkpointing |
Enables checkpointing. | |||
--acp |
Enables ACP mode (Agent Client Protocol). Useful for IDE/editor integrations like Zed. | Stable. Replaces the deprecated --experimental-acp flag. |
||
--experimental-lsp |
Enables experimental LSP (Language Server Protocol) feature for code intelligence (go-to-definition, find references, diagnostics, etc.). | Experimental. Requires language servers to be installed. | ||
--extensions |
-e |
Specifies a list of extensions to use for the session. | Extension names | If not provided, all available extensions are used. Use the special term qwen -e none to disable all extensions. Example: qwen -e my-extension -e my-other-extension |
--list-extensions |
-l |
Lists all available extensions and exits. | ||
--proxy |
Sets the proxy for the CLI. | Proxy URL | Example: --proxy http://localhost:7890. |
|
--include-directories |
Includes additional directories in the workspace for multi-directory support. | Directory paths | Can be specified multiple times or as comma-separated values. 5 directories can be added at maximum. Example: --include-directories /path/to/project1,/path/to/project2 or --include-directories /path/to/project1 --include-directories /path/to/project2 |
|
--screen-reader |
Enables screen reader mode, which adjusts the TUI for better compatibility with screen readers. | |||
--version |
Displays the version of the CLI. | |||
--openai-logging |
Enables logging of OpenAI API calls for debugging and analysis. | This flag overrides the enableOpenAILogging setting in settings.json. |
||
--openai-logging-dir |
Sets a custom directory path for OpenAI API logs. | Directory path | This flag overrides the openAILoggingDir setting in settings.json. Supports absolute paths, relative paths, and ~ expansion. Example: qwen --openai-logging-dir "~/qwen-logs" --openai-logging |
Context Files (Hierarchical Instructional Context)
While not strictly configuration for the CLI's behavior, context files (defaulting to QWEN.md but configurable via the context.fileName setting) are crucial for configuring the instructional context (also referred to as "memory"). This powerful feature allows you to give project-specific instructions, coding style guides, or any relevant background information to the AI, making its responses more tailored and accurate to your needs. The CLI includes UI elements, such as an indicator in the footer showing the number of loaded context files, to keep you informed about the active context.
- Purpose: These Markdown files contain instructions, guidelines, or context that you want the Qwen model to be aware of during your interactions. The system is designed to manage this instructional context hierarchically.
Example Context File Content (e.g. QWEN.md)
Here's a conceptual example of what a context file at the root of a TypeScript project might contain:
# Project: My Awesome TypeScript Library
## General Instructions:
- When generating new TypeScript code, please follow the existing coding style.
- Ensure all new functions and classes have JSDoc comments.
- Prefer functional programming paradigms where appropriate.
- All code should be compatible with TypeScript 5.0 and Node.js 22+.
## Coding Style:
- Use 2 spaces for indentation.
- Interface names should be prefixed with `I` (e.g., `IUserService`).
- Private class members should be prefixed with an underscore (`_`).
- Always use strict equality (`===` and `!==`).
## Specific Component: `src/api/client.ts`
- This file handles all outbound API requests.
- When adding new API call functions, ensure they include robust error handling and logging.
- Use the existing `fetchWithRetry` utility for all GET requests.
## Regarding Dependencies:
- Avoid introducing new external dependencies unless absolutely necessary.
- If a new dependency is required, please state the reason.
This example demonstrates how you can provide general project context, specific coding conventions, and even notes about particular files or components. The more relevant and precise your context files are, the better the AI can assist you. Project-specific context files are highly encouraged to establish conventions and context.
- Hierarchical Loading and Precedence: The CLI implements a hierarchical memory system by loading context files (e.g.,
QWEN.md) from several locations. Content from files lower in this list (more specific) typically overrides or supplements content from files higher up (more general). The exact concatenation order and final context can be inspected using the/memory showcommand. The typical loading order is:- Global Context File:
- Location:
~/.qwen/<configured-context-filename>(e.g.,~/.qwen/QWEN.mdin your user home directory). - Scope: Provides default instructions for all your projects.
- Location:
- Project Root & Ancestors Context Files:
- Location: The CLI searches for the configured context file in the current working directory and then in each parent directory up to either the project root (identified by a
.gitfolder) or your home directory. - Scope: Provides context relevant to the entire project or a significant portion of it.
- Location: The CLI searches for the configured context file in the current working directory and then in each parent directory up to either the project root (identified by a
- Global Context File:
- Concatenation & UI Indication: The contents of all found context files are concatenated (with separators indicating their origin and path) and provided as part of the system prompt. The CLI footer displays the count of loaded context files, giving you a quick visual cue about the active instructional context.
- Importing Content: You can modularize your context files by importing other Markdown files using the
@path/to/file.mdsyntax. For more details, see the Memory Import Processor documentation. - Commands for Memory Management:
- Use
/memory refreshto force a re-scan and reload of all context files from all configured locations. This updates the AI's instructional context. - Use
/memory showto display the combined instructional context currently loaded, allowing you to verify the hierarchy and content being used by the AI. - See the Commands documentation for full details on the
/memorycommand and its sub-commands (showandrefresh).
- Use
By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor Qwen Code's responses to your specific needs and projects.
Sandbox
Qwen Code can execute potentially unsafe operations (like shell commands and file modifications) within a sandboxed environment to protect your system.
Sandbox is disabled by default, but you can enable it in a few ways:
- Using
--sandboxor-sflag. - Setting
QWEN_SANDBOXenvironment variable. - Setting
tools.sandboxin settings.
⚠️
--yolodoes not automatically enable a sandbox. YOLO mode only auto-approves tool calls; sandboxing must still be opted into via--sandbox,QWEN_SANDBOX, ortools.sandbox. In headless / non-interactive runs with--yolo(or--approval-mode=yolo) and no sandbox, the model can execute shell, write, and edit tools at the current process's privilege level — Qwen Code prints a warning to stderr in that case. Suppress withQWEN_CODE_SUPPRESS_YOLO_WARNING=1once you've reviewed the trade-off.
By default, it uses a pre-built qwen-code-sandbox Docker image.
For project-specific sandboxing needs, you can create a custom Dockerfile at .qwen/sandbox.Dockerfile in your project's root directory. This Dockerfile can be based on the base sandbox image:
FROM qwen-code-sandbox
# Add your custom dependencies or configurations here
# For example:
# RUN apt-get update && apt-get install -y some-package
# COPY ./my-config /app/my-config
When .qwen/sandbox.Dockerfile exists, you can use BUILD_SANDBOX environment variable when running Qwen Code to automatically build the custom sandbox image:
BUILD_SANDBOX=1 qwen -s
Usage Statistics
To help us improve Qwen Code, we collect anonymized usage statistics. This data helps us understand how the CLI is used, identify common issues, and prioritize new features.
What we collect:
- Tool Calls: We log the names of the tools that are called, whether they succeed or fail, and how long they take to execute. We do not collect the arguments passed to the tools or any data returned by them.
- API Requests: We log the model used for each request, the duration of the request, and whether it was successful. We do not collect the content of the prompts or responses.
- Session Information: We collect information about the configuration of the CLI, such as the enabled tools and the approval mode.
What we DON'T collect:
- Personally Identifiable Information (PII): We do not collect any personal information, such as your name, email address, or API keys.
- Prompt and Response Content: We do not log the content of your prompts or the responses from the model.
- File Content: We do not log the content of any files that are read or written by the CLI.
How to opt out:
You can opt out of usage statistics collection at any time by setting the usageStatisticsEnabled property to false under the privacy category in your settings.json file:
{
"privacy": {
"usageStatisticsEnabled": false
}
}
Note
When usage statistics are enabled, events are sent to an Alibaba Cloud RUM collection endpoint.