Merge branch 'main' into add-git-co-author

This commit is contained in:
tanzhenxin
2025-12-16 14:43:27 +08:00
129 changed files with 4822 additions and 4125 deletions

28
docs/users/_meta.ts Normal file
View File

@@ -0,0 +1,28 @@
export default {
'Getting started': {
type: 'separator',
title: 'Getting started', // Title is optional
},
overview: 'Overview',
quickstart: 'QuickStart',
'common-workflow': 'Command Workflows',
'Outside of the terminal': {
type: 'separator',
title: 'Outside of the terminal', // Title is optional
},
'integration-vscode': 'Visual Studio Code',
'integration-zed': 'Zed IDE',
'integration-github-action': 'Github Actions',
'Code with Qwen Code': {
type: 'separator',
title: 'Code with Qwen Code', // Title is optional
},
features: 'Features',
configuration: 'Configuration',
reference: 'Reference',
support: 'Support',
// need refine
'ide-integration': {
display: 'hidden',
},
};

View File

@@ -0,0 +1,571 @@
# Common workflows
> Learn about common workflows with Qwen Code.
Each task in this document includes clear instructions, example commands, and best practices to help you get the most from Qwen Code.
## Understand new codebases
### Get a quick codebase overview
Suppose you've just joined a new project and need to understand its structure quickly.
**1. Navigate to the project root directory**
```bash
cd /path/to/project
```
**2. Start Qwen Code**
```bash
qwen
```
**3. Ask for a high-level overview**
```
give me an overview of this codebase
```
**4. Dive deeper into specific components**
```
explain the main architecture patterns used here
```
```
what are the key data models?
```
```
how is authentication handled?
```
> [!tip]
>
> - Start with broad questions, then narrow down to specific areas
> - Ask about coding conventions and patterns used in the project
> - Request a glossary of project-specific terms
### Find relevant code
Suppose you need to locate code related to a specific feature or functionality.
**1. Ask Qwen Code to find relevant files**
```
find the files that handle user authentication
```
**2. Get context on how components interact**
```
how do these authentication files work together?
```
**3. Understand the execution flow**
```
trace the login process from front-end to database
```
> [!tip]
>
> - Be specific about what you're looking for
> - Use domain language from the project
## Fix bugs efficiently
Suppose you've encountered an error message and need to find and fix its source.
**1. Share the error with Qwen Code**
```
I'm seeing an error when I run npm test
```
**2. Ask for fix recommendations**
```
suggest a few ways to fix the @ts-ignore in user.ts
```
**3. Apply the fix**
```
update user.tsto add the null check you suggested
```
> [!tip]
>
> - Tell Qwen Code the command to reproduce the issue and get a stack trace
> - Mention any steps to reproduce the error
> - Let Qwen Code know if the error is intermittent or consistent
## Refactor code
Suppose you need to update old code to use modern patterns and practices.
**1. Identify legacy code for refactoring**
```
find deprecated API usage in our codebase
```
**2. Get refactoring recommendations**
```
suggest how to refactor utils.js to use modern JavaScript features
```
**3. Apply the changes safely**
```
refactor utils.js to use ES 2024 features while maintaining the same behavior
```
**4. Verify the refactoring**
```
run tests for the refactored code
```
> [!tip]
>
> - Ask Qwen Code to explain the benefits of the modern approach
> - Request that changes maintain backward compatibility when needed
> - Do refactoring in small, testable increments
## Use specialized subagents
Suppose you want to use specialized AI subagents to handle specific tasks more effectively.
**1. View available subagents**
```
/agents
```
This shows all available subagents and lets you create new ones.
**2. Use subagents automatically**
Qwen Code automatically delegates appropriate tasks to specialized subagents:
```
review my recent code changes for security issues
```
```
run all tests and fix any failures
```
**3. Explicitly request specific subagents**
```
use the code-reviewer subagent to check the auth module
```
```
have the debugger subagent investigate why users can't log in
```
**4. Create custom subagents for your workflow**
```
/agents
```
Then select "create" and follow the prompts to define:
- A unique identifier that describes the subagent's purpose (for example, `code-reviewer`, `api-designer`).
- When Qwen Code should use this agent
- Which tools it can access
- A system prompt describing the agent's role and behavior
> [!tip]
>
> - Create project-specific subagents in `.qwen/agents/` for team sharing
> - Use descriptive `description` fields to enable automatic delegation
> - Limit tool access to what each subagent actually needs
> - Know more about [Sub Agents](/users/features/sub-agents)
> - Know more about [Approval Mode](/users/features/approval-mode)
## Work with tests
Suppose you need to add tests for uncovered code.
**1. Identify untested code**
```
find functions in NotificationsService.swift that are not covered by tests
```
**2. Generate test scaffolding**
```
add tests for the notification service
```
**3. Add meaningful test cases**
```
add test cases for edge conditions in the notification service
```
**4. Run and verify tests**
```
run the new tests and fix any failures
```
Qwen Code can generate tests that follow your project's existing patterns and conventions. When asking for tests, be specific about what behavior you want to verify. Qwen Code examines your existing test files to match the style, frameworks, and assertion patterns already in use.
For comprehensive coverage, ask Qwen Code to identify edge cases you might have missed. Qwen Code can analyze your code paths and suggest tests for error conditions, boundary values, and unexpected inputs that are easy to overlook.
## Create pull requests
Suppose you need to create a well-documented pull request for your changes.
**1. Summarize your changes**
```
summarize the changes I've made to the authentication module
```
**2. Generate a pull request with Qwen Code**
```
create a pr
```
**3. Review and refine**
```
enhance the PR description with more context about the security improvements
```
**4. Add testing details**
```
add information about how these changes were tested
```
> [!tip]
>
> - Ask Qwen Code directly to make a PR for you
> - Review Qwen Code's generated PR before submitting
> - Ask Qwen Code to highlight potential risks or considerations
## Handle documentation
Suppose you need to add or update documentation for your code.
**1. Identify undocumented code**
```
find functions without proper JSDoc comments in the auth module
```
**2. Generate documentation**
```
add JSDoc comments to the undocumented functions in auth.js
```
**3. Review and enhance**
```
improve the generated documentation with more context and examples
```
**4. Verify documentation**
```
check if the documentation follows our project standards
```
> [!tip]
>
> - Specify the documentation style you want (JSDoc, docstrings, etc.)
> - Ask for examples in the documentation
> - Request documentation for public APIs, interfaces, and complex logic
## Reference files and directories
Use `@` to quickly include files or directories without waiting for Qwen Code to read them.
**1. Reference a single file**
```
Explain the logic in @src/utils/auth.js
```
This includes the full content of the file in the conversation.
**2. Reference a directory**
```
What's the structure of @src/components?
```
This provides a directory listing with file information.
**3. Reference MCP resources**
```
Show me the data from @github: repos/owner/repo/issues
```
This fetches data from connected MCP servers using the format @server: resource. See [MCP](/users/features/mcp) for details.
> [!tip]
>
> - File paths can be relative or absolute
> - @ file references add `QWEN.md` in the file's directory and parent directories to context
> - Directory references show file listings, not contents
> - You can reference multiple files in a single message (for example, "`@file 1.js` and `@file 2.js`")
## Resume previous conversations
Suppose you've been working on a task with Qwen Code and need to continue where you left off in a later session.
Qwen Code provides two options for resuming previous conversations:
- `--continue` to automatically continue the most recent conversation
- `--resume` to display a conversation picker
**1. Continue the most recent conversation**
```bash
qwen --continue
```
This immediately resumes your most recent conversation without any prompts.
**2. Continue in non-interactive mode**
```bash
qwen --continue --p "Continue with my task"
```
Use `--print` with `--continue` to resume the most recent conversation in non-interactive mode, perfect for scripts or automation.
**3. Show conversation picker**
```bash
qwen --resume
```
This displays an interactive conversation selector with a clean list view showing:
- Session summary (or initial prompt)
- Metadata: time elapsed, message count, and git branch
Use arrow keys to navigate and press Enter to select a conversation. Press Esc to exit.
> [!tip]
>
> - Conversation history is stored locally on your machine
> - Use `--continue` for quick access to your most recent conversation
> - Use `--resume` when you need to select a specific past conversation
> - When resuming, you'll see the entire conversation history before continuing
> - The resumed conversation starts with the same model and configuration as the original
>
> **How it works**:
>
> 1. **Conversation Storage**: All conversations are automatically saved locally with their full message history
> 2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context
> 3. **Tool State**: Tool usage and results from the previous conversation are preserved
> 4. **Context Restoration**: The conversation resumes with all previous context intact
>
> **Examples**:
>
> ```bash
> # Continue most recent conversation
> qwen --continue
>
> # Continue most recent conversation with a specific prompt
> qwen --continue --p "Show me our progress"
>
> # Show conversation picker
> qwen --resume
>
> # Continue most recent conversation in non-interactive mode
> qwen --continue --p "Run the tests again"
> ```
## Run parallel Qwen Code sessions with Git worktrees
Suppose you need to work on multiple tasks simultaneously with complete code isolation between Qwen Code instances.
**1. Understand Git worktrees**
Git worktrees allow you to check out multiple branches from the same repository into separate directories. Each worktree has its own working directory with isolated files, while sharing the same Git history. Learn more in the [official Git worktree documentation](https://git-scm.com/docs/git-worktree).
**2. Create a new worktree**
```bash
# Create a new worktree with a new branch
git worktree add ../project-feature-a -b feature-a
# Or create a worktree with an existing branch
git worktree add ../project-bugfix bugfix-123
```
This creates a new directory with a separate working copy of your repository.
**3. Run Qwen Code in each worktree**
```bash
# Navigate to your worktree
cd ../project-feature-a
# Run Qwen Code in this isolated environment
qwen
```
**4. Run Qwen Code in another worktree**
```bash
cd ../project-bugfix
qwen
```
**5. Manage your worktrees**
```bash
# List all worktrees
git worktree list
# Remove a worktree when done
git worktree remove ../project-feature-a
```
> [!tip]
>
> - Each worktree has its own independent file state, making it perfect for parallel Qwen Code sessions
> - Changes made in one worktree won't affect others, preventing Qwen Code instances from interfering with each other
> - All worktrees share the same Git history and remote connections
> - For long-running tasks, you can have Qwen Code working in one worktree while you continue development in another
> - Use descriptive directory names to easily identify which task each worktree is for
> - Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include:
> - JavaScript projects: Running dependency installation (`npm install`, `yarn`)
> - Python projects: Setting up virtual environments or installing with package managers
> - Other languages: Following your project's standard setup process
## Use Qwen Code as a unix-style utility
### Add Qwen Code to your verification process
Suppose you want to use Qwen Code as a linter or code reviewer.
**Add Qwen Code to your build script:**
```json
// package.json
{
...
"scripts": {
...
"lint:Qwen Code": "qwen -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'"
}
}
```
> [!tip]
>
> - Use Qwen Code for automated code review in your CI/CD pipeline
> - Customize the prompt to check for specific issues relevant to your project
> - Consider creating multiple scripts for different types of verification
### Pipe in, pipe out
Suppose you want to pipe data into Qwen Code, and get back data in a structured format.
**Pipe data through Qwen Code:**
```bash
cat build-error.txt | qwen -p 'concisely explain the root cause of this build error' > output.txt
```
> [!tip]
>
> - Use pipes to integrate Qwen-Code into existing shell scripts
> - Combine with other Unix tools for powerful workflows
> - Consider using --output-format for structured output
### Control output format
Suppose you need Qwen Code's output in a specific format, especially when integrating Qwen Code into scripts or other tools.
**1. Use text format (default)**
```bash
cat data.txt | qwen -p 'summarize this data' --output-format text > summary.txt
```
This outputs just Qwen Code's plain text response (default behavior).
**2. Use JSON format**
```bash
cat code.py | qwen -p 'analyze this code for bugs' --output-format json > analysis.json
```
This outputs a JSON array of messages with metadata including cost and duration.
**3. Use streaming JSON format**
```bash
cat log.txt | qwen -p 'parse this log file for errors' --output-format stream-json
```
This outputs a series of JSON objects in real-time as Qwen Code processes the request. Each message is a valid JSON object, but the entire output is not valid JSON if concatenated.
> [!tip]
>
> - Use `--output-format text` for simple integrations where you just need Qwen Code's response
> - Use `--output-format json` when you need the full conversation log
> - Use `--output-format stream-json` for real-time output of each conversation turn
## Ask Qwen Code about its capabilities
Qwen Code has built-in access to its documentation and can answer questions about its own features and limitations.
### Example questions
```
can Qwen Code create pull requests?
```
```
how does Qwen Code handle permissions?
```
```
what slash commands are available?
```
```
how do I use MCP with Qwen Code?
```
```
how do I configure Qwen Code for Amazon Bedrock?
```
```
what are the limitations of Qwen Code?
```
> [!note]
>
> Qwen Code provides documentation-based answers to these questions. For executable examples and hands-on demonstrations, refer to the specific workflow sections above.
> [!tip]
>
> - Qwen Code always has access to the latest Qwen Code documentation, regardless of the version you're using
> - Ask specific questions to get detailed answers
> - Qwen Code can explain complex features like MCP integration, enterprise configurations, and advanced workflows

View File

@@ -0,0 +1,10 @@
export default {
settings: 'Settings',
auth: 'Authentication',
memory: {
display: 'hidden',
},
'qwen-ignore': 'Ignoring Files',
'trusted-folders': 'Trusted Folders',
themes: 'Themes',
};

View File

@@ -0,0 +1,119 @@
# Authentication
Qwen Code supports two authentication methods. Pick the one that matches how you want to run the CLI:
- **Qwen OAuth (recommended)**: sign in with your `qwen.ai` account in a browser.
- **OpenAI-compatible API**: use an API key (OpenAI or any OpenAI-compatible provider / endpoint).
## Option 1: Qwen OAuth (recommended & free) 👍
Use this if you want the simplest setup and youre using Qwen models.
- **How it works**: on first start, Qwen Code opens a browser login page. After you finish, credentials are cached locally so you usually wont need to log in again.
- **Requirements**: a `qwen.ai` account + internet access (at least for the first login).
- **Benefits**: no API key management, automatic credential refresh.
- **Cost & quota**: free, with a quota of **60 requests/minute** and **2,000 requests/day**.
Start the CLI and follow the browser flow:
```bash
qwen
```
## Option 2: OpenAI-compatible API (API key)
Use this if you want to use OpenAI models or any provider that exposes an OpenAI-compatible API (e.g. OpenAI, Azure OpenAI, OpenRouter, ModelScope, Alibaba Cloud Bailian, or a self-hosted compatible endpoint).
### Quick start (interactive, recommended for local use)
When you choose the OpenAI-compatible option in the CLI, it will prompt you for:
- **API key**
- **Base URL** (default: `https://api.openai.com/v1`)
- **Model** (default: `gpt-4o`)
> **Note:** the CLI may display the key in plain text for verification. Make sure your terminal is not being recorded or shared.
### Configure via command-line arguments
```bash
# API key only
qwen-code --openai-api-key "your-api-key-here"
# Custom base URL (OpenAI-compatible endpoint)
qwen-code --openai-api-key "your-api-key-here" --openai-base-url "https://your-endpoint.com/v1"
# Custom model
qwen-code --openai-api-key "your-api-key-here" --model "gpt-4o-mini"
```
### Configure via environment variables
You can set these in your shell profile, CI, or an `.env` file:
```bash
export OPENAI_API_KEY="your-api-key-here"
export OPENAI_BASE_URL="https://api.openai.com/v1" # optional
export OPENAI_MODEL="gpt-4o" # optional
```
#### Persisting env vars with `.env` / `.qwen/.env`
Qwen Code will auto-load environment variables from the **first** `.env` file it finds (variables are **not merged** across multiple files).
Search order:
1. From the **current directory**, walking upward toward `/`:
1. `.qwen/.env`
2. `.env`
2. If nothing is found, it falls back to your **home directory**:
- `~/.qwen/.env`
- `~/.env`
`.qwen/.env` is recommended to keep Qwen Code variables isolated from other tools. Some variables (like `DEBUG` and `DEBUG_MODE`) are excluded from project `.env` files to avoid interfering with qwen-code behavior.
Examples:
```bash
# Project-specific settings (recommended)
mkdir -p .qwen
cat >> .qwen/.env <<'EOF'
OPENAI_API_KEY="your-api-key"
OPENAI_BASE_URL="https://api-inference.modelscope.cn/v1"
OPENAI_MODEL="Qwen/Qwen3-Coder-480B-A35B-Instruct"
EOF
```
```bash
# User-wide settings (available everywhere)
mkdir -p ~/.qwen
cat >> ~/.qwen/.env <<'EOF'
OPENAI_API_KEY="your-api-key"
OPENAI_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"
OPENAI_MODEL="qwen3-coder-plus"
EOF
```
## Switch authentication method (without restarting)
In the Qwen Code UI, run:
```bash
/auth
```
## Non-interactive / headless environments (CI, SSH, containers)
In a non-interactive terminal you typically **cannot** complete the OAuth browser login flow.
Use the OpenAI-compatible API method via environment variables:
- Set at least `OPENAI_API_KEY`.
- Optionally set `OPENAI_BASE_URL` and `OPENAI_MODEL`.
If none of these are set in a non-interactive session, Qwen Code will exit with an error.
## Security notes
- Dont commit API keys to version control.
- Prefer `.qwen/.env` for project-local secrets (and keep it out of git).
- Treat your terminal output as sensitive if it prints credentials for verification.

View File

View File

@@ -0,0 +1,55 @@
# Ignoring Files
This document provides an overview of the Qwen Ignore (`.qwenignore`) feature of Qwen Code.
Qwen Code includes the ability to automatically ignore files, similar to `.gitignore` (used by Git). Adding paths to your `.qwenignore` file will exclude them from tools that support this feature, although they will still be visible to other services (such as Git).
## How it works
When you add a path to your `.qwenignore` file, tools that respect this file will exclude matching files and directories from their operations. For example, when you use the [`read_many_files`](/developers/tools/multi-file) command, any paths in your `.qwenignore` file will be automatically excluded.
For the most part, `.qwenignore` follows the conventions of `.gitignore` files:
- Blank lines and lines starting with `#` are ignored.
- Standard glob patterns are supported (such as `*`, `?`, and `[]`).
- Putting a `/` at the end will only match directories.
- Putting a `/` at the beginning anchors the path relative to the `.qwenignore` file.
- `!` negates a pattern.
You can update your `.qwenignore` file at any time. To apply the changes, you must restart your Qwen Code session.
## How to use `.qwenignore`
| Step | Description |
| ---------------------- | -------------------------------------------------------------------------------------- |
| **Enable .qwenignore** | Create a file named `.qwenignore` in your project root directory |
| **Add ignore rules** | Open `.qwenignore` file and add paths to ignore, example: `/archive/` or `apikeys.txt` |
### `.qwenignore` examples
You can use `.qwenignore` to ignore directories and files:
```
# Exclude your /packages/ directory and all subdirectories
/packages/
# Exclude your apikeys.txt file
apikeys.txt
```
You can use wildcards in your `.qwenignore` file with `*`:
```
# Exclude all .md files
*.md
```
Finally, you can exclude files and directories from exclusion with `!`:
```
# Exclude all .md files except README.md
*.md
!README.md
```
To remove paths from your `.qwenignore` file, delete the relevant lines.

View File

@@ -0,0 +1,514 @@
# Qwen Code Configuration
> [!tip]
>
> **Authentication / API keys:** Authentication (Qwen OAuth vs OpenAI-compatible API) and auth-related environment variables (like `OPENAI_API_KEY`) are documented in **[Authentication](/users/configuration/auth)**.
> [!note]
>
> **Note on New Configuration Format**: The format of the `settings.json` file 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.json`<br>Windows: `C:\ProgramData\qwen-code\system-defaults.json`<br>macOS: `/Library/Application Support/QwenCode/system-defaults.json` <br>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` <br>Windows: `C:\ProgramData\qwen-code\settings.json` <br>macOS: `/Library/Application Support/QwenCode/settings.json`<br>The 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.json` files can reference environment variables using either `$VAR_NAME` or `${VAR_NAME}` syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variable `MY_API_TOKEN`, you could use it in `settings.json` like 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](/users/features/sandbox) (e.g. `.qwen/sandbox-macos-custom.sb`, `.qwen/sandbox.Dockerfile`).
### Available settings in `settings.json`
Settings are organized into categories. All settings should be placed within their corresponding top-level category object in your `settings.json` file.
#### general
| Setting | Type | Description | Default |
| ------------------------------- | ------- | ------------------------------------------ | ----------- |
| `general.preferredEditor` | string | The preferred editor to open files in. | `undefined` |
| `general.vimMode` | boolean | Enable Vim keybindings. | `false` |
| `general.disableAutoUpdate` | boolean | Disable automatic updates. | `false` |
| `general.disableUpdateNag` | boolean | Disable update notification prompts. | `false` |
| `general.checkpointing.enabled` | boolean | Enable session checkpointing for recovery. | `false` |
#### 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](/users/configuration/themes) for available options. | `undefined` |
| `ui.customThemes` | object | Custom theme definitions. | `{}` |
| `ui.hideWindowTitle` | boolean | Hide the window title bar. | `false` |
| `ui.hideTips` | boolean | Hide helpful tips in the UI. | `false` |
| `ui.hideBanner` | boolean | Hide the application banner. | `false` |
| `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.showCitations` | boolean | Show citations for generated text in the chat. | `true` |
| `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. This feature integrates with the `/summary` command and quit confirmation dialog. | `true` |
| `ui.accessibility.disableLoadingPhrases` | boolean | Disable loading phrases for accessibility. | `false` |
| `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. | `[]` |
#### 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.summarizeToolOutput` | object | Enables or disables the summarization of tool output. You can specify the token budget for the summarization using the `tokenBudget` setting. Note: Currently only the `run_shell_command` tool is supported. For example `{"run_shell_command": {"tokenBudget": 2000}}` | `undefined` |
| `model.generationConfig` | object | Advanced overrides passed to the underlying content generator. Supports request controls such as `timeout`, `maxRetries`, and `disableCacheControl`, 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 | Sets the threshold for chat history compression as a percentage of the model's total token limit. This is a value between 0 and 1 that applies to both automatic compression and the manual `/compress` command. For example, a value of `0.6` will trigger compression when the chat history exceeds 60% of the token limit. Use `0` to disable compression entirely. | `0.7` |
| `model.skipNextSpeakerCheck` | boolean | Skip the next speaker check. | `false` |
| `model.skipLoopDetection` | boolean | Disables loop detection checks. Loop detection prevents infinite loops in AI responses but can generate false positives that interrupt legitimate workflows. Enable this option if you experience frequent false positive loop detection interruptions. | `false` |
| `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,
"disableCacheControl": false,
"samplingParams": {
"temperature": 0.2,
"top_p": 0.8,
"max_tokens": 1024
}
}
}
}
```
**model.openAILoggingDir examples:**
- `"~/qwen-logs"` - Logs to `~/qwen-logs` directory
- `"./custom-logs"` - Logs to `./custom-logs` relative to current directory
- `"/tmp/openai-logs"` - Logs to absolute path `/tmp/openai-logs`
#### 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.discoveryMaxDirs` | number | Maximum number of directories to search for memory. | `200` |
| `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.disableFuzzySearch` | boolean | When `true`, disables the fuzzy search capabilities when searching for files, which can improve performance on projects with a large number of files. | `false` |
#### 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:
1. **Use `.qwenignore`:** Create a `.qwenignore` file 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.
2. **Disable Fuzzy Search:** If ignoring files is not enough, you can disable fuzzy search by setting `disableFuzzySearch` to `true` in your `settings.json` file. This will use a simpler, non-fuzzy matching algorithm, which can be faster.
3. **Disable Recursive File Search:** As a last resort, you can disable recursive file search entirely by setting `enableRecursiveFileSearch` to `false`. 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.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. | `false` | |
| `tools.core` | array of strings | This can be used to restrict the set of built-in tools with an allowlist. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"tools.core": ["run_shell_command(ls -l)"]` will only allow the `ls -l` command to be executed. | `undefined` | |
| `tools.exclude` | array of strings | Tool names to exclude from discovery. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"tools.exclude": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command. **Security Note:** Command-specific restrictions in `tools.exclude` for `run_shell_command` are based on simple string matching and can be easily bypassed. This feature is **not a security mechanism** and should not be relied upon to safely execute untrusted code. It is recommended to use `tools.core` to explicitly select commands that can be executed. | `undefined` | |
| `tools.allowed` | array of strings | A list of tool names that will bypass the confirmation dialog. This is useful for tools that you trust and use frequently. For example, `["run_shell_command(git)", "run_shell_command(npm test)"]` will skip the confirmation dialog to run any `git` and `npm test` commands. | `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](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `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.enableToolOutputTruncation` | boolean | Enable truncation of large tool outputs. | `true` | Requires restart: Yes |
| `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 |
| `tools.autoAccept` | boolean | Controls whether the CLI automatically accepts and executes tool calls that are considered safe (e.g., read-only operations) without explicit user confirmation. If set to `true`, the CLI will bypass the confirmation prompt for tools deemed safe. | `false` | |
#### git
| Setting | Type | Description | Default |
| ------------------------- | ------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `git.gitCoAuthor.enabled` | boolean | Automatically add a Co-authored-by trailer to git commit messages when commits are made through Qwen Code. | `true` |
| `git.gitCoAuthor.name` | string | The name to use in the Co-authored-by trailer. | `"Qwen-Coder"` |
| `git.gitCoAuthor.email` | string | The email to use in the Co-authored-by trailer. | `"qwen-coder@alibabacloud.com"` |
#### 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 `mcpServers` at 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.
#### 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` |
| `advanced.tavilyApiKey` | string | API key for Tavily web search service. Used to enable the `web_search` tool functionality. | `undefined` |
> [!note]
>
> **Note about advanced.tavilyApiKey:** This is a legacy configuration format. For Qwen OAuth users, DashScope provider is automatically available without any configuration. For other authentication types, configure Tavily or Google providers using the new `webSearch` configuration format.
#### 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](/developers/development/telemetry).
| Setting | Type | Description | Default |
| ------------------------ | ------- | -------------------------------------------------------------------------------- | ------- |
| `telemetry.enabled` | boolean | Whether or not telemetry is enabled. | |
| `telemetry.target` | string | The destination for collected telemetry. Supported values are `local` and `gcp`. | |
| `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.outfile` | string | The file to write telemetry to when `target` is `local`. | |
| `telemetry.useCollector` | boolean | Whether to use an external OTLP collector. | |
### Example `settings.json`
Here is an example of a `settings.json` file with the nested structure, new as of v0.3.0:
```
{
"general": {
"vimMode": true,
"preferredEditor": "code"
},
"ui": {
"theme": "GitHub",
"hideBanner": true,
"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",
"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
},
"privacy": {
"usageStatisticsEnabled": true
},
"model": {
"name": "qwen3-coder-plus",
"maxSessionTurns": 10,
"enableOpenAILogging": false,
"openAILoggingDir": "~/qwen-logs",
"summarizeToolOutput": {
"run_shell_command": {
"tokenBudget": 100
}
}
},
"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](/users/configuration/auth)**.
> [!tip]
>
> **Environment Variable Exclusion:** Some environment variables (like `DEBUG` and `DEBUG_MODE`) are automatically excluded from project `.env` files by default to prevent interference with the CLI behavior. Variables from `.qwen/.env` files are never excluded. You can customize this behavior using the `advanced.excludedEnvVars`setting in your `settings.json` file.
### Environment Variables Table
| Variable | Description | Notes |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GEMINI_TELEMETRY_ENABLED` | Set to `true` or `1` to enable telemetry. Any other value is treated as disabling it. | Overrides the `telemetry.enabled` setting. |
| `GEMINI_TELEMETRY_TARGET` | Sets the telemetry target (`local` or `gcp`). | Overrides the `telemetry.target` setting. |
| `GEMINI_TELEMETRY_OTLP_ENDPOINT` | Sets the OTLP endpoint for telemetry. | Overrides the `telemetry.otlpEndpoint` setting. |
| `GEMINI_TELEMETRY_OTLP_PROTOCOL` | Sets the OTLP protocol (`grpc` or `http`). | Overrides the `telemetry.otlpProtocol` setting. |
| `GEMINI_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. |
| `GEMINI_TELEMETRY_OUTFILE` | Sets the file path to write telemetry to when the target is `local`. | Overrides the `telemetry.outfile` setting. |
| `GEMINI_TELEMETRY_USE_COLLECTOR` | Set to `true` or `1` to enable or disable using an external OTLP collector. Any other value is treated as disabling it. | Overrides the `telemetry.useCollector` setting. |
| `GEMINI_SANDBOX` | Alternative to the `sandbox` setting in `settings.json`. | Accepts `true`, `false`, `docker`, `podman`, or a custom command string. |
| `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. | |
| `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. |
| `TAVILY_API_KEY` | Your API key for the Tavily web search service. | Used to enable the `web_search` tool functionality. Example: `export TAVILY_API_KEY="tvly-your-api-key-here"` |
## Command-Line Arguments
Arguments passed directly when running the CLI can override other configurations for that specific session.
### 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"` |
| `--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](/users/features/headless) 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](/users/features/headless) 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](/users/features/headless) 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) 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-edit`<br>See more about [Approval Mode](/users/features/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)"` |
| `--telemetry` | | Enables [telemetry](/developers/development/telemetry). | | |
| `--telemetry-target` | | Sets the telemetry target. | | See [telemetry](/developers/development/telemetry) for more information. |
| `--telemetry-otlp-endpoint` | | Sets the OTLP endpoint for telemetry. | | See [telemetry](/developers/development/telemetry) for more information. |
| `--telemetry-otlp-protocol` | | Sets the OTLP protocol for telemetry (`grpc` or `http`). | | Defaults to `grpc`. See [telemetry](/developers/development/telemetry) for more information. |
| `--telemetry-log-prompts` | | Enables logging of prompts for telemetry. | | See [telemetry](/developers/development/telemetry) for more information. |
| `--checkpointing` | | Enables [checkpointing](/users/features/checkpointing). | | |
| `--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` |
| `--tavily-api-key` | | Sets the Tavily API key for web search functionality for this session. | API key | Example: `qwen --tavily-api-key tvly-your-api-key-here` |
## 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 20+.
## 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 sophisticated 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 show` command. The typical loading order is:
1. **Global Context File:**
- Location: `~/.qwen/<configured-context-filename>` (e.g., `~/.qwen/QWEN.md` in your user home directory).
- Scope: Provides default instructions for all your projects.
2. **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 `.git` folder) or your home directory.
- Scope: Provides context relevant to the entire project or a significant portion of it.
3. **Sub-directory Context Files (Contextual/Local):**
- Location: The CLI also scans for the configured context file in subdirectories _below_ the current working directory (respecting common ignore patterns like `node_modules`, `.git`, etc.). The breadth of this search is limited to 200 directories by default, but can be configured with the `context.discoveryMaxDirs` setting in your `settings.json` file.
- Scope: Allows for highly specific instructions relevant to a particular component, module, or subsection of your project.
- **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.md` syntax. For more details, see the [Memory Import Processor documentation](/users/configuration/memory).
- **Commands for Memory Management:**
- Use `/memory refresh` to force a re-scan and reload of all context files from all configured locations. This updates the AI's instructional context.
- Use `/memory show` to display the combined instructional context currently loaded, allowing you to verify the hierarchy and content being used by the AI.
- See the [Commands documentation](/users/reference/cli-reference) for full details on the `/memory` command and its sub-commands (`show` and `refresh`).
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](/users/features/sandbox) is disabled by default, but you can enable it in a few ways:
- Using `--sandbox` or `-s` flag.
- Setting `GEMINI_SANDBOX` environment variable.
- Sandbox is enabled when using `--yolo` or `--approval-mode=yolo` by default.
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.

View File

@@ -0,0 +1,160 @@
# Themes
Qwen Code supports a variety of themes to customize its color scheme and appearance. You can change the theme to suit your preferences via the `/theme` command or `"theme":` configuration setting.
## Available Themes
Qwen Code comes with a selection of pre-defined themes, which you can list using the `/theme` command within the CLI:
- **Dark Themes:**
- `ANSI`
- `Atom One`
- `Ayu`
- `Default`
- `Dracula`
- `GitHub`
- **Light Themes:**
- `ANSI Light`
- `Ayu Light`
- `Default Light`
- `GitHub Light`
- `Google Code`
- `Xcode`
### Changing Themes
1. Enter `/theme` into Qwen Code.
2. A dialog or selection prompt appears, listing the available themes.
3. Using the arrow keys, select a theme. Some interfaces might offer a live preview or highlight as you select.
4. Confirm your selection to apply the theme.
**Note:** If a theme is defined in your `settings.json` file (either by name or by a file path), you must remove the `"theme"` setting from the file before you can change the theme using the `/theme` command.
### Theme Persistence
Selected themes are saved in Qwen Code's [configuration](./configuration.md) so your preference is remembered across sessions.
---
## Custom Color Themes
Qwen Code allows you to create your own custom color themes by specifying them in your `settings.json` file. This gives you full control over the color palette used in the CLI.
### How to Define a Custom Theme
Add a `customThemes` block to your user, project, or system `settings.json` file. Each custom theme is defined as an object with a unique name and a set of color keys. For example:
```json
{
"ui": {
"customThemes": {
"MyCustomTheme": {
"name": "MyCustomTheme",
"type": "custom",
"Background": "#181818",
...
}
}
}
}
```
**Color keys:**
- `Background`
- `Foreground`
- `LightBlue`
- `AccentBlue`
- `AccentPurple`
- `AccentCyan`
- `AccentGreen`
- `AccentYellow`
- `AccentRed`
- `Comment`
- `Gray`
- `DiffAdded` (optional, for added lines in diffs)
- `DiffRemoved` (optional, for removed lines in diffs)
- `DiffModified` (optional, for modified lines in diffs)
**Required Properties:**
- `name` (must match the key in the `customThemes` object and be a string)
- `type` (must be the string `"custom"`)
- `Background`
- `Foreground`
- `LightBlue`
- `AccentBlue`
- `AccentPurple`
- `AccentCyan`
- `AccentGreen`
- `AccentYellow`
- `AccentRed`
- `Comment`
- `Gray`
You can use either hex codes (e.g., `#FF0000`) **or** standard CSS color names (e.g., `coral`, `teal`, `blue`) for any color value. See [CSS color names](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords) for a full list of supported names.
You can define multiple custom themes by adding more entries to the `customThemes` object.
### Loading Themes from a File
In addition to defining custom themes in `settings.json`, you can also load a theme directly from a JSON file by specifying the file path in your `settings.json`. This is useful for sharing themes or keeping them separate from your main configuration.
To load a theme from a file, set the `theme` property in your `settings.json` to the path of your theme file:
```json
{
"ui": {
"theme": "/path/to/your/theme.json"
}
}
```
The theme file must be a valid JSON file that follows the same structure as a custom theme defined in `settings.json`.
**Example `my-theme.json`:**
```json
{
"name": "My File Theme",
"type": "custom",
"Background": "#282A36",
"Foreground": "#F8F8F2",
"LightBlue": "#82AAFF",
"AccentBlue": "#61AFEF",
"AccentPurple": "#BD93F9",
"AccentCyan": "#8BE9FD",
"AccentGreen": "#50FA7B",
"AccentYellow": "#F1FA8C",
"AccentRed": "#FF5555",
"Comment": "#6272A4",
"Gray": "#ABB2BF",
"DiffAdded": "#A6E3A1",
"DiffRemoved": "#F38BA8",
"DiffModified": "#89B4FA",
"GradientColors": ["#4796E4", "#847ACE", "#C3677F"]
}
```
**Security Note:** For your safety, Gemini CLI will only load theme files that are located within your home directory. If you attempt to load a theme from outside your home directory, a warning will be displayed and the theme will not be loaded. This is to prevent loading potentially malicious theme files from untrusted sources.
### Example Custom Theme
<img src="https://gw.alicdn.com/imgextra/i1/O1CN01Em30Hc1jYXAdIgls3_!!6000000004560-2-tps-1009-629.png" alt=" " style="zoom:100%;text-align:center;margin: 0 auto;" />
### Using Your Custom Theme
- Select your custom theme using the `/theme` command in Qwen Code. Your custom theme will appear in the theme selection dialog.
- Or, set it as the default by adding `"theme": "MyCustomTheme"` to the `ui` object in your `settings.json`.
- Custom themes can be set at the user, project, or system level, and follow the same [configuration precedence](./configuration.md) as other settings.
## Themes Preview
| Dark Theme | Preview | Light Theme | Preview |
| :----------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| ANSI | <img src="https://gw.alicdn.com/imgextra/i2/O1CN01ZInJiq1GdSZc9gHsI_!!6000000000645-2-tps-1140-934.png" style="zoom:30%;text-align:center;margin: 0 auto;" /> | ANSI Light | <img src="https://gw.alicdn.com/imgextra/i2/O1CN01IiJQFC1h9E3MXQj6W_!!6000000004234-2-tps-1140-934.png" style="zoom:30%;text-align:center;margin: 0 auto;" /> |
| Atom OneDark | <img src="https://gw.alicdn.com/imgextra/i2/O1CN01Zlx1SO1Sw21SkTKV3_!!6000000002310-2-tps-1140-934.png" style="zoom:30%;text-align:center;margin: 0 auto;" /> | Ayu Light | <img src="https://gw.alicdn.com/imgextra/i3/O1CN01zEUc1V1jeUJsnCgQb_!!6000000004573-2-tps-1140-934.png" alt=" " style="zoom:30%;text-align:center;margin: 0 auto;" /> |
| Ayu | <img src="https://gw.alicdn.com/imgextra/i3/O1CN019upo6v1SmPhmRjzfN_!!6000000002289-2-tps-1140-934.png" alt=" " style="zoom:30%;text-align:center;margin: 0 auto;" /> | Default Light | <img src="https://gw.alicdn.com/imgextra/i4/O1CN01RHjrEs1u7TXq3M6l3_!!6000000005990-2-tps-1140-934.png" alt=" " style="zoom:30%;text-align:center;margin: 0 auto;" /> |
| Default | <img src="https://gw.alicdn.com/imgextra/i4/O1CN016pIeXz1pFC8owmR4Q_!!6000000005330-2-tps-1140-934.png" style="zoom:30%;text-align:center;margin: 0 auto;" /> | GitHub Light | <img src="https://gw.alicdn.com/imgextra/i4/O1CN01US2b0g1VETCPAVWLA_!!6000000002621-2-tps-1140-934.png" alt=" " style="zoom:30%;text-align:center;margin: 0 auto;" /> |
| Dracula | <img src="https://gw.alicdn.com/imgextra/i4/O1CN016htnWH20c3gd2LpUR_!!6000000006869-2-tps-1140-934.png" style="zoom:30%;text-align:center;margin: 0 auto;" /> | Google Code | <img src="https://gw.alicdn.com/imgextra/i1/O1CN01Ng29ab23iQ2BuYKz8_!!6000000007289-2-tps-1140-934.png" alt=" " style="zoom:30%;text-align:center;margin: 0 auto;" /> |
| GitHub | <img src="https://gw.alicdn.com/imgextra/i4/O1CN01fFCRda1IQIQ9qDNqv_!!6000000000887-2-tps-1140-934.png" alt=" " style="zoom:30%;text-align:center;margin: 0 auto;" /> | Xcode | <img src="https://gw.alicdn.com/imgextra/i1/O1CN010E3QAi1Huh5o1E9LN_!!6000000000818-2-tps-1140-934.png" alt=" " style="zoom:30%;text-align:center;margin: 0 auto;" /> |

View File

@@ -0,0 +1,61 @@
# Trusted Folders
The Trusted Folders feature is a security setting that gives you control over which projects can use the full capabilities of the Qwen Code. It prevents potentially malicious code from running by asking you to approve a folder before the CLI loads any project-specific configurations from it.
## Enabling the Feature
The Trusted Folders feature is **disabled by default**. To use it, you must first enable it in your settings.
Add the following to your user `settings.json` file:
```json
{
"security": {
"folderTrust": {
"enabled": true
}
}
}
```
## How It Works: The Trust Dialog
Once the feature is enabled, the first time you run the Qwen Code from a folder, a dialog will automatically appear, prompting you to make a choice:
- **Trust folder**: Grants full trust to the current folder (e.g. `my-project`).
- **Trust parent folder**: Grants trust to the parent directory (e.g. `safe-projects`), which automatically trusts all of its subdirectories as well. This is useful if you keep all your safe projects in one place.
- **Don't trust**: Marks the folder as untrusted. The CLI will operate in a restricted "safe mode."
Your choice is saved in a central file (`~/.qwen/trustedFolders.json`), so you will only be asked once per folder.
## Why Trust Matters: The Impact of an Untrusted Workspace
When a folder is **untrusted**, the Qwen Code runs in a restricted "safe mode" to protect you. In this mode, the following features are disabled:
1. **Workspace Settings are Ignored**: The CLI will **not** load the `.qwen/settings.json` file from the project. This prevents the loading of custom tools and other potentially dangerous configurations.
2. **Environment Variables are Ignored**: The CLI will **not** load any `.env` files from the project.
3. **Extension Management is Restricted**: You **cannot install, update, or uninstall** extensions.
4. **Tool Auto-Acceptance is Disabled**: You will always be prompted before any tool is run, even if you have auto-acceptance enabled globally.
5. **Automatic Memory Loading is Disabled**: The CLI will not automatically load files into context from directories specified in local settings.
Granting trust to a folder unlocks the full functionality of the Qwen Code for that workspace.
## Managing Your Trust Settings
If you need to change a decision or see all your settings, you have a couple of options:
- **Change the Current Folder's Trust**: Run the `/permissions` command from within the CLI. This will bring up the same interactive dialog, allowing you to change the trust level for the current folder.
- **View All Trust Rules**: To see a complete list of all your trusted and untrusted folder rules, you can inspect the contents of the `~/.qwen/trustedFolders.json` file in your home directory.
## The Trust Check Process (Advanced)
For advanced users, it's helpful to know the exact order of operations for how trust is determined:
1. **IDE Trust Signal**: If you are using the [IDE Integration](/users/ide-integration/ide-integration), the CLI first asks the IDE if the workspace is trusted. The IDE's response takes highest priority.
2. **Local Trust File**: If the IDE is not connected, the CLI checks the central `~/.qwen/trustedFolders.json` file.

View File

@@ -0,0 +1,12 @@
export default {
commands: 'Commands',
'sub-agents': 'SubAgents',
headless: 'Headless Mode',
checkpointing: {
display: 'hidden',
},
'approval-mode': 'Approval Mode',
mcp: 'MCP',
'token-caching': 'Token Caching',
sandbox: 'Sandboxing',
};

View File

@@ -0,0 +1,261 @@
Qwen Code offers three distinct permission modes that allow you to flexibly control how AI interacts with your code and system based on task complexity and risk level.
## Permission Modes Comparison
| Mode | File Editing | Shell Commands | Best For | Risk Level |
| -------------- | --------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------ | ---------- |
| **Plan** | ❌ Read-only analysis only | ❌ Not executed | • Code exploration <br>• Planning complex changes <br>• Safe code review | Lowest |
| **Default** | ✅ Manual approval required | ✅ Manual approval required | • New/unfamiliar codebases <br>• Critical systems <br>• Team collaboration <br>• Learning and teaching | Low |
| **Auto-Edit** | ✅ Auto-approved | ❌ Manual approval required | • Daily development tasks <br>• Refactoring and code improvements <br>• Safe automation | Medium |
| **YOLO** | ✅ Auto-approved | ✅ Auto-approved | • Trusted personal projects <br>• Automated scripts/CI/CD <br>• Batch processing tasks | Highest |
### Quick Reference Guide
- **Start in Plan Mode**: Great for understanding before making changes
- **Work in Default Mode**: The balanced choice for most development work
- **Switch to Auto-Edit**: When you're making lots of safe code changes
- **Use YOLO sparingly**: Only for trusted automation in controlled environments
> [!tip]
>
> You can quickly cycle through modes during a session using **Shift+Tab**. The terminal status bar shows your current mode, so you always know what permissions Qwen Code has.
## 1. Use Plan Mode for safe code analysis
Plan Mode instructs Qwen Code to create a plan by analyzing the codebase with **read-only** operations, perfect for exploring codebases, planning complex changes, or reviewing code safely.
### When to use Plan Mode
- **Multi-step implementation**: When your feature requires making edits to many files
- **Code exploration**: When you want to research the codebase thoroughly before changing anything
- **Interactive development**: When you want to iterate on the direction with Qwen Code
### How to use Plan Mode
**Turn on Plan Mode during a session**
You can switch into Plan Mode during a session using **Shift+Tab** to cycle through permission modes.
If you are in Normal Mode, **Shift+Tab** first switches into `auto-edits` Mode, indicated by `⏵⏵ accept edits on` at the bottom of the terminal. A subsequent **Shift+Tab** will switch into Plan Mode, indicated by `⏸ plan mode`.
**Start a new session in Plan Mode**
To start a new session in Plan Mode, use the `/approval-mode` then select `plan`
```bash
/approval-mode
```
**Run "headless" queries in Plan Mode**
You can also run a query in Plan Mode directly with `-p` or `prompt`:
```bash
qwen --prompt "What is machine learning?"
```
### Example: Planning a complex refactor
```bash
/approval-mode plan
```
```
I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.
```
Qwen Code analyzes the current implementation and create a comprehensive plan. Refine with follow-ups:
```
What about backward compatibility?
How should we handle database migration?
```
### Configure Plan Mode as default
```json
// .qwen/settings.json
{
"permissions": {
"defaultMode": "plan"
}
}
```
## 2. Use Default Mode for Controlled Interaction
Default Mode is the standard way to work with Qwen Code. In this mode, you maintain full control over all potentially risky operations - Qwen Code will ask for your approval before making any file changes or executing shell commands.
### When to use Default Mode
- **New to a codebase**: When you're exploring an unfamiliar project and want to be extra cautious
- **Critical systems**: When working on production code, infrastructure, or sensitive data
- **Learning and teaching**: When you want to understand each step Qwen Code is taking
- **Team collaboration**: When multiple people are working on the same codebase
- **Complex operations**: When the changes involve multiple files or complex logic
### How to use Default Mode
**Turn on Default Mode during a session**
You can switch into Default Mode during a session using **Shift+Tab** to cycle through permission modes. If you're in any other mode, pressing **Shift+Tab** will eventually cycle back to Default Mode, indicated by the absence of any mode indicator at the bottom of the terminal.
**Start a new session in Default Mode**
Default Mode is the initial mode when you start Qwen Code. If you've changed modes and want to return to Default Mode, use:
```
/approval-mode default
```
**Run "headless" queries in Default Mode**
When running headless commands, Default Mode is the default behavior. You can explicitly specify it with:
```
qwen --prompt "Analyze this code for potential bugs"
```
### Example: Safely implementing a feature
```
/approval-mode default
```
```
I need to add user profile pictures to our application. The pictures should be stored in an S3 bucket and the URLs saved in the database.
```
Qwen Code will analyze your codebase and propose a plan. It will then ask for approval before:
1. Creating new files (controllers, models, migrations)
2. Modifying existing files (adding new columns, updating APIs)
3. Running any shell commands (database migrations, dependency installation)
You can review each proposed change and approve or reject it individually.
### Configure Default Mode as default
```bash
// .qwen/settings.json
{
"permissions": {
"defaultMode": "default"
}
}
```
## 3. Auto Edits Mode
Auto-Edit Mode instructs Qwen Code to automatically approve file edits while requiring manual approval for shell commands, ideal for accelerating development workflows while maintaining system safety.
### When to use Auto-Accept Edits Mode
- **Daily development**: Ideal for most coding tasks
- **Safe automation**: Allows AI to modify code while preventing accidental execution of dangerous commands
- **Team collaboration**: Use in shared projects to avoid unintended impacts on others
### How to switch to this mode
```
# Switch via command
/approval-mode auto-edit
# Or use keyboard shortcut
Shift+Tab # Switch from other modes
```
### Workflow Example
1. You ask Qwen Code to refactor a function
2. AI analyzes the code and proposes changes
3. **Automatically** applies all file changes without confirmation
4. If tests need to be run, it will **request approval** to execute `npm test`
## 4. YOLO Mode - Full Automation
YOLO Mode grants Qwen Code the highest permissions, automatically approving all tool calls including file editing and shell commands.
### When to use YOLO Mode
- **Automated scripts**: Running predefined automated tasks
- **CI/CD pipelines**: Automated execution in controlled environments
- **Personal projects**: Rapid iteration in fully trusted environments
- **Batch processing**: Tasks requiring multi-step command chains
> [!warning]
>
> **Use YOLO Mode with caution**: AI can execute any command with your terminal permissions. Ensure:
>
> 1. You trust the current codebase
> 2. You understand all actions AI will perform
> 3. Important files are backed up or committed to version control
### How to enable YOLO Mode
```
# Temporarily enable (current session only)
/approval-mode yolo
# Set as project default
/approval-mode yolo --project
# Set as user global default
/approval-mode yolo --user
```
### Configuration Example
```bash
// .qwen/settings.json
{
"permissions": {
"defaultMode": "yolo",
"confirmShellCommands": false,
"confirmFileEdits": false
}
}
```
### Automated Workflow Example
```bash
# Fully automated refactoring task
qwen --prompt "Run the test suite, fix all failing tests, then commit changes"
# Without human intervention, AI will:
# 1. Run test commands (auto-approved)
# 2. Fix failed test cases (auto-edit files)
# 3. Execute git commit (auto-approved)
```
## Mode Switching & Configuration
### Keyboard Shortcut Switching
During a Qwen Code session, use **Shift+Tab** to quickly cycle through the three modes:
```
Default Mode → Auto-Edit Mode → YOLO Mode → Plan Mode → Default Mode
```
### Persistent Configuration
```
// Project-level: ./.qwen/settings.json
// User-level: ~/.qwen/settings.json
{
"permissions": {
"defaultMode": "auto-edit", // or "plan" or "yolo"
"confirmShellCommands": true,
"confirmFileEdits": true
}
}
```
### Mode Usage Recommendations
1. **New to codebase**: Start with **Plan Mode** for safe exploration
2. **Daily development tasks**: Use **Auto-Accept Edits** (default mode), efficient and safe
3. **Automated scripts**: Use **YOLO Mode** in controlled environments for full automation
4. **Complex refactoring**: Use **Plan Mode** first for detailed planning, then switch to appropriate mode for execution

View File

@@ -0,0 +1,77 @@
# Checkpointing
Qwen Code includes a Checkpointing feature that automatically saves a snapshot of your project's state before any file modifications are made by AI-powered tools. This allows you to safely experiment with and apply code changes, knowing you can instantly revert back to the state before the tool was run.
## How It Works
When you approve a tool that modifies the file system (like `write_file` or `edit`), the CLI automatically creates a "checkpoint." This checkpoint includes:
1. **A Git Snapshot:** A commit is made in a special, shadow Git repository located in your home directory (`~/.qwen/history/<project_hash>`). This snapshot captures the complete state of your project files at that moment. It does **not** interfere with your own project's Git repository.
2. **Conversation History:** The entire conversation you've had with the agent up to that point is saved.
3. **The Tool Call:** The specific tool call that was about to be executed is also stored.
If you want to undo the change or simply go back, you can use the `/restore` command. Restoring a checkpoint will:
- Revert all files in your project to the state captured in the snapshot.
- Restore the conversation history in the CLI.
- Re-propose the original tool call, allowing you to run it again, modify it, or simply ignore it.
All checkpoint data, including the Git snapshot and conversation history, is stored locally on your machine. The Git snapshot is stored in the shadow repository while the conversation history and tool calls are saved in a JSON file in your project's temporary directory, typically located at `~/.qwen/tmp/<project_hash>/checkpoints`.
## Enabling the Feature
The Checkpointing feature is disabled by default. To enable it, you can either use a command-line flag or edit your `settings.json` file.
### Using the Command-Line Flag
You can enable checkpointing for the current session by using the `--checkpointing` flag when starting Qwen Code:
```bash
qwen --checkpointing
```
### Using the `settings.json` File
To enable checkpointing by default for all sessions, you need to edit your `settings.json` file.
Add the following key to your `settings.json`:
```json
{
"general": {
"checkpointing": {
"enabled": true
}
}
}
```
## Using the `/restore` Command
Once enabled, checkpoints are created automatically. To manage them, you use the `/restore` command.
### List Available Checkpoints
To see a list of all saved checkpoints for the current project, simply run:
```
/restore
```
The CLI will display a list of available checkpoint files. These file names are typically composed of a timestamp, the name of the file being modified, and the name of the tool that was about to be run (e.g., `2025-06-22T10-00-00_000Z-my-file.txt-write_file`).
### Restore a Specific Checkpoint
To restore your project to a specific checkpoint, use the checkpoint file from the list:
```
/restore <checkpoint_file>
```
For example:
```
/restore 2025-06-22T10-00-00_000Z-my-file.txt-write_file
```
After running the command, your files and conversation will be immediately restored to the state they were in when the checkpoint was created, and the original tool prompt will reappear.

View File

@@ -0,0 +1,264 @@
# Commands
This document details all commands supported by Qwen Code, helping you efficiently manage sessions, customize the interface, and control its behavior.
Qwen Code commands are triggered through specific prefixes and fall into three categories:
| Prefix Type | Function Description | Typical Use Case |
| -------------------------- | --------------------------------------------------- | ---------------------------------------------------------------- |
| Slash Commands (`/`) | Meta-level control of Qwen Code itself | Managing sessions, modifying settings, getting help |
| At Commands (`@`) | Quickly inject local file content into conversation | Allowing AI to analyze specified files or code under directories |
| Exclamation Commands (`!`) | Direct interaction with system Shell | Executing system commands like `git status`, `ls`, etc. |
## 1. Slash Commands (`/`)
Slash commands are used to manage Qwen Code sessions, interface, and basic behavior.
### 1.1 Session and Project Management
These commands help you save, restore, and summarize work progress.
| Command | Description | Usage Examples |
| ----------- | --------------------------------------------------------- | ------------------------------------ |
| `/summary` | Generate project summary based on conversation history | `/summary` |
| `/compress` | Replace chat history with summary to save Tokens | `/compress` |
| `/restore` | Restore files to state before tool execution | `/restore` (list) or `/restore <ID>` |
| `/init` | Analyze current directory and create initial context file | `/init` |
### 1.2 Interface and Workspace Control
Commands for adjusting interface appearance and work environment.
| Command | Description | Usage Examples |
| ------------ | ---------------------------------------- | ----------------------------- |
| `/clear` | Clear terminal screen content | `/clear` (shortcut: `Ctrl+L`) |
| `/theme` | Change Qwen Code visual theme | `/theme` |
| `/vim` | Turn input area Vim editing mode on/off | `/vim` |
| `/directory` | Manage multi-directory support workspace | `/dir add ./src,./tests` |
| `/editor` | Open dialog to select supported editor | `/editor` |
### 1.3 Language Settings
Commands specifically for controlling interface and output language.
| Command | Description | Usage Examples |
| --------------------- | -------------------------------- | -------------------------- |
| `/language` | View or change language settings | `/language` |
| → `ui [language]` | Set UI interface language | `/language ui zh-CN` |
| → `output [language]` | Set LLM output language | `/language output Chinese` |
- Available UI languages: `zh-CN` (Simplified Chinese), `en-US` (English)
- Output language examples: `Chinese`, `English`, `Japanese`, etc.
### 1.4 Tool and Model Management
Commands for managing AI tools and models.
| Command | Description | Usage Examples |
| ---------------- | --------------------------------------------- | --------------------------------------------- |
| `/mcp` | List configured MCP servers and tools | `/mcp`, `/mcp desc` |
| `/tools` | Display currently available tool list | `/tools`, `/tools desc` |
| `/approval-mode` | Change approval mode for tool usage | `/approval-mode <mode (auto-edit)> --project` |
| →`plan` | Analysis only, no execution | Secure review |
| →`default` | Require approval for edits | Daily use |
| →`auto-edit` | Automatically approve edits | Trusted environment |
| →`yolo` | Automatically approve all | Quick prototyping |
| `/model` | Switch model used in current session | `/model` |
| `/extensions` | List all active extensions in current session | `/extensions` |
| `/memory` | Manage AI's instruction context | `/memory add Important Info` |
### 1.5 Information, Settings, and Help
Commands for obtaining information and performing system settings.
| Command | Description | Usage Examples |
| --------------- | ----------------------------------------------- | ------------------------------------------------ |
| `/help` | Display help information for available commands | `/help` or `/?` |
| `/about` | Display version information | `/about` |
| `/stats` | Display detailed statistics for current session | `/stats` |
| `/settings` | Open settings editor | `/settings` |
| `/auth` | Change authentication method | `/auth` |
| `/bug` | Submit issue about Qwen Code | `/bug Button click unresponsive` |
| `/copy` | Copy last output content to clipboard | `/copy` |
| `/quit-confirm` | Show confirmation dialog before quitting | `/quit-confirm` (shortcut: press `Ctrl+C` twice) |
| `/quit` | Exit Qwen Code immediately | `/quit` or `/exit` |
### 1.6 Common Shortcuts
| Shortcut | Function | Note |
| ------------------ | ----------------------- | ---------------------- |
| `Ctrl/cmd+L` | Clear screen | Equivalent to `/clear` |
| `Ctrl/cmd+T` | Toggle tool description | MCP tool management |
| `Ctrl/cmd+C`×2 | Exit confirmation | Secure exit mechanism |
| `Ctrl/cmd+Z` | Undo input | Text editing |
| `Ctrl/cmd+Shift+Z` | Redo input | Text editing |
## 2. @ Commands (Introducing Files)
@ commands are used to quickly add local file or directory content to the conversation.
| Command Format | Description | Examples |
| ------------------- | -------------------------------------------- | ------------------------------------------------ |
| `@<file path>` | Inject content of specified file | `@src/main.py Please explain this code` |
| `@<directory path>` | Recursively read all text files in directory | `@docs/ Summarize content of this document` |
| Standalone `@` | Used when discussing `@` symbol itself | `@ What is this symbol used for in programming?` |
Note: Spaces in paths need to be escaped with backslash (e.g., `@My\ Documents/file.txt`)
## 3. Exclamation Commands (`!`) - Shell Command Execution
Exclamation commands allow you to execute system commands directly within Qwen Code.
| Command Format | Description | Examples |
| ------------------ | ------------------------------------------------------------------ | -------------------------------------- |
| `!<shell command>` | Execute command in sub-Shell | `!ls -la`, `!git status` |
| Standalone `!` | Switch Shell mode, any input is executed directly as Shell command | `!`(enter) → Input command → `!`(exit) |
Environment Variables: Commands executed via `!` will set the `QWEN_CODE=1` environment variable.
## 4. Custom Commands
Save frequently used prompts as shortcut commands to improve work efficiency and ensure consistency.
### Quick Overview
| Function | Description | Advantages | Priority | Applicable Scenarios |
| ---------------- | ------------------------------------------ | -------------------------------------- | -------- | ---------------------------------------------------- |
| Namespace | Subdirectory creates colon-named commands | Better command organization | | |
| Global Commands | `~/.qwen/commands/` | Available in all projects | Low | Personal frequently used commands, cross-project use |
| Project Commands | `<project root directory>/.qwen/commands/` | Project-specific, version-controllable | High | Team sharing, project-specific commands |
Priority Rules: Project commands > User commands (project command used when names are same)
### Command Naming Rules
#### File Path to Command Name Mapping Table
| File Location | Generated Command | Example Call |
| ---------------------------- | ----------------- | --------------------- |
| `~/.qwen/commands/test.toml` | `/test` | `/test Parameter` |
| `<project>/git/commit.toml` | `/git:commit` | `/git:commit Message` |
Naming Rules: Path separator (`/` or `\`) converted to colon (`:`)
### TOML File Format Specification
| Field | Required | Description | Example |
| ------------- | -------- | ---------------------------------------- | ------------------------------------------ |
| `prompt` | Required | Prompt content sent to model | `prompt = "Please analyze code: {{args}}"` |
| `description` | Optional | Command description (displayed in /help) | `description = "Code analysis tool"` |
### Parameter Processing Mechanism
| Processing Method | Syntax | Applicable Scenarios | Security Features |
| ---------------------------- | ------------------ | ------------------------------------ | -------------------------------------- |
| Context-aware Injection | `{{args}}` | Need precise parameter control | Automatic Shell escaping |
| Default Parameter Processing | No special marking | Simple commands, parameter appending | Append as-is |
| Shell Command Injection | `!{command}` | Need dynamic content | Execution confirmation required before |
#### 1. Context-aware Injection (`{{args}}`)
| Scenario | TOML Configuration | Call Method | Actual Effect |
| ---------------- | --------------------------------------- | --------------------- | ------------------------ |
| Raw Injection | `prompt = "Fix: {{args}}"` | `/fix "Button issue"` | `Fix: "Button issue"` |
| In Shell Command | `prompt = "Search: !{grep {{args}} .}"` | `/search "hello"` | Execute `grep "hello" .` |
#### 2. Default Parameter Processing
| Input Situation | Processing Method | Example |
| --------------- | ------------------------------------------------------ | ---------------------------------------------- |
| Has parameters | Append to end of prompt (separated by two line breaks) | `/cmd parameter` → Original prompt + parameter |
| No parameters | Send prompt as is | `/cmd` → Original prompt |
🚀 Dynamic Content Injection
| Injection Type | Syntax | Processing Order | Purpose |
| --------------------- | -------------- | ------------------- | -------------------------------- |
| File Content | `@{file path}` | Processed first | Inject static reference files |
| Shell Commands | `!{command}` | Processed in middle | Inject dynamic execution results |
| Parameter Replacement | `{{args}}` | Processed last | Inject user parameters |
#### 3. Shell Command Execution (`!{...}`)
| Operation | User Interaction |
| ------------------------------- | -------------------- |
| 1. Parse command and parameters | - |
| 2. Automatic Shell escaping | - |
| 3. Show confirmation dialog | ✅ User confirmation |
| 4. Execute command | - |
| 5. Inject output to prompt | - |
Example: Git Commit Message Generation
```
# git/commit.toml
description = "Generate Commit message based on staged changes"
prompt = """
Please generate a Commit message based on the following diff:
diff
!{git diff --staged}
"""
```
#### 4. File Content Injection (`@{...}`)
| File Type | Support Status | Processing Method |
| ------------ | ---------------------- | --------------------------- |
| Text Files | ✅ Full Support | Directly inject content |
| Images/PDF | ✅ Multi-modal Support | Encode and inject |
| Binary Files | ⚠️ Limited Support | May be skipped or truncated |
| Directory | ✅ Recursive Injection | Follow .gitignore rules |
Example: Code Review Command
```
# review.toml
description = "Code review based on best practices"
prompt = """
Review {{args}}, reference standards:
@{docs/code-standards.md}
"""
```
### Practical Creation Example
#### "Pure Function Refactoring" Command Creation Steps Table
| Operation | Command/Code |
| ----------------------------- | ------------------------------------------- |
| 1. Create directory structure | `mkdir -p ~/.qwen/commands/refactor` |
| 2. Create command file | `touch ~/.qwen/commands/refactor/pure.toml` |
| 3. Edit command content | Refer to the complete code below. |
| 4. Test command | `@file.js``/refactor:pure` |
```# ~/.qwen/commands/refactor/pure.toml
description = "Refactor code to pure function"
prompt = """
Please analyze code in current context, refactor to pure function.
Requirements:
1. Provide refactored code
2. Explain key changes and pure function characteristic implementation
3. Maintain function unchanged
"""
```
### Custom Command Best Practices Summary
#### Command Design Recommendations Table
| Practice Points | Recommended Approach | Avoid |
| -------------------- | ----------------------------------- | ------------------------------------------- |
| Command Naming | Use namespaces for organization | Avoid overly generic names |
| Parameter Processing | Clearly use `{{args}}` | Rely on default appending (easy to confuse) |
| Error Handling | Utilize Shell error output | Ignore execution failure |
| File Organization | Organize by function in directories | All commands in root directory |
| Description Field | Always provide clear description | Rely on auto-generated description |
#### Security Features Reminder Table
| Security Mechanism | Protection Effect | User Operation |
| ---------------------- | -------------------------- | ---------------------- |
| Shell Escaping | Prevent command injection | Automatic processing |
| Execution Confirmation | Avoid accidental execution | Dialog confirmation |
| Error Reporting | Help diagnose issues | View error information |

View File

@@ -0,0 +1,282 @@
# Headless Mode
Headless mode allows you to run Qwen Code programmatically from command line
scripts and automation tools without any interactive UI. This is ideal for
scripting, automation, CI/CD pipelines, and building AI-powered tools.
## Overview
The headless mode provides a headless interface to Qwen Code that:
- Accepts prompts via command line arguments or stdin
- Returns structured output (text or JSON)
- Supports file redirection and piping
- Enables automation and scripting workflows
- Provides consistent exit codes for error handling
- Can resume previous sessions scoped to the current project for multi-step automation
## Basic Usage
### Direct Prompts
Use the `--prompt` (or `-p`) flag to run in headless mode:
```bash
qwen --prompt "What is machine learning?"
```
### Stdin Input
Pipe input to Qwen Code from your terminal:
```bash
echo "Explain this code" | qwen
```
### Combining with File Input
Read from files and process with Qwen Code:
```bash
cat README.md | qwen --prompt "Summarize this documentation"
```
### Resume Previous Sessions (Headless)
Reuse conversation context from the current project in headless scripts:
```bash
# Continue the most recent session for this project and run a new prompt
qwen --continue -p "Run the tests again and summarize failures"
# Resume a specific session ID directly (no UI)
qwen --resume 123e4567-e89b-12d3-a456-426614174000 -p "Apply the follow-up refactor"
```
> [!note]
>
> - Session data is project-scoped JSONL under `~/.qwen/projects/<sanitized-cwd>/chats`.
> - Restores conversation history, tool outputs, and chat-compression checkpoints before sending the new prompt.
## Output Formats
Qwen Code supports multiple output formats for different use cases:
### Text Output (Default)
Standard human-readable output:
```bash
qwen -p "What is the capital of France?"
```
Response format:
```
The capital of France is Paris.
```
### JSON Output
Returns structured data as a JSON array. All messages are buffered and output together when the session completes. This format is ideal for programmatic processing and automation scripts.
The JSON output is an array of message objects. The output includes multiple message types: system messages (session initialization), assistant messages (AI responses), and result messages (execution summary).
#### Example Usage
```bash
qwen -p "What is the capital of France?" --output-format json
```
Output (at end of execution):
```json
[
{
"type": "system",
"subtype": "session_start",
"uuid": "...",
"session_id": "...",
"model": "qwen3-coder-plus",
...
},
{
"type": "assistant",
"uuid": "...",
"session_id": "...",
"message": {
"id": "...",
"type": "message",
"role": "assistant",
"model": "qwen3-coder-plus",
"content": [
{
"type": "text",
"text": "The capital of France is Paris."
}
],
"usage": {...}
},
"parent_tool_use_id": null
},
{
"type": "result",
"subtype": "success",
"uuid": "...",
"session_id": "...",
"is_error": false,
"duration_ms": 1234,
"result": "The capital of France is Paris.",
"usage": {...}
}
]
```
### Stream-JSON Output
Stream-JSON format emits JSON messages immediately as they occur during execution, enabling real-time monitoring. This format uses line-delimited JSON where each message is a complete JSON object on a single line.
```bash
qwen -p "Explain TypeScript" --output-format stream-json
```
Output (streaming as events occur):
```json
{"type":"system","subtype":"session_start","uuid":"...","session_id":"..."}
{"type":"assistant","uuid":"...","session_id":"...","message":{...}}
{"type":"result","subtype":"success","uuid":"...","session_id":"..."}
```
When combined with `--include-partial-messages`, additional stream events are emitted in real-time (message_start, content_block_delta, etc.) for real-time UI updates.
```bash
qwen -p "Write a Python script" --output-format stream-json --include-partial-messages
```
### Input Format
The `--input-format` parameter controls how Qwen Code consumes input from standard input:
- **`text`** (default): Standard text input from stdin or command-line arguments
- **`stream-json`**: JSON message protocol via stdin for bidirectional communication
> **Note:** Stream-json input mode is currently under construction and is intended for SDK integration. It requires `--output-format stream-json` to be set.
### File Redirection
Save output to files or pipe to other commands:
```bash
# Save to file
qwen -p "Explain Docker" > docker-explanation.txt
qwen -p "Explain Docker" --output-format json > docker-explanation.json
# Append to file
qwen -p "Add more details" >> docker-explanation.txt
# Pipe to other tools
qwen -p "What is Kubernetes?" --output-format json | jq '.response'
qwen -p "Explain microservices" | wc -w
qwen -p "List programming languages" | grep -i "python"
# Stream-JSON output for real-time processing
qwen -p "Explain Docker" --output-format stream-json | jq '.type'
qwen -p "Write code" --output-format stream-json --include-partial-messages | jq '.event.type'
```
## Configuration Options
Key command-line options for headless usage:
| Option | Description | Example |
| ---------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------ |
| `--prompt`, `-p` | Run in headless mode | `qwen -p "query"` |
| `--output-format`, `-o` | Specify output format (text, json, stream-json) | `qwen -p "query" --output-format json` |
| `--input-format` | Specify input format (text, stream-json) | `qwen --input-format text --output-format stream-json` |
| `--include-partial-messages` | Include partial messages in stream-json output | `qwen -p "query" --output-format stream-json --include-partial-messages` |
| `--debug`, `-d` | Enable debug mode | `qwen -p "query" --debug` |
| `--all-files`, `-a` | Include all files in context | `qwen -p "query" --all-files` |
| `--include-directories` | Include additional directories | `qwen -p "query" --include-directories src,docs` |
| `--yolo`, `-y` | Auto-approve all actions | `qwen -p "query" --yolo` |
| `--approval-mode` | Set approval mode | `qwen -p "query" --approval-mode auto_edit` |
| `--continue` | Resume the most recent session for this project | `qwen --continue -p "Pick up where we left off"` |
| `--resume [sessionId]` | Resume a specific session (or choose interactively) | `qwen --resume 123e... -p "Finish the refactor"` |
For complete details on all available configuration options, settings files, and environment variables, see the [Configuration Guide](/users/configuration/settings).
## Examples
### Code review
```bash
cat src/auth.py | qwen -p "Review this authentication code for security issues" > security-review.txt
```
### Generate commit messages
```bash
result=$(git diff --cached | qwen -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response'
```
### API documentation
```bash
result=$(cat api/routes.js | qwen -p "Generate OpenAPI spec for these routes" --output-format json)
echo "$result" | jq -r '.response' > openapi.json
```
### Batch code analysis
```bash
for file in src/*.py; do
echo "Analyzing $file..."
result=$(cat "$file" | qwen -p "Find potential bugs and suggest improvements" --output-format json)
echo "$result" | jq -r '.response' > "reports/$(basename "$file").analysis"
echo "Completed analysis for $(basename "$file")" >> reports/progress.log
done
```
### PR code review
```bash
result=$(git diff origin/main...HEAD | qwen -p "Review these changes for bugs, security issues, and code quality" --output-format json)
echo "$result" | jq -r '.response' > pr-review.json
```
### Log analysis
```bash
grep "ERROR" /var/log/app.log | tail -20 | qwen -p "Analyze these errors and suggest root cause and fixes" > error-analysis.txt
```
### Release notes generation
```bash
result=$(git log --oneline v1.0.0..HEAD | qwen -p "Generate release notes from these commits" --output-format json)
response=$(echo "$result" | jq -r '.response')
echo "$response"
echo "$response" >> CHANGELOG.md
```
### Model and tool usage tracking
```bash
result=$(qwen -p "Explain this database schema" --include-directories db --output-format json)
total_tokens=$(echo "$result" | jq -r '.stats.models // {} | to_entries | map(.value.tokens.total) | add // 0')
models_used=$(echo "$result" | jq -r '.stats.models // {} | keys | join(", ") | if . == "" then "none" else . end')
tool_calls=$(echo "$result" | jq -r '.stats.tools.totalCalls // 0')
tools_used=$(echo "$result" | jq -r '.stats.tools.byName // {} | keys | join(", ") | if . == "" then "none" else . end')
echo "$(date): $total_tokens tokens, $tool_calls tool calls ($tools_used) used with models: $models_used" >> usage.log
echo "$result" | jq -r '.response' > schema-docs.md
echo "Recent usage trends:"
tail -5 usage.log
```
## Resources
- [CLI Configuration](/users/configuration/settings#command-line-arguments) - Complete configuration guide
- [Authentication](/users/configuration/settings#environment-variables-for-api-access) - Setup authentication
- [Commands](/users/reference/cli-reference) - Interactive commands reference
- [Tutorials](/users/quickstart) - Step-by-step automation guides

284
docs/users/features/mcp.md Normal file
View File

@@ -0,0 +1,284 @@
# Connect Qwen Code to tools via MCP
Qwen Code can connect to external tools and data sources through the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction). MCP servers give Qwen Code access to your tools, databases, and APIs.
## What you can do with MCP
With MCP servers connected, you can ask Qwen Code to:
- Work with files and repos (read/search/write, depending on the tools you enable)
- Query databases (schema inspection, queries, reporting)
- Integrate internal services (wrap your APIs as MCP tools)
- Automate workflows (repeatable tasks exposed as tools/prompts)
> [!tip]
> If youre looking for the “one command to get started”, jump to [Quick start](#quick-start).
## Quick start
Qwen Code loads MCP servers from `mcpServers` in your `settings.json`. You can configure servers either:
- By editing `settings.json` directly
- By using `qwen mcp` commands (see [CLI reference](#qwen-mcp-cli))
### Add your first server
1. Add a server (example: remote HTTP MCP server):
```bash
qwen mcp add --transport http my-server http://localhost:3000/mcp
```
2. Verify it shows up:
```bash
qwen mcp list
```
3. Restart Qwen Code in the same project (or start it if it wasnt running yet), then ask the model to use tools from that server.
## Where configuration is stored (scopes)
Most users only need these two scopes:
- **Project scope (default)**: `.qwen/settings.json` in your project root
- **User scope**: `~/.qwen/settings.json` across all projects on your machine
Write to user scope:
```bash
qwen mcp add --scope user --transport http my-server http://localhost:3000/mcp
```
> [!tip]
> For advanced configuration layers (system defaults/system settings and precedence rules), see [Settings](/users/configuration/settings).
## Configure servers
### Choose a transport
| Transport | When to use | JSON field(s) |
| --------- | ----------------------------------------------------------------- | ------------------------------------------- |
| `http` | Recommended for remote services; works well for cloud MCP servers | `httpUrl` (+ optional `headers`) |
| `sse` | Legacy/deprecated servers that only support Server-Sent Events | `url` (+ optional `headers`) |
| `stdio` | Local process (scripts, CLIs, Docker) on your machine | `command`, `args` (+ optional `cwd`, `env`) |
> [!note]
> If a server supports both, prefer **HTTP** over **SSE**.
### Configure via `settings.json` vs `qwen mcp add`
Both approaches produce the same `mcpServers` entries in your `settings.json`—use whichever you prefer.
#### Stdio server (local process)
JSON (`.qwen/settings.json`):
```json
{
"mcpServers": {
"pythonTools": {
"command": "python",
"args": ["-m", "my_mcp_server", "--port", "8080"],
"cwd": "./mcp-servers/python",
"env": {
"DATABASE_URL": "$DB_CONNECTION_STRING",
"API_KEY": "${EXTERNAL_API_KEY}"
},
"timeout": 15000
}
}
}
```
CLI (writes to project scope by default):
```bash
qwen mcp add pythonTools -e DATABASE_URL=$DB_CONNECTION_STRING -e API_KEY=$EXTERNAL_API_KEY \
--timeout 15000 python -m my_mcp_server --port 8080
```
#### HTTP server (remote streamable HTTP)
JSON:
```json
{
"mcpServers": {
"httpServerWithAuth": {
"httpUrl": "http://localhost:3000/mcp",
"headers": {
"Authorization": "Bearer your-api-token"
},
"timeout": 5000
}
}
}
```
CLI:
```bash
qwen mcp add --transport http httpServerWithAuth http://localhost:3000/mcp \
--header "Authorization: Bearer your-api-token" --timeout 5000
```
#### SSE server (remote Server-Sent Events)
JSON:
```json
{
"mcpServers": {
"sseServer": {
"url": "http://localhost:8080/sse",
"timeout": 30000
}
}
}
```
CLI:
```bash
qwen mcp add --transport sse sseServer http://localhost:8080/sse --timeout 30000
```
## Safety and control
### Trust (skip confirmations)
- **Server trust** (`trust: true`): bypasses confirmation prompts for that server (use sparingly).
### Tool filtering (allow/deny tools per server)
Use `includeTools` / `excludeTools` to restrict tools exposed by a server (from Qwen Codes perspective).
Example: include only a few tools:
```json
{
"mcpServers": {
"filteredServer": {
"command": "python",
"args": ["-m", "my_mcp_server"],
"includeTools": ["safe_tool", "file_reader", "data_processor"],
"timeout": 30000
}
}
}
```
### Global allow/deny lists
The `mcp` object in your `settings.json` defines global rules for all MCP servers:
- `mcp.allowed`: allow-list of MCP server names (keys in `mcpServers`)
- `mcp.excluded`: deny-list of MCP server names
Example:
```json
{
"mcp": {
"allowed": ["my-trusted-server"],
"excluded": ["experimental-server"]
}
}
```
## Troubleshooting
- **Server shows “Disconnected” in `qwen mcp list`**: verify the URL/command is correct, then increase `timeout`.
- **Stdio server fails to start**: use an absolute `command` path, and double-check `cwd`/`env`.
- **Environment variables in JSON dont resolve**: ensure they exist in the environment where Qwen Code runs (shell vs GUI app environments can differ).
## Reference
### `settings.json` structure
#### Server-specific configuration (`mcpServers`)
Add an `mcpServers` object to your `settings.json` file:
```json
// ... file contains other config objects
{
"mcpServers": {
"serverName": {
"command": "path/to/server",
"args": ["--arg1", "value1"],
"env": {
"API_KEY": "$MY_API_TOKEN"
},
"cwd": "./server-directory",
"timeout": 30000,
"trust": false
}
}
}
```
Configuration properties:
Required (one of the following):
| Property | Description |
| --------- | ------------------------------------------------------ |
| `command` | Path to the executable for Stdio transport |
| `url` | SSE endpoint URL (e.g., `"http://localhost:8080/sse"`) |
| `httpUrl` | HTTP streaming endpoint URL |
Optional:
| Property | Type/Default | Description |
| ---------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `args` | array | Command-line arguments for Stdio transport |
| `headers` | object | Custom HTTP headers when using `url` or `httpUrl` |
| `env` | object | Environment variables for the server process. Values can reference environment variables using `$VAR_NAME` or `${VAR_NAME}` syntax |
| `cwd` | string | Working directory for Stdio transport |
| `timeout` | number<br>(default: 600,000) | Request timeout in milliseconds (default: 600,000ms = 10 minutes) |
| `trust` | boolean<br>(default: false) | When `true`, bypasses all tool call confirmations for this server (default: `false`) |
| `includeTools` | array | 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. |
| `excludeTools` | array | 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.<br>Note: `excludeTools` takes precedence over `includeTools` - if a tool is in both lists, it will be excluded. |
| `targetAudience` | string | The OAuth Client ID allowlisted on the IAP-protected application you are trying to access. Used with `authProviderType: 'service_account_impersonation'`. |
| `targetServiceAccount` | string | The email address of the Google Cloud Service Account to impersonate. Used with `authProviderType: 'service_account_impersonation'`. |
<a id="qwen-mcp-cli"></a>
### Manage MCP servers with `qwen mcp`
You can always configure MCP servers by manually editing `settings.json`, but the CLI is usually faster.
#### Adding a server (`qwen mcp add`)
```bash
qwen mcp add [options] <name> <commandOrUrl> [args...]
```
| Argument/Option | Description | Default | Example |
| ------------------- | ------------------------------------------------------------------- | ------------------ | ----------------------------------------- |
| `<name>` | A unique name for the server. | — | `example-server` |
| `<commandOrUrl>` | The command to execute (for `stdio`) or the URL (for `http`/`sse`). | — | `/usr/bin/python` or `http://localhost:8` |
| `[args...]` | Optional arguments for a `stdio` command. | — | `--port 5000` |
| `-s`, `--scope` | Configuration scope (user or project). | `project` | `-s user` |
| `-t`, `--transport` | Transport type (`stdio`, `sse`, `http`). | `stdio` | `-t sse` |
| `-e`, `--env` | Set environment variables. | — | `-e KEY=value` |
| `-H`, `--header` | Set HTTP headers for SSE and HTTP transports. | — | `-H "X-Api-Key: abc123"` |
| `--timeout` | Set connection timeout in milliseconds. | — | `--timeout 30000` |
| `--trust` | Trust the server (bypass all tool call confirmation prompts). | — (`false`) | `--trust` |
| `--description` | Set the description for the server. | — | `--description "Local tools"` |
| `--include-tools` | A comma-separated list of tools to include. | all tools included | `--include-tools mytool,othertool` |
| `--exclude-tools` | A comma-separated list of tools to exclude. | none | `--exclude-tools mytool` |
#### Listing servers (`qwen mcp list`)
```bash
qwen mcp list
```
#### Removing a server (`qwen mcp remove`)
```bash
qwen mcp remove <name>
```

View File

@@ -0,0 +1,225 @@
# Sandbox
This document explains how to run Qwen Code inside a sandbox to reduce risk when tools execute shell commands or modify files.
## Prerequisites
Before using sandboxing, you need to install and set up Qwen Code:
```bash
npm install -g @qwen-code/qwen-code
```
To verify the installation
```bash
qwen --version
```
## Overview of sandboxing
Sandboxing isolates potentially dangerous operations (such as shell commands or file modifications) from your host system, providing a security barrier between the CLI and your environment.
The benefits of sandboxing include:
- **Security**: Prevent accidental system damage or data loss.
- **Isolation**: Limit file system access to project directory.
- **Consistency**: Ensure reproducible environments across different systems.
- **Safety**: Reduce risk when working with untrusted code or experimental commands.
> [!note]
>
> **Naming note:** Some sandbox-related environment variables still use the `GEMINI_*` prefix for backwards compatibility.
## Sandboxing methods
Your ideal method of sandboxing may differ depending on your platform and your preferred container solution.
### 1. macOS Seatbelt (macOS only)
Lightweight, built-in sandboxing using `sandbox-exec`.
**Default profile**: `permissive-open` - restricts writes outside the project directory, but allows most other operations and outbound network access.
**Best for**: Fast, no Docker required, strong guardrails for file writes.
### 2. Container-based (Docker/Podman)
Cross-platform sandboxing with complete process isolation.
By default, Qwen Code uses a published sandbox image (configured in the CLI package) and will pull it as needed.
**Best for**: Strong isolation on any OS, consistent tooling inside a known image.
### Choosing a method
- **On macOS**:
- Use Seatbelt when you want lightweight sandboxing (recommended for most users).
- Use Docker/Podman when you need a full Linux userland (e.g., tools that require Linux binaries).
- **On Linux/Windows**:
- Use Docker or Podman.
## Quickstart
```bash
# Enable sandboxing with command flag
qwen -s -p "analyze the code structure"
# Or enable sandboxing for your shell session (recommended for CI / scripts)
export GEMINI_SANDBOX=true # true auto-picks a provider (see notes below)
qwen -p "run the test suite"
# Configure in settings.json
{
"tools": {
"sandbox": true
}
}
```
> [!tip]
>
> **Provider selection notes:**
>
> - On **macOS**, `GEMINI_SANDBOX=true` typically selects `sandbox-exec` (Seatbelt) if available.
> - On **Linux/Windows**, `GEMINI_SANDBOX=true` requires `docker` or `podman` to be installed.
> - To force a provider, set `GEMINI_SANDBOX=docker|podman|sandbox-exec`.
## Configuration
### Enable sandboxing (in order of precedence)
1. **Environment variable**: `GEMINI_SANDBOX=true|false|docker|podman|sandbox-exec`
2. **Command flag / argument**: `-s`, `--sandbox`, or `--sandbox=<provider>`
3. **Settings file**: `tools.sandbox` in your `settings.json` (e.g., `{"tools": {"sandbox": true}}`).
> [!important]
>
> If `GEMINI_SANDBOX` is set, it **overrides** the CLI flag and `settings.json`.
### Configure the sandbox image (Docker/Podman)
- **CLI flag**: `--sandbox-image <image>`
- **Environment variable**: `GEMINI_SANDBOX_IMAGE=<image>`
If you dont set either, Qwen Code uses the default image configured in the CLI package (for example `ghcr.io/qwenlm/qwen-code:<version>`).
### macOS Seatbelt profiles
Built-in profiles (set via `SEATBELT_PROFILE` env var):
- `permissive-open` (default): Write restrictions, network allowed
- `permissive-closed`: Write restrictions, no network
- `permissive-proxied`: Write restrictions, network via proxy
- `restrictive-open`: Strict restrictions, network allowed
- `restrictive-closed`: Maximum restrictions
- `restrictive-proxied`: Strict restrictions, network via proxy
> [!tip]
>
> Start with `permissive-open`, then tighten to `restrictive-closed` if your workflow still works.
### Custom Seatbelt profiles (macOS)
To use a custom Seatbelt profile:
1. Create a file named `.qwen/sandbox-macos-<profile_name>.sb` in your project.
2. Set `SEATBELT_PROFILE=<profile_name>`.
### Custom Sandbox Flags
For container-based sandboxing, you can inject custom flags into the `docker` or `podman` command using the `SANDBOX_FLAGS` environment variable. This is useful for advanced configurations, such as disabling security features for specific use cases.
**Example (Podman)**:
To disable SELinux labeling for volume mounts, you can set the following:
```bash
export SANDBOX_FLAGS="--security-opt label=disable"
```
Multiple flags can be provided as a space-separated string:
```bash
export SANDBOX_FLAGS="--flag1 --flag2=value"
```
### Network proxying (all sandbox methods)
If you want to restrict outbound network access to an allowlist, you can run a local proxy alongside the sandbox:
- Set `GEMINI_SANDBOX_PROXY_COMMAND=<command>`
- The command must start a proxy server that listens on `:::8877`
This is especially useful with `*-proxied` Seatbelt profiles.
For a working allowlist-style proxy example, see: [Example Proxy Script](/developers/examples/proxy-script).
## Linux UID/GID handling
The sandbox automatically handles user permissions on Linux. Override these permissions with:
```bash
export SANDBOX_SET_UID_GID=true # Force host UID/GID
export SANDBOX_SET_UID_GID=false # Disable UID/GID mapping
```
## Customizing the sandbox environment (Docker/Podman)
If you need extra tools inside the container (e.g., `git`, `python`, `rg`), create a custom Dockerfile:
- Path: `.qwen/sandbox.Dockerfile`
- Then run with: `BUILD_SANDBOX=1 qwen -s ...`
This builds a project-specific image based on the default sandbox image.
## Troubleshooting
### Common issues
**"Operation not permitted"**
- Operation requires access outside sandbox.
- On macOS Seatbelt: try a more permissive `SEATBELT_PROFILE`.
- On Docker/Podman: verify the workspace is mounted and your command doesnt require access outside the project directory.
**Missing commands**
- Container sandbox: add them via `.qwen/sandbox.Dockerfile` or `.qwen/sandbox.bashrc`.
- Seatbelt: your host binaries are used, but the sandbox may restrict access to some paths.
**Network issues**
- Check sandbox profile allows network.
- Verify proxy configuration.
### Debug mode
```bash
DEBUG=1 qwen -s -p "debug command"
```
**Note:** If you have `DEBUG=true` in a project's `.env` file, it won't affect the CLI due to automatic exclusion. Use `.qwen/.env` files for Qwen Code-specific debug settings.
### Inspect sandbox
```bash
# Check environment
qwen -s -p "run shell command: env | grep SANDBOX"
# List mounts
qwen -s -p "run shell command: mount | grep workspace"
```
## Security notes
- Sandboxing reduces but doesn't eliminate all risks.
- Use the most restrictive profile that allows your work.
- Container overhead is minimal after the first pull/build.
- GUI applications may not work in sandboxes.
## Related documentation
- [Configuration](/users/configuration/settings): Full configuration options.
- [Commands](/users/reference/cli-reference): Available commands.
- [Troubleshooting](/users/support/troubleshooting): General troubleshooting.

View File

@@ -0,0 +1,490 @@
# Subagents
Subagents are specialized AI assistants that handle specific types of tasks within Qwen Code. They allow you to delegate focused work to AI agents that are configured with task-specific prompts, tools, and behaviors.
## What are Subagents?
Subagents are independent AI assistants that:
- **Specialize in specific tasks** - Each Subagent is configured with a focused system prompt for particular types of work
- **Have separate context** - They maintain their own conversation history, separate from your main chat
- **Use controlled tools** - You can configure which tools each Subagent has access to
- **Work autonomously** - Once given a task, they work independently until completion or failure
- **Provide detailed feedback** - You can see their progress, tool usage, and execution statistics in real-time
## Key Benefits
- **Task Specialization**: Create agents optimized for specific workflows (testing, documentation, refactoring, etc.)
- **Context Isolation**: Keep specialized work separate from your main conversation
- **Reusability**: Save and reuse agent configurations across projects and sessions
- **Controlled Access**: Limit which tools each agent can use for security and focus
- **Progress Visibility**: Monitor agent execution with real-time progress updates
## How Subagents Work
1. **Configuration**: You create Subagents configurations that define their behavior, tools, and system prompts
2. **Delegation**: The main AI can automatically delegate tasks to appropriate Subagents
3. **Execution**: Subagents work independently, using their configured tools to complete tasks
4. **Results**: They return results and execution summaries back to the main conversation
## Getting Started
### Quick Start
1. **Create your first Subagent**:
`/agents create`
Follow the guided wizard to create a specialized agent.
2. **Manage existing agents**:
`/agents manage`
View and manage your configured Subagents.
3. **Use Subagents automatically**: Simply ask the main AI to perform tasks that match your Subagents' specializations. The AI will automatically delegate appropriate work.
### Example Usage
```
User: "Please write comprehensive tests for the authentication module"
AI: I'll delegate this to your testing specialist Subagents.
[Delegates to "testing-expert" Subagents]
[Shows real-time progress of test creation]
[Returns with completed test files and execution summary]`
```
## Management
### CLI Commands
Subagents are managed through the `/agents` slash command and its subcommands:
**Usage:**`/agents create`。Creates a new Subagent through a guided step wizard.
**Usage:**`/agents manage`。Opens an interactive management dialog for viewing and managing existing Subagents.
### Storage Locations
Subagents are stored as Markdown files in two locations:
- **Project-level**: `.qwen/agents/` (takes precedence)
- **User-level**: `~/.qwen/agents/` (fallback)
This allows you to have both project-specific agents and personal agents that work across all projects.
### File Format
Subagents are configured using Markdown files with YAML frontmatter. This format is human-readable and easy to edit with any text editor.
#### Basic Structure
```
---
name: agent-name
description: Brief description of when and how to use this agent
tools:
- tool1
- tool2
- tool3 # Optional
---
System prompt content goes here.
Multiple paragraphs are supported.
You can use ${variable} templating for dynamic content.
```
#### Example Usage
```
---
name: project-documenter
description: Creates project documentation and README files
---
You are a documentation specialist for the ${project_name} project.
Your task: ${task_description}
Working directory: ${current_directory}
Generated on: ${timestamp}
Focus on creating clear, comprehensive documentation that helps both
new contributors and end users understand the project.
```
## Using Subagents Effectively
### Automatic Delegation
Qwen Code proactively delegates tasks based on:
- The task description in your request
- The description field in Subagents configurations
- Current context and available tools
To encourage more proactive Subagents use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your description field.
### Explicit Invocation
Request a specific Subagent by mentioning it in your command:
```
Let the testing-expert Subagents create unit tests for the payment module
Have the documentation-writer Subagents update the API reference
Get the react-specialist Subagents to optimize this component's performance
```
## Examples
### Development Workflow Agents
#### Testing Specialist
Perfect for comprehensive test creation and test-driven development.
```
---
name: testing-expert
description: Writes comprehensive unit tests, integration tests, and handles test automation with best practices
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a testing specialist focused on creating high-quality, maintainable tests.
Your expertise includes:
- Unit testing with appropriate mocking and isolation
- Integration testing for component interactions
- Test-driven development practices
- Edge case identification and comprehensive coverage
- Performance and load testing when appropriate
For each testing task:
1. Analyze the code structure and dependencies
2. Identify key functionality, edge cases, and error conditions
3. Create comprehensive test suites with descriptive names
4. Include proper setup/teardown and meaningful assertions
5. Add comments explaining complex test scenarios
6. Ensure tests are maintainable and follow DRY principles
Always follow testing best practices for the detected language and framework.
Focus on both positive and negative test cases.
```
**Use Cases:**
- “Write unit tests for the authentication service”
- “Create integration tests for the payment processing workflow”
- “Add test coverage for edge cases in the data validation module”
#### Documentation Writer
Specialized in creating clear, comprehensive documentation.
```
---
name: documentation-writer
description: Creates comprehensive documentation, README files, API docs, and user guides
tools:
- read_file
- write_file
- read_many_files
- web_search
---
You are a technical documentation specialist for ${project_name}.
Your role is to create clear, comprehensive documentation that serves both
developers and end users. Focus on:
**For API Documentation:**
- Clear endpoint descriptions with examples
- Parameter details with types and constraints
- Response format documentation
- Error code explanations
- Authentication requirements
**For User Documentation:**
- Step-by-step instructions with screenshots when helpful
- Installation and setup guides
- Configuration options and examples
- Troubleshooting sections for common issues
- FAQ sections based on common user questions
**For Developer Documentation:**
- Architecture overviews and design decisions
- Code examples that actually work
- Contributing guidelines
- Development environment setup
Always verify code examples and ensure documentation stays current with
the actual implementation. Use clear headings, bullet points, and examples.
```
**Use Cases:**
- “Create API documentation for the user management endpoints”
- “Write a comprehensive README for this project”
- “Document the deployment process with troubleshooting steps”
#### Code Reviewer
Focused on code quality, security, and best practices.
```
---
name: code-reviewer
description: Reviews code for best practices, security issues, performance, and maintainability
tools:
- read_file
- read_many_files
---
You are an experienced code reviewer focused on quality, security, and maintainability.
Review criteria:
- **Code Structure**: Organization, modularity, and separation of concerns
- **Performance**: Algorithmic efficiency and resource usage
- **Security**: Vulnerability assessment and secure coding practices
- **Best Practices**: Language/framework-specific conventions
- **Error Handling**: Proper exception handling and edge case coverage
- **Readability**: Clear naming, comments, and code organization
- **Testing**: Test coverage and testability considerations
Provide constructive feedback with:
1. **Critical Issues**: Security vulnerabilities, major bugs
2. **Important Improvements**: Performance issues, design problems
3. **Minor Suggestions**: Style improvements, refactoring opportunities
4. **Positive Feedback**: Well-implemented patterns and good practices
Focus on actionable feedback with specific examples and suggested solutions.
Prioritize issues by impact and provide rationale for recommendations.
```
**Use Cases:**
- “Review this authentication implementation for security issues”
- “Check the performance implications of this database query logic”
- “Evaluate the code structure and suggest improvements”
### Technology-Specific Agents
#### React Specialist
Optimized for React development, hooks, and component patterns.
```
---
name: react-specialist
description: Expert in React development, hooks, component patterns, and modern React best practices
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a React specialist with deep expertise in modern React development.
Your expertise covers:
- **Component Design**: Functional components, custom hooks, composition patterns
- **State Management**: useState, useReducer, Context API, and external libraries
- **Performance**: React.memo, useMemo, useCallback, code splitting
- **Testing**: React Testing Library, Jest, component testing strategies
- **TypeScript Integration**: Proper typing for props, hooks, and components
- **Modern Patterns**: Suspense, Error Boundaries, Concurrent Features
For React tasks:
1. Use functional components and hooks by default
2. Implement proper TypeScript typing
3. Follow React best practices and conventions
4. Consider performance implications
5. Include appropriate error handling
6. Write testable, maintainable code
Always stay current with React best practices and avoid deprecated patterns.
Focus on accessibility and user experience considerations.
```
**Use Cases:**
- “Create a reusable data table component with sorting and filtering”
- “Implement a custom hook for API data fetching with caching”
- “Refactor this class component to use modern React patterns”
#### Python Expert
Specialized in Python development, frameworks, and best practices.
```
---
name: python-expert
description: Expert in Python development, frameworks, testing, and Python-specific best practices
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a Python expert with deep knowledge of the Python ecosystem.
Your expertise includes:
- **Core Python**: Pythonic patterns, data structures, algorithms
- **Frameworks**: Django, Flask, FastAPI, SQLAlchemy
- **Testing**: pytest, unittest, mocking, test-driven development
- **Data Science**: pandas, numpy, matplotlib, jupyter notebooks
- **Async Programming**: asyncio, async/await patterns
- **Package Management**: pip, poetry, virtual environments
- **Code Quality**: PEP 8, type hints, linting with pylint/flake8
For Python tasks:
1. Follow PEP 8 style guidelines
2. Use type hints for better code documentation
3. Implement proper error handling with specific exceptions
4. Write comprehensive docstrings
5. Consider performance and memory usage
6. Include appropriate logging
7. Write testable, modular code
Focus on writing clean, maintainable Python code that follows community standards.
```
**Use Cases:**
- “Create a FastAPI service for user authentication with JWT tokens”
- “Implement a data processing pipeline with pandas and error handling”
- “Write a CLI tool using argparse with comprehensive help documentation”
## Best Practices
### Design Principles
#### Single Responsibility Principle
Each Subagent should have a clear, focused purpose.
**✅ Good:**
```
---
name: testing-expert
description: Writes comprehensive unit tests and integration tests
---
```
**❌ Avoid:**
```
---
name: general-helper
description: Helps with testing, documentation, code review, and deployment
---
```
**Why:** Focused agents produce better results and are easier to maintain.
#### Clear Specialization
Define specific expertise areas rather than broad capabilities.
**✅ Good:**
```
---
name: react-performance-optimizer
description: Optimizes React applications for performance using profiling and best practices
---
```
**❌ Avoid:**
```
---
name: frontend-developer
description: Works on frontend development tasks
---
```
**Why:** Specific expertise leads to more targeted and effective assistance.
#### Actionable Descriptions
Write descriptions that clearly indicate when to use the agent.
**✅ Good:**
```
description: Reviews code for security vulnerabilities, performance issues, and maintainability concerns
```
**❌ Avoid:**
```
description: A helpful code reviewer
```
**Why:** Clear descriptions help the main AI choose the right agent for each task.
### Configuration Best Practices
#### System Prompt Guidelines
**Be Specific About Expertise:**
```
You are a Python testing specialist with expertise in:
- pytest framework and fixtures
- Mock objects and dependency injection
- Test-driven development practices
- Performance testing with pytest-benchmark
```
**Include Step-by-Step Approaches:**
```
For each testing task:
1. Analyze the code structure and dependencies
2. Identify key functionality and edge cases
3. Create comprehensive test suites with clear naming
4. Include setup/teardown and proper assertions
5. Add comments explaining complex test scenarios
```
**Specify Output Standards:**
```
Always follow these standards:
- Use descriptive test names that explain the scenario
- Include both positive and negative test cases
- Add docstrings for complex test functions
- Ensure tests are independent and can run in any order
```
## Security Considerations
- **Tool Restrictions**: Subagents only have access to their configured tools
- **Sandboxing**: All tool execution follows the same security model as direct tool use
- **Audit Trail**: All Subagents actions are logged and visible in real-time
- **Access Control**: Project and user-level separation provides appropriate boundaries
- **Sensitive Information**: Avoid including secrets or credentials in agent configurations
- **Production Environments**: Consider separate agents for production vs development environments

View File

@@ -0,0 +1,29 @@
# Token Caching and Cost Optimization
Qwen Code automatically optimizes API costs through token caching when using API key authentication. This feature stores frequently used content like system instructions and conversation history to reduce the number of tokens processed in subsequent requests.
## How It Benefits You
- **Cost reduction**: Less tokens mean lower API costs
- **Faster responses**: Cached content is retrieved more quickly
- **Automatic optimization**: No configuration needed - it works behind the scenes
## Token caching is available for
- API key users (Qwen API key, OpenAI-compatible providers)
## Monitoring Your Savings
Use the `/stats` command to see your cached token savings:
- When active, the stats display shows how many tokens were served from cache
- You'll see both the absolute number and percentage of cached tokens
- Example: "10,500 (90.4%) of input tokens were served from the cache, reducing costs."
This information is only displayed when cached tokens are being used, which occurs with API key authentication but not with OAuth authentication.
## Example Stats Display
![Qwen Code Stats Display](https://img.alicdn.com/imgextra/i3/O1CN01F1yzRs1juyZu63jdS_!!6000000004609-2-tps-1038-738.png)
The above image shows an example of the `/stats` command output, highlighting the cached token savings information.

View File

@@ -0,0 +1,4 @@
export default {
'ide-integration': 'Introduction',
'ide-companion-spec': 'IDE Companion Spec',
};

View File

@@ -0,0 +1,184 @@
# Qwen Code Companion Plugin: Interface Specification
> Last Updated: September 15, 2025
This document defines the contract for building a companion plugin to enable Qwen Code's IDE mode. For VS Code, these features (native diffing, context awareness) are provided by the official extension ([marketplace](https://marketplace.visualstudio.com/items?itemName=qwenlm.qwen-code-vscode-ide-companion)). This specification is for contributors who wish to bring similar functionality to other editors like JetBrains IDEs, Sublime Text, etc.
## I. The Communication Interface
Qwen Code and the IDE plugin communicate through a local communication channel.
### 1. Transport Layer: MCP over HTTP
The plugin **MUST** run a local HTTP server that implements the **Model Context Protocol (MCP)**.
- **Protocol:** The server must be a valid MCP server. We recommend using an existing MCP SDK for your language of choice if available.
- **Endpoint:** The server should expose a single endpoint (e.g., `/mcp`) for all MCP communication.
- **Port:** The server **MUST** listen on a dynamically assigned port (i.e., listen on port `0`).
### 2. Discovery Mechanism: The Port File
For Qwen Code to connect, it needs to discover which IDE instance it's running in and what port your server is using. The plugin **MUST** facilitate this by creating a "discovery file."
- **How the CLI Finds the File:** The CLI determines the Process ID (PID) of the IDE it's running in by traversing the process tree. It then looks for a discovery file that contains this PID in its name.
- **File Location:** The file must be created in a specific directory: `os.tmpdir()/qwen/ide/`. Your plugin must create this directory if it doesn't exist.
- **File Naming Convention:** The filename is critical and **MUST** follow the pattern:
`qwen-code-ide-server-${PID}-${PORT}.json`
- `${PID}`: The process ID of the parent IDE process. Your plugin must determine this PID and include it in the filename.
- `${PORT}`: The port your MCP server is listening on.
- **File Content & Workspace Validation:** The file **MUST** contain a JSON object with the following structure:
```json
{
"port": 12345,
"workspacePath": "/path/to/project1:/path/to/project2",
"authToken": "a-very-secret-token",
"ideInfo": {
"name": "vscode",
"displayName": "VS Code"
}
}
```
- `port` (number, required): The port of the MCP server.
- `workspacePath` (string, required): A list of all open workspace root paths, delimited by the OS-specific path separator (`:` for Linux/macOS, `;` for Windows). The CLI uses this path to ensure it's running in the same project folder that's open in the IDE. If the CLI's current working directory is not a sub-directory of `workspacePath`, the connection will be rejected. Your plugin **MUST** provide the correct, absolute path(s) to the root of the open workspace(s).
- `authToken` (string, required): A secret token for securing the connection. The CLI will include this token in an `Authorization: Bearer <token>` header on all requests.
- `ideInfo` (object, required): Information about the IDE.
- `name` (string, required): A short, lowercase identifier for the IDE (e.g., `vscode`, `jetbrains`).
- `displayName` (string, required): A user-friendly name for the IDE (e.g., `VS Code`, `JetBrains IDE`).
- **Authentication:** To secure the connection, the plugin **MUST** generate a unique, secret token and include it in the discovery file. The CLI will then include this token in the `Authorization` header for all requests to the MCP server (e.g., `Authorization: Bearer a-very-secret-token`). Your server **MUST** validate this token on every request and reject any that are unauthorized.
- **Tie-Breaking with Environment Variables (Recommended):** For the most reliable experience, your plugin **SHOULD** both create the discovery file and set the `QWEN_CODE_IDE_SERVER_PORT` environment variable in the integrated terminal. The file serves as the primary discovery mechanism, but the environment variable is crucial for tie-breaking. If a user has multiple IDE windows open for the same workspace, the CLI uses the `QWEN_CODE_IDE_SERVER_PORT` variable to identify and connect to the correct window's server.
## II. The Context Interface
To enable context awareness, the plugin **MAY** provide the CLI with real-time information about the user's activity in the IDE.
### `ide/contextUpdate` Notification
The plugin **MAY** send an `ide/contextUpdate` [notification](https://modelcontextprotocol.io/specification/2025-06-18/basic/index#notifications) to the CLI whenever the user's context changes.
- **Triggering Events:** This notification should be sent (with a recommended debounce of 50ms) when:
- A file is opened, closed, or focused.
- The user's cursor position or text selection changes in the active file.
- **Payload (`IdeContext`):** The notification parameters **MUST** be an `IdeContext` object:
```typescript
interface IdeContext {
workspaceState?: {
openFiles?: File[];
isTrusted?: boolean;
};
}
interface File {
// Absolute path to the file
path: string;
// Last focused Unix timestamp (for ordering)
timestamp: number;
// True if this is the currently focused file
isActive?: boolean;
cursor?: {
// 1-based line number
line: number;
// 1-based character number
character: number;
};
// The text currently selected by the user
selectedText?: string;
}
```
**Note:** The `openFiles` list should only include files that exist on disk. Virtual files (e.g., unsaved files without a path, editor settings pages) **MUST** be excluded.
### How the CLI Uses This Context
After receiving the `IdeContext` object, the CLI performs several normalization and truncation steps before sending the information to the model.
- **File Ordering:** The CLI uses the `timestamp` field to determine the most recently used files. It sorts the `openFiles` list based on this value. Therefore, your plugin **MUST** provide an accurate Unix timestamp for when a file was last focused.
- **Active File:** The CLI considers only the most recent file (after sorting) to be the "active" file. It will ignore the `isActive` flag on all other files and clear their `cursor` and `selectedText` fields. Your plugin should focus on setting `isActive: true` and providing cursor/selection details only for the currently focused file.
- **Truncation:** To manage token limits, the CLI truncates both the file list (to 10 files) and the `selectedText` (to 16KB).
While the CLI handles the final truncation, it is highly recommended that your plugin also limits the amount of context it sends.
## III. The Diffing Interface
To enable interactive code modifications, the plugin **MAY** expose a diffing interface. This allows the CLI to request that the IDE open a diff view, showing proposed changes to a file. The user can then review, edit, and ultimately accept or reject these changes directly within the IDE.
### `openDiff` Tool
The plugin **MUST** register an `openDiff` tool on its MCP server.
- **Description:** This tool instructs the IDE to open a modifiable diff view for a specific file.
- **Request (`OpenDiffRequest`):** The tool is invoked via a `tools/call` request. The `arguments` field within the request's `params` **MUST** be an `OpenDiffRequest` object.
```typescript
interface OpenDiffRequest {
// The absolute path to the file to be diffed.
filePath: string;
// The proposed new content for the file.
newContent: string;
}
```
- **Response (`CallToolResult`):** The tool **MUST** immediately return a `CallToolResult` to acknowledge the request and report whether the diff view was successfully opened.
- On Success: If the diff view was opened successfully, the response **MUST** contain empty content (i.e., `content: []`).
- On Failure: If an error prevented the diff view from opening, the response **MUST** have `isError: true` and include a `TextContent` block in the `content` array describing the error.
The actual outcome of the diff (acceptance or rejection) is communicated asynchronously via notifications.
### `closeDiff` Tool
The plugin **MUST** register a `closeDiff` tool on its MCP server.
- **Description:** This tool instructs the IDE to close an open diff view for a specific file.
- **Request (`CloseDiffRequest`):** The tool is invoked via a `tools/call` request. The `arguments` field within the request's `params` **MUST** be an `CloseDiffRequest` object.
```typescript
interface CloseDiffRequest {
// The absolute path to the file whose diff view should be closed.
filePath: string;
}
```
- **Response (`CallToolResult`):** The tool **MUST** return a `CallToolResult`.
- On Success: If the diff view was closed successfully, the response **MUST** include a single **TextContent** block in the content array containing the file's final content before closing.
- On Failure: If an error prevented the diff view from closing, the response **MUST** have `isError: true` and include a `TextContent` block in the `content` array describing the error.
### `ide/diffAccepted` Notification
When the user accepts the changes in a diff view (e.g., by clicking an "Apply" or "Save" button), the plugin **MUST** send an `ide/diffAccepted` notification to the CLI.
- **Payload:** The notification parameters **MUST** include the file path and the final content of the file. The content may differ from the original `newContent` if the user made manual edits in the diff view.
```typescript
{
// The absolute path to the file that was diffed.
filePath: string;
// The full content of the file after acceptance.
content: string;
}
```
### `ide/diffRejected` Notification
When the user rejects the changes (e.g., by closing the diff view without accepting), the plugin **MUST** send an `ide/diffRejected` notification to the CLI.
- **Payload:** The notification parameters **MUST** include the file path of the rejected diff.
```typescript
{
// The absolute path to the file that was diffed.
filePath: string;
}
```
## IV. The Lifecycle Interface
The plugin **MUST** manage its resources and the discovery file correctly based on the IDE's lifecycle.
- **On Activation (IDE startup/plugin enabled):**
1. Start the MCP server.
2. Create the discovery file.
- **On Deactivation (IDE shutdown/plugin disabled):**
1. Stop the MCP server.
2. Delete the discovery file.

View File

@@ -0,0 +1,144 @@
# IDE Integration
Qwen Code can integrate with your IDE to provide a more seamless and context-aware experience. This integration allows the CLI to understand your workspace better and enables powerful features like native in-editor diffing.
Currently, the only supported IDE is [Visual Studio Code](https://code.visualstudio.com/) and other editors that support VS Code extensions. To build support for other editors, see the [IDE Companion Extension Spec](/users/ide-integration/ide-companion-spec).
## Features
- **Workspace Context:** The CLI automatically gains awareness of your workspace to provide more relevant and accurate responses. This context includes:
- The **10 most recently accessed files** in your workspace.
- Your active cursor position.
- Any text you have selected (up to a 16KB limit; longer selections will be truncated).
- **Native Diffing:** When Qwen suggests code modifications, you can view the changes directly within your IDE's native diff viewer. This allows you to review, edit, and accept or reject the suggested changes seamlessly.
- **VS Code Commands:** You can access Qwen Code features directly from the VS Code Command Palette (`Cmd+Shift+P` or `Ctrl+Shift+P`):
- `Qwen Code: Run`: Starts a new Qwen Code session in the integrated terminal.
- `Qwen Code: Accept Diff`: Accepts the changes in the active diff editor.
- `Qwen Code: Close Diff Editor`: Rejects the changes and closes the active diff editor.
- `Qwen Code: View Third-Party Notices`: Displays the third-party notices for the extension.
## Installation and Setup
There are three ways to set up the IDE integration:
### 1. Automatic Nudge (Recommended)
When you run Qwen Code inside a supported editor, it will automatically detect your environment and prompt you to connect. Answering "Yes" will automatically run the necessary setup, which includes installing the companion extension and enabling the connection.
### 2. Manual Installation from CLI
If you previously dismissed the prompt or want to install the extension manually, you can run the following command inside Qwen Code:
```
/ide install
```
This will find the correct extension for your IDE and install it.
### 3. Manual Installation from a Marketplace
You can also install the extension directly from a marketplace.
- **For Visual Studio Code:** Install from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=qwenlm.qwen-code-vscode-ide-companion).
- **For VS Code Forks:** To support forks of VS Code, the extension is also published on the [Open VSX Registry](https://open-vsx.org/extension/qwenlm/qwen-code-vscode-ide-companion). Follow your editor's instructions for installing extensions from this registry.
> NOTE:
> The "Qwen Code Companion" extension may appear towards the bottom of search results. If you don't see it immediately, try scrolling down or sorting by "Newly Published".
>
> After manually installing the extension, you must run `/ide enable` in the CLI to activate the integration.
## Usage
### Enabling and Disabling
You can control the IDE integration from within the CLI:
- To enable the connection to the IDE, run:
```
/ide enable
```
- To disable the connection, run:
```
/ide disable
```
When enabled, Qwen Code will automatically attempt to connect to the IDE companion extension.
### Checking the Status
To check the connection status and see the context the CLI has received from the IDE, run:
```
/ide status
```
If connected, this command will show the IDE it's connected to and a list of recently opened files it is aware of.
(Note: The file list is limited to 10 recently accessed files within your workspace and only includes local files on disk.)
### Working with Diffs
When you ask Qwen model to modify a file, it can open a diff view directly in your editor.
**To accept a diff**, you can perform any of the following actions:
- Click the **checkmark icon** in the diff editor's title bar.
- Save the file (e.g., with `Cmd+S` or `Ctrl+S`).
- Open the Command Palette and run **Qwen Code: Accept Diff**.
- Respond with `yes` in the CLI when prompted.
**To reject a diff**, you can:
- Click the **'x' icon** in the diff editor's title bar.
- Close the diff editor tab.
- Open the Command Palette and run **Qwen Code: Close Diff Editor**.
- Respond with `no` in the CLI when prompted.
You can also **modify the suggested changes** directly in the diff view before accepting them.
If you select Yes, allow always in the CLI, changes will no longer show up in the IDE as they will be auto-accepted.
## Using with Sandboxing
If you are using Qwen Code within a sandbox, please be aware of the following:
- **On macOS:** The IDE integration requires network access to communicate with the IDE companion extension. You must use a Seatbelt profile that allows network access.
- **In a Docker Container:** If you run Qwen Code inside a Docker (or Podman) container, the IDE integration can still connect to the VS Code extension running on your host machine. The CLI is configured to automatically find the IDE server on `host.docker.internal`. No special configuration is usually required, but you may need to ensure your Docker networking setup allows connections from the container to the host.
## Troubleshooting
If you encounter issues with IDE integration, here are some common error messages and how to resolve them.
### Connection Errors
- **Message:** `🔴 Disconnected: Failed to connect to IDE companion extension for [IDE Name]. Please ensure the extension is running and try restarting your terminal. To install the extension, run /ide install.`
- **Cause:** Qwen Code could not find the necessary environment variables (`QWEN_CODE_IDE_WORKSPACE_PATH` or `QWEN_CODE_IDE_SERVER_PORT`) to connect to the IDE. This usually means the IDE companion extension is not running or did not initialize correctly.
- **Solution:**
1. Make sure you have installed the **Qwen Code Companion** extension in your IDE and that it is enabled.
2. Open a new terminal window in your IDE to ensure it picks up the correct environment.
- **Message:** `🔴 Disconnected: IDE connection error. The connection was lost unexpectedly. Please try reconnecting by running /ide enable`
- **Cause:** The connection to the IDE companion was lost.
- **Solution:** Run `/ide enable` to try and reconnect. If the issue continues, open a new terminal window or restart your IDE.
### Configuration Errors
- **Message:** `🔴 Disconnected: Directory mismatch. Qwen Code is running in a different location than the open workspace in [IDE Name]. Please run the CLI from the same directory as your project's root folder.`
- **Cause:** The CLI's current working directory is outside the folder or workspace you have open in your IDE.
- **Solution:** `cd` into the same directory that is open in your IDE and restart the CLI.
- **Message:** `🔴 Disconnected: To use this feature, please open a workspace folder in [IDE Name] and try again.`
- **Cause:** You have no workspace open in your IDE.
- **Solution:** Open a workspace in your IDE and restart the CLI.
### General Errors
- **Message:** `IDE integration is not supported in your current environment. To use this feature, run Qwen Code in one of these supported IDEs: [List of IDEs]`
- **Cause:** You are running Qwen Code in a terminal or environment that is not a supported IDE.
- **Solution:** Run Qwen Code from the integrated terminal of a supported IDE, like VS Code.
- **Message:** `No installer is available for IDE. Please install the Qwen Code Companion extension manually from the marketplace.`
- **Cause:** You ran `/ide install`, but the CLI does not have an automated installer for your specific IDE.
- **Solution:** Open your IDE's extension marketplace, search for "Qwen Code Companion", and install it manually.

View File

@@ -0,0 +1,282 @@
# Github Actionsqwen-code-action
## Overview
`qwen-code-action` is a GitHub Action that integrates [Qwen Code] into your development workflow via the [Qwen Code CLI]. It acts both as an autonomous agent for critical routine coding tasks, and an on-demand collaborator you can quickly delegate work to.
Use it to perform GitHub pull request reviews, triage issues, perform code analysis and modification, and more using [Qwen Code] conversationally (e.g., `@qwencoder fix this issue`) directly inside your GitHub repositories.
- [qwen-code-action](#qwen-code-action)
- [Overview](#overview)
- [Features](#features)
- [Quick Start](#quick-start)
- [1. Get a Qwen API Key](#1-get-a-qwen-api-key)
- [2. Add it as a GitHub Secret](#2-add-it-as-a-github-secret)
- [3. Update your .gitignore](#3-update-your-gitignore)
- [4. Choose a Workflow](#4-choose-a-workflow)
- [5. Try it out](#5-try-it-out)
- [Workflows](#workflows)
- [Qwen Code Dispatch](#qwen-code-dispatch)
- [Issue Triage](#issue-triage)
- [Pull Request Review](#pull-request-review)
- [Qwen Code CLI Assistant](#qwen-code-cli-assistant)
- [Configuration](#configuration)
- [Inputs](#inputs)
- [Outputs](#outputs)
- [Repository Variables](#repository-variables)
- [Secrets](#secrets)
- [Authentication](#authentication)
- [GitHub Authentication](#github-authentication)
- [Extensions](#extensions)
- [Best Practices](#best-practices)
- [Customization](#customization)
- [Contributing](#contributing)
## Features
- **Automation**: Trigger workflows based on events (e.g. issue opening) or schedules (e.g. nightly).
- **On-demand Collaboration**: Trigger workflows in issue and pull request
comments by mentioning the [Qwen Code CLI] (e.g., `@qwencoder /review`).
- **Extensible with Tools**: Leverage [Qwen Code] models' tool-calling capabilities to
interact with other CLIs like the [GitHub CLI] (`gh`).
- **Customizable**: Use a `QWEN.md` file in your repository to provide
project-specific instructions and context to [Qwen Code CLI].
## Quick Start
Get started with Qwen Code CLI in your repository in just a few minutes:
### 1. Get a Qwen API Key
Obtain your API key from [DashScope] (Alibaba Cloud's AI platform)
### 2. Add it as a GitHub Secret
Store your API key as a secret named `QWEN_API_KEY` in your repository:
- Go to your repository's **Settings > Secrets and variables > Actions**
- Click **New repository secret**
- Name: `QWEN_API_KEY`, Value: your API key
### 3. Update your .gitignore
Add the following entries to your `.gitignore` file:
```gitignore
# qwen-code-cli settings
.qwen/
# GitHub App credentials
gha-creds-*.json
```
### 4. Choose a Workflow
You have two options to set up a workflow:
**Option A: Use setup command (Recommended)**
1. Start the Qwen Code CLI in your terminal:
```shell
qwen
```
2. In Qwen Code CLI in your terminal, type:
```
/setup-github
```
**Option B: Manually copy workflows**
1. Copy the pre-built workflows from the [`examples/workflows`](./examples/workflows) directory to your repository's `.github/workflows` directory. Note: the `qwen-dispatch.yml` workflow must also be copied, which triggers the workflows to run.
### 5. Try it out
**Pull Request Review:**
- Open a pull request in your repository and wait for automatic review
- Comment `@qwencoder /review` on an existing pull request to manually trigger a review
**Issue Triage:**
- Open an issue and wait for automatic triage
- Comment `@qwencoder /triage` on existing issues to manually trigger triaging
**General AI Assistance:**
- In any issue or pull request, mention `@qwencoder` followed by your request
- Examples:
- `@qwencoder explain this code change`
- `@qwencoder suggest improvements for this function`
- `@qwencoder help me debug this error`
- `@qwencoder write unit tests for this component`
## Workflows
This action provides several pre-built workflows for different use cases. Each workflow is designed to be copied into your repository's `.github/workflows` directory and customized as needed.
### Qwen Code Dispatch
This workflow acts as a central dispatcher for Qwen Code CLI, routing requests to
the appropriate workflow based on the triggering event and the command provided
in the comment. For a detailed guide on how to set up the dispatch workflow, go
to the
[Qwen Code Dispatch workflow documentation](./examples/workflows/qwen-dispatch).
### Issue Triage
This action can be used to triage GitHub Issues automatically or on a schedule.
For a detailed guide on how to set up the issue triage system, go to the
[GitHub Issue Triage workflow documentation](./examples/workflows/issue-triage).
### Pull Request Review
This action can be used to automatically review pull requests when they are
opened. For a detailed guide on how to set up the pull request review system,
go to the [GitHub PR Review workflow documentation](./examples/workflows/pr-review).
### Qwen Code CLI Assistant
This type of action can be used to invoke a general-purpose, conversational Qwen Code
AI assistant within the pull requests and issues to perform a wide range of
tasks. For a detailed guide on how to set up the general-purpose Qwen Code CLI workflow,
go to the [Qwen Code Assistant workflow documentation](./examples/workflows/qwen-assistant).
## Configuration
### Inputs
<!-- BEGIN_AUTOGEN_INPUTS -->
- <a name="__input_qwen_api_key"></a><a href="#user-content-__input_qwen_api_key"><code>qwen*api_key</code></a>: *(Optional)\_ The API key for the Qwen API.
- <a name="__input_qwen_cli_version"></a><a href="#user-content-__input_qwen_cli_version"><code>qwen*cli_version</code></a>: *(Optional, default: `latest`)\_ The version of the Qwen Code CLI to install. Can be "latest", "preview", "nightly", a specific version number, or a git branch, tag, or commit. For more information, see [Qwen Code CLI releases](https://github.com/QwenLM/qwen-code-action/blob/main/docs/releases.md).
- <a name="__input_qwen_debug"></a><a href="#user-content-__input_qwen_debug"><code>qwen*debug</code></a>: *(Optional)\_ Enable debug logging and output streaming.
- <a name="__input_qwen_model"></a><a href="#user-content-__input_qwen_model"><code>qwen*model</code></a>: *(Optional)\_ The model to use with Qwen Code.
- <a name="__input_prompt"></a><a href="#user-content-__input_prompt"><code>prompt</code></a>: _(Optional, default: `You are a helpful assistant.`)_ A string passed to the Qwen Code CLI's [`--prompt` argument](https://github.com/QwenLM/qwen-code-action/blob/main/docs/cli/configuration.md#command-line-arguments).
- <a name="__input_settings"></a><a href="#user-content-__input_settings"><code>settings</code></a>: _(Optional)_ A JSON string written to `.qwen/settings.json` to configure the CLI's _project_ settings.
For more details, see the documentation on [settings files](https://github.com/QwenLM/qwen-code-action/blob/main/docs/cli/configuration.md#settings-files).
- <a name="__input_use_qwen_code_assist"></a><a href="#user-content-__input_use_qwen_code_assist"><code>use*qwen_code_assist</code></a>: *(Optional, default: `false`)\_ Whether to use Code Assist for Qwen Code model access instead of the default Qwen Code API key.
For more information, see the [Qwen Code CLI documentation](https://github.com/QwenLM/qwen-code-action/blob/main/docs/cli/authentication.md).
- <a name="__input_use_vertex_ai"></a><a href="#user-content-__input_use_vertex_ai"><code>use*vertex_ai</code></a>: *(Optional, default: `false`)\_ Whether to use Vertex AI for Qwen Code model access instead of the default Qwen Code API key.
For more information, see the [Qwen Code CLI documentation](https://github.com/QwenLM/qwen-code-action/blob/main/docs/cli/authentication.md).
- <a name="__input_extensions"></a><a href="#user-content-__input_extensions"><code>extensions</code></a>: _(Optional)_ A list of Qwen Code CLI extensions to install.
- <a name="__input_upload_artifacts"></a><a href="#user-content-__input_upload_artifacts"><code>upload*artifacts</code></a>: *(Optional, default: `false`)\_ Whether to upload artifacts to the github action.
- <a name="__input_use_pnpm"></a><a href="#user-content-__input_use_pnpm"><code>use*pnpm</code></a>: *(Optional, default: `false`)\_ Whether or not to use pnpm instead of npm to install qwen-code-cli
- <a name="__input_workflow_name"></a><a href="#user-content-__input_workflow_name"><code>workflow*name</code></a>: *(Optional, default: `${{ github.workflow }}`)\_ The GitHub workflow name, used for telemetry purposes.
<!-- END_AUTOGEN_INPUTS -->
### Outputs
<!-- BEGIN_AUTOGEN_OUTPUTS -->
- <a name="__output_summary"></a><a href="#user-content-__output_summary"><code>summary</code></a>: The summarized output from the Qwen Code CLI execution.
- <a name="__output_error"></a><a href="#user-content-__output_error"><code>error</code></a>: The error output from the Qwen Code CLI execution, if any.
<!-- END_AUTOGEN_OUTPUTS -->
### Repository Variables
We recommend setting the following values as repository variables so they can be reused across all workflows. Alternatively, you can set them inline as action inputs in individual workflows or to override repository-level values.
| Name | Description | Type | Required | When Required |
| ------------------ | --------------------------------------------------------- | -------- | -------- | ------------------------- |
| `DEBUG` | Enables debug logging for the Qwen Code CLI. | Variable | No | Never |
| `QWEN_CLI_VERSION` | Controls which version of the Qwen Code CLI is installed. | Variable | No | Pinning the CLI version |
| `APP_ID` | GitHub App ID for custom authentication. | Variable | No | Using a custom GitHub App |
To add a repository variable:
1. Go to your repository's **Settings > Secrets and variables > Actions > New variable**.
2. Enter the variable name and value.
3. Save.
For details about repository variables, refer to the [GitHub documentation on variables][variables].
### Secrets
You can set the following secrets in your repository:
| Name | Description | Required | When Required |
| ----------------- | --------------------------------------------- | -------- | ------------------------------------------ |
| `QWEN_API_KEY` | Your Qwen API key from DashScope. | Yes | Required for all workflows that call Qwen. |
| `APP_PRIVATE_KEY` | Private key for your GitHub App (PEM format). | No | Using a custom GitHub App. |
To add a secret:
1. Go to your repository's **Settings > Secrets and variables >Actions > New repository secret**.
2. Enter the secret name and value.
3. Save.
For more information, refer to the
[official GitHub documentation on creating and using encrypted secrets][secrets].
## Authentication
This action requires authentication to the GitHub API and optionally to Qwen Code services.
### GitHub Authentication
You can authenticate with GitHub in two ways:
1. **Default `GITHUB_TOKEN`:** For simpler use cases, the action can use the
default `GITHUB_TOKEN` provided by the workflow.
2. **Custom GitHub App (Recommended):** For the most secure and flexible
authentication, we recommend creating a custom GitHub App.
For detailed setup instructions for both Qwen and GitHub authentication, go to the
[**Authentication documentation**](./docs/authentication.md).
## Extensions
The Qwen Code CLI can be extended with additional functionality through extensions.
These extensions are installed from source from their GitHub repositories.
For detailed instructions on how to set up and configure extensions, go to the
[Extensions documentation](./docs/extensions.md).
## Best Practices
To ensure the security, reliability, and efficiency of your automated workflows, we strongly recommend following our best practices. These guidelines cover key areas such as repository security, workflow configuration, and monitoring.
Key recommendations include:
- **Securing Your Repository:** Implementing branch and tag protection, and restricting pull request approvers.
- **Monitoring and Auditing:** Regularly reviewing action logs and enabling OpenTelemetry for deeper insights into performance and behavior.
For a comprehensive guide on securing your repository and workflows, please refer to our [**Best Practices documentation**](./docs/best-practices.md).
## Customization
Create a [QWEN.md] file in the root of your repository to provide
project-specific context and instructions to [Qwen Code CLI]. This is useful for defining
coding conventions, architectural patterns, or other guidelines the model should
follow for a given repository.
## Contributing
Contributions are welcome! Check out the Qwen Code CLI
[**Contributing Guide**](./CONTRIBUTING.md) for more details on how to get
started.
[secrets]: https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions
[Qwen Code]: https://github.com/QwenLM/qwen-code
[DashScope]: https://dashscope.console.aliyun.com/apiKey
[Qwen Code CLI]: https://github.com/QwenLM/qwen-code-action/
[variables]: https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-variables#creating-configuration-variables-for-a-repository
[GitHub CLI]: https://docs.github.com/en/github-cli/github-cli
[QWEN.md]: https://github.com/QwenLM/qwen-code-action/blob/main/docs/cli/configuration.md#context-files-hierarchical-instructional-context

View File

@@ -0,0 +1,45 @@
# Visual Studio Code
> The VS Code extension (Beta) lets you see Qwen's changes in real-time through a native graphical interface integrated directly into your IDE, making it easier to access and interact with Qwen Code.
<br/>
<video src="https://cloud.video.taobao.com/vod/JnvYMhUia2EKFAaiuErqNpzWE9mz3odG76vArAHNg94.mp4" controls width="800">
Your browser does not support the video tag.
</video>
### Features
- **Native IDE experience**: Dedicated Qwen Code sidebar panel accessed via the Qwen icon
- **Auto-accept edits mode**: Automatically apply Qwen's changes as they're made
- **File management**: @-mention files or attach files and images using the system file picker
- **Conversation history**: Access to past conversations
- **Multiple sessions**: Run multiple Qwen Code sessions simultaneously
### Requirements
- VS Code 1.98.0 or higher
### Installation
1. Install Qwen Code CLI:
```bash
npm install -g qwen-code
```
2. Download and install the extension from the [Visual Studio Code Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=qwenlm.qwen-code-vscode-ide-companion).
## Troubleshooting
### Extension not installing
- Ensure you have VS Code 1.98.0 or higher
- Check that VS Code has permission to install extensions
- Try installing directly from the Marketplace website
### Qwen Code not responding
- Check your internet connection
- Start a new conversation to see if the issue persists
- [File an issue on GitHub](https://github.com/qwenlm/qwen-code/issues) if the problem continues

View File

@@ -0,0 +1,54 @@
# Zed Editor
> Zed Editor provides native support for AI coding assistants through the Agent Control Protocol (ACP). This integration allows you to use Qwen Code directly within Zed's interface with real-time code suggestions.
![Zed Editor Overview](https://img.alicdn.com/imgextra/i1/O1CN01aAhU311GwEoNh27FP_!!6000000000686-2-tps-3024-1898.png)
### Features
- **Native agent experience**: Integrated AI assistant panel within Zed's interface
- **Agent Control Protocol**: Full support for ACP enabling advanced IDE interactions
- **File management**: @-mention files to add them to the conversation context
- **Conversation history**: Access to past conversations within Zed
### Requirements
- Zed Editor (latest version recommended)
- Qwen Code CLI installed
### Installation
1. Install Qwen Code CLI:
```bash
npm install -g qwen-code
```
2. Download and install [Zed Editor](https://zed.dev/)
3. In Zed, click the **settings button** in the top right corner, select **"Add agent"**, choose **"Create a custom agent"**, and add the following configuration:
```json
"Qwen Code": {
"type": "custom",
"command": "qwen",
"args": ["--experimental-acp"],
"env": {}
}
```
![Qwen Code Integration](https://img.alicdn.com/imgextra/i1/O1CN013s61L91dSE1J7MTgO_!!6000000003734-2-tps-2592-1234.png)
## Troubleshooting
### Agent not appearing
- Run `qwen --version` in terminal to verify installation
- Check that the JSON configuration is valid
- Restart Zed Editor
### Qwen Code not responding
- Check your internet connection
- Verify CLI works by running `qwen` in terminal
- [File an issue on GitHub](https://github.com/qwenlm/qwen-code/issues) if the problem persists

62
docs/users/overview.md Normal file
View File

@@ -0,0 +1,62 @@
# Qwen Code overview
> Learn about Qwen Code, Qwen's agentic coding tool that lives in your terminal and helps you turn ideas into code faster than ever before.
## Get started in 30 seconds
Prerequisites:
- A [Qwen Code](https://chat.qwen.ai/auth?mode=register) account
- Requires [Node.js 20+](https://nodejs.org/zh-cn/download), you can use `node -v` to check the version. If it's not installed, use the following command to install it.
### Install Qwen Code:
**NPM**(recommended)
```bash
npm install -g @qwen-code/qwen-code@latest
```
**Homebrew**(macOS, Linux)
```bash
brew install qwen-code
```
### Start using Qwen Code:
```bash
cd your-project
qwen
```
Select **Qwen OAuth (Free)** authentication and follow the prompts to log in. Then let's start with understanding your codebase. Try one of these commands:
```
what does this project do?
```
![](https://gw.alicdn.com/imgextra/i2/O1CN01XoPbZm1CrsZzvMQ6m_!!6000000000135-1-tps-772-646.gif)
You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 mins) →](/users/quickstart)
> [!tip]
>
> See [troubleshooting](/users/support/troubleshooting) if you hit issues.
> [!note]
>
> **New VS Code Extension (Beta)**: Prefer a graphical interface? Our new **VS Code extension** provides an easy-to-use native IDE experience without requiring terminal familiarity. Simply install from the marketplace and start coding with Qwen Code directly in your sidebar. You can search for **Qwen Code** in the VS Code Marketplace and download it.
## What Qwen Code does for you
- **Build features from descriptions**: Tell Qwen Code what you want to build in plain language. It will make a plan, write the code, and ensure it works.
- **Debug and fix issues**: Describe a bug or paste an error message. Qwen Code will analyze your codebase, identify the problem, and implement a fix.
- **Navigate any codebase**: Ask anything about your team's codebase, and get a thoughtful answer back. Qwen Code maintains awareness of your entire project structure, can find up-to-date information from the web, and with [MCP](/users/features/mcp) can pull from external datasources like Google Drive, Figma, and Slack.
- **Automate tedious tasks**: Fix fiddly lint issues, resolve merge conflicts, and write release notes. Do all this in a single command from your developer machines, or automatically in CI.
## Why developers love Qwen Code
- **Works in your terminal**: Not another chat window. Not another IDE. Qwen Code meets you where you already work, with the tools you already love.
- **Takes action**: Qwen Code can directly edit files, run commands, and create commits. Need more? [MCP](/users/features/mcp) lets Qwen Code read your design docs in Google Drive, update your tickets in Jira, or use _your_ custom developer tooling.
- **Unix philosophy**: Qwen Code is composable and scriptable. `tail -f app.log | qwen -p "Slack me if you see any anomalies appear in this log stream"` _works_. Your CI can run `qwen -p "If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review"`.

251
docs/users/quickstart.md Normal file
View File

@@ -0,0 +1,251 @@
# Quickstart
> 👏 Welcome to Qwen Code!
This quickstart guide will have you using AI-powered coding assistance in just a few minutes. By the end, you'll understand how to use Qwen Code for common development tasks.
## Before you begin
Make sure you have:
- A **terminal** or command prompt open
- A code project to work with
- A [Qwen Code](https://chat.qwen.ai/auth?mode=register) account
## Step 1: Install Qwen Code
To install Qwen Code, use one of the following methods:
### NPM (recommended)
Requires [Node.js 20+](https://nodejs.org/download), you can use `node -v` check the version. If it's not installed, use the following command to install it.
If you have [Node.js or newer installed](https://nodejs.org/en/download/):
```sh
npm install -g @qwen-code/qwen-code@latest
```
### Homebrew (macOS, Linux)
```sh
brew install qwen-code
```
## Step 2: Log in to your account
Qwen Code requires an account to use. When you start an interactive session with the `qwen` command, you'll need to log in:
```bash
# You'll be prompted to log in on first use
qwen
```
```bash
# Follow the prompts to log in with your account
/auth
```
Select `Qwen OAuth`, log in to your account and follow the prompts to confirm. Once logged in, your credentials are stored and you won't need to log in again.
> [!note]
>
> When you first authenticate Qwen Code with your Qwen account, a workspace called ".qwen" is automatically created for you. This workspace provides centralized cost tracking and management for all Qwen Code usage in your organization.
> [!tip]
>
> If you need to log in again or switch accounts, use the `/auth` command within Qwen Code.
## Step 3: Start your first session
Open your terminal in any project directory and start Qwen Code:
```bash
# optiona
cd /path/to/your/project
# start qwen
qwen
```
You'll see the Qwen Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands.
## Chat with Qwen Code
### Ask your first question
Qwen Code will analyze your files and provide a summary. You can also ask more specific questions:
```
explain the folder structure
```
You can also ask Qwen Code about its own capabilities:
```
what can Qwen Code do?
```
> [!note]
>
> Qwen Code reads your files as needed - you don't have to manually add context. Qwen Code also has access to its own documentation and can answer questions about its features and capabilities.
### Make your first code change
Now let's make Qwen Code do some actual coding. Try a simple task:
```
add a hello world function to the main file
```
Qwen Code will:
1. Find the appropriate file
2. Show you the proposed changes
3. Ask for your approval
4. Make the edit
> [!note]
>
> Qwen Code always asks for permission before modifying files. You can approve individual changes or enable "Accept all" mode for a session.
### Use Git with Qwen Code
Qwen Code makes Git operations conversational:
```
what files have I changed?
```
```
commit my changes with a descriptive message
```
You can also prompt for more complex Git operations:
```
create a new branch called feature/quickstart
```
```
show me the last 5 commits
```
```
help me resolve merge conflicts
```
### Fix a bug or add a feature
Qwen Code is proficient at debugging and feature implementation.
Describe what you want in natural language:
```
add input validation to the user registration form
```
Or fix existing issues:
```
there's a bug where users can submit empty forms - fix it
```
Qwen Code will:
- Locate the relevant code
- Understand the context
- Implement a solution
- Run tests if available
### Test out other common workflows
There are a number of ways to work with Claude:
**Refactor code**
```
refactor the authentication module to use async/await instead of callbacks
```
**Write tests**
```
write unit tests for the calculator functions
```
**Update documentation**
```
update the README with installation instructions
```
**Code review**
```
review my changes and suggest improvements
```
> [!tip]
>
> **Remember**: Qwen Code is your AI pair programmer. Talk to it like you would a helpful colleague - describe what you want to achieve, and it will help you get there.
## Essential commands
Here are the most important commands for daily use:
| Command | What it does | Example |
| --------------------- | ------------------------------------------------ | ----------------------------- |
| `qwen` | start Qwen Code | `qwen` |
| `/auth` | Change authentication method | `/auth` |
| `/help` | Display help information for available commands | `/help` or `/?` |
| `/compress` | Replace chat history with summary to save Tokens | `/compress` |
| `/clear` | Clear terminal screen content | `/clear` (shortcut: `Ctrl+L`) |
| `/theme` | Change Qwen Code visual theme | `/theme` |
| `/language` | View or change language settings | `/language` |
| → `ui [language]` | Set UI interface language | `/language ui zh-CN` |
| → `output [language]` | Set LLM output language | `/language output Chinese` |
| `/quit` | Exit Qwen Code immediately | `/quit` or `/exit` |
See the [CLI reference](/users/reference/cli-reference) for a complete list of commands.
## Pro tips for beginners
**Be specific with your requests**
- Instead of: "fix the bug"
- Try: "fix the login bug where users see a blank screen after entering wrong credentials"
**Use step-by-step instructions**
- Break complex tasks into steps:
```
1. create a new database table for user profiles
2. create an API endpoint to get and update user profiles
3. build a webpage that allows users to see and edit their information
```
**Let Claude explore first**
- Before making changes, let Claude understand your code:
```
analyze the database schema
```
```
build a dashboard showing products that are most frequently returned by our UK customers
```
**Save time with shortcuts**
- Press `?` to see all available keyboard shortcuts
- Use Tab for command completion
- Press ↑ for command history
- Type `/` to see all slash commands
## Getting help
- **In Qwen Code**: Type `/help` or ask "how do I..."
- **Documentation**: You're here! Browse other guides
- **Community**: Join our [GitHub Discussion](https://github.com/QwenLM/qwen-code/discussions) for tips and support

View File

@@ -0,0 +1,3 @@
export default {
'keyboard-shortcuts': 'Keyboard Shortcuts',
};

View File

@@ -0,0 +1,69 @@
# Qwen Code Keyboard Shortcuts
This document lists the available keyboard shortcuts in Qwen Code.
## General
| Shortcut | Description |
| ----------- | --------------------------------------------------------------------------------------------------------------------- |
| `Esc` | Close dialogs and suggestions. |
| `Ctrl+C` | Cancel the ongoing request and clear the input. Press twice to exit the application. |
| `Ctrl+D` | Exit the application if the input is empty. Press twice to confirm. |
| `Ctrl+L` | Clear the screen. |
| `Ctrl+O` | Toggle the display of the debug console. |
| `Ctrl+S` | Allows long responses to print fully, disabling truncation. Use your terminal's scrollback to view the entire output. |
| `Ctrl+T` | Toggle the display of tool descriptions. |
| `Shift+Tab` | Cycle approval modes (`plan``default``auto-edit``yolo`). |
## Input Prompt
| Shortcut | Description |
| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `!` | Toggle shell mode when the input is empty. |
| `\` (at end of line) + `Enter` | Insert a newline. |
| `Down Arrow` | Navigate down through the input history. |
| `Enter` | Submit the current prompt. |
| `Meta+Delete` / `Ctrl+Delete` | Delete the word to the right of the cursor. |
| `Tab` | Autocomplete the current suggestion if one exists. |
| `Up Arrow` | Navigate up through the input history. |
| `Ctrl+A` / `Home` | Move the cursor to the beginning of the line. |
| `Ctrl+B` / `Left Arrow` | Move the cursor one character to the left. |
| `Ctrl+C` | Clear the input prompt |
| `Esc` (double press) | Clear the input prompt. |
| `Ctrl+D` / `Delete` | Delete the character to the right of the cursor. |
| `Ctrl+E` / `End` | Move the cursor to the end of the line. |
| `Ctrl+F` / `Right Arrow` | Move the cursor one character to the right. |
| `Ctrl+H` / `Backspace` | Delete the character to the left of the cursor. |
| `Ctrl+K` | Delete from the cursor to the end of the line. |
| `Ctrl+Left Arrow` / `Meta+Left Arrow` / `Meta+B` | Move the cursor one word to the left. |
| `Ctrl+N` | Navigate down through the input history. |
| `Ctrl+P` | Navigate up through the input history. |
| `Ctrl+Right Arrow` / `Meta+Right Arrow` / `Meta+F` | Move the cursor one word to the right. |
| `Ctrl+U` | Delete from the cursor to the beginning of the line. |
| `Ctrl+V` | Paste clipboard content. If the clipboard contains an image, it will be saved and a reference to it will be inserted in the prompt. |
| `Ctrl+W` / `Meta+Backspace` / `Ctrl+Backspace` | Delete the word to the left of the cursor. |
| `Ctrl+X` / `Meta+Enter` | Open the current input in an external editor. |
## Suggestions
| Shortcut | Description |
| --------------- | -------------------------------------- |
| `Down Arrow` | Navigate down through the suggestions. |
| `Tab` / `Enter` | Accept the selected suggestion. |
| `Up Arrow` | Navigate up through the suggestions. |
## Radio Button Select
| Shortcut | Description |
| ------------------ | ------------------------------------------------------------------------------------------------------------- |
| `Down Arrow` / `j` | Move selection down. |
| `Enter` | Confirm selection. |
| `Up Arrow` / `k` | Move selection up. |
| `1-9` | Select an item by its number. |
| (multi-digit) | For items with numbers greater than 9, press the digits in quick succession to select the corresponding item. |
## IDE Integration
| Shortcut | Description |
| -------- | --------------------------------- |
| `Ctrl+G` | See context CLI received from IDE |

View File

@@ -0,0 +1,42 @@
# Uninstall
Your uninstall method depends on how you ran the CLI. Follow the instructions for either npx or a global npm installation.
## Method 1: Using npx
npx runs packages from a temporary cache without a permanent installation. To "uninstall" the CLI, you must clear this cache, which will remove qwen-code and any other packages previously executed with npx.
The npx cache is a directory named `_npx` inside your main npm cache folder. You can find your npm cache path by running `npm config get cache`.
**For macOS / Linux**
```bash
# The path is typically ~/.npm/_npx
rm -rf "$(npm config get cache)/_npx"
```
**For Windows**
_Command Prompt_
```cmd
:: The path is typically %LocalAppData%\npm-cache\_npx
rmdir /s /q "%LocalAppData%\npm-cache\_npx"
```
_PowerShell_
```powershell
# The path is typically $env:LocalAppData\npm-cache\_npx
Remove-Item -Path (Join-Path $env:LocalAppData "npm-cache\_npx") -Recurse -Force
```
## Method 2: Using npm (Global Install)
If you installed the CLI globally (e.g. `npm install -g @qwen-code/qwen-code`), use the `npm uninstall` command with the `-g` flag to remove it.
```bash
npm uninstall -g @qwen-code/qwen-code
```
This command completely removes the package from your system.

View File

@@ -0,0 +1,6 @@
export default {
troubleshooting: 'Troubleshooting',
'tos-privacy': 'Terms of Service',
Uninstall: 'Uninstall',
};

View File

@@ -0,0 +1,94 @@
# Qwen Code: Terms of Service and Privacy Notice
Qwen Code is an open-source AI coding assistant tool maintained by the Qwen Code team. This document outlines the terms of service and privacy policies that apply when using Qwen Code's authentication methods and AI model services.
## How to determine your authentication method
Qwen Code supports two main authentication methods to access AI models. Your authentication method determines which terms of service and privacy policies apply to your usage:
1. **Qwen OAuth** - Log in with your qwen.ai account
2. **OpenAI-Compatible API** - Use API keys from various AI model providers
For each authentication method, different Terms of Service and Privacy Notices may apply depending on the underlying service provider.
| Authentication Method | Provider | Terms of Service | Privacy Notice |
| :-------------------- | :---------------- | :---------------------------------------------------------------------------- | :--------------------------------------------------- |
| Qwen OAuth | Qwen AI | [Qwen Terms of Service](https://qwen.ai/termsservice) | [Qwen Privacy Policy](https://qwen.ai/privacypolicy) |
| OpenAI-Compatible API | Various Providers | Depends on your chosen API provider (OpenAI, Alibaba Cloud, ModelScope, etc.) | Depends on your chosen API provider |
## 1. If you are using Qwen OAuth Authentication
When you authenticate using your qwen.ai account, these Terms of Service and Privacy Notice documents apply:
- **Terms of Service:** Your use is governed by the [Qwen Terms of Service](https://qwen.ai/termsservice).
- **Privacy Notice:** The collection and use of your data is described in the [Qwen Privacy Policy](https://qwen.ai/privacypolicy).
For details about authentication setup, quotas, and supported features, see [Authentication Setup](/users/configuration/settings).
## 2. If you are using OpenAI-Compatible API Authentication
When you authenticate using API keys from OpenAI-compatible providers, the applicable Terms of Service and Privacy Notice depend on your chosen provider.
> [!important]
>
> When using OpenAI-compatible API authentication, you are subject to the terms and privacy policies of your chosen API provider, not Qwen Code's terms. Please review your provider's documentation for specific details about data usage, retention, and privacy practices.
Qwen Code supports various OpenAI-compatible providers. Please refer to your specific provider's terms of service and privacy policy for detailed information.
## Usage Statistics and Telemetry
Qwen Code may collect anonymous usage statistics and [telemetry](/developers/development/telemetry) data to improve the user experience and product quality. This data collection is optional and can be controlled through configuration settings.
### What Data is Collected
When enabled, Qwen Code may collect:
- Anonymous usage statistics (commands run, performance metrics)
- Error reports and crash data
- Feature usage patterns
### Data Collection by Authentication Method
- **Qwen OAuth:** Usage statistics are governed by Qwen's privacy policy. You can opt-out through Qwen Code's configuration settings.
- **OpenAI-Compatible API:** No additional data is collected by Qwen Code beyond what your chosen API provider collects.
## Frequently Asked Questions (FAQ)
### 1. Is my code, including prompts and answers, used to train AI models?
Whether your code, including prompts and answers, is used to train AI models depends on your authentication method and the specific AI service provider you use:
- **Qwen OAuth**: Data usage is governed by [Qwen's Privacy Policy](https://qwen.ai/privacy). Please refer to their policy for specific details about data collection and model training practices.
- **OpenAI-Compatible API**: Data usage depends entirely on your chosen API provider. Each provider has their own data usage policies. Please review the privacy policy and terms of service of your specific provider.
**Important**: Qwen Code itself does not use your prompts, code, or responses for model training. Any data usage for training purposes would be governed by the policies of the AI service provider you authenticate with.
### 2. What are Usage Statistics and what does the opt-out control?
The **Usage Statistics** setting controls optional data collection by Qwen Code for improving the user experience and product quality.
When enabled, Qwen Code may collect:
- Anonymous telemetry (commands run, performance metrics, feature usage)
- Error reports and crash data
- General usage patterns
**What is NOT collected by Qwen Code:**
- Your code content
- Prompts sent to AI models
- Responses from AI models
- Personal information
The Usage Statistics setting only controls data collection by Qwen Code itself. It does not affect what data your chosen AI service provider (Qwen, OpenAI, etc.) may collect according to their own privacy policies.
### 3. How do I switch between authentication methods?
You can switch between Qwen OAuth and OpenAI-compatible API authentication at any time:
1. **During startup**: Choose your preferred authentication method when prompted
2. **Within the CLI**: Use the `/auth` command to reconfigure your authentication method
3. **Environment variables**: Set up `.env` files for automatic OpenAI-compatible API authentication
For detailed instructions, see the [Authentication Setup](/users/configuration/settings#environment-variables-for-api-access) documentation.

View File

@@ -0,0 +1,116 @@
# Troubleshooting
This guide provides solutions to common issues and debugging tips, including topics on:
- Authentication or login errors
- Frequently asked questions (FAQs)
- Debugging tips
- Existing GitHub Issues similar to yours or creating new Issues
## Authentication or login errors
- **Error: `UNABLE_TO_GET_ISSUER_CERT_LOCALLY` or `unable to get local issuer certificate`**
- **Cause:** You may be on a corporate network with a firewall that intercepts and inspects SSL/TLS traffic. This often requires a custom root CA certificate to be trusted by Node.js.
- **Solution:** Set the `NODE_EXTRA_CA_CERTS` environment variable to the absolute path of your corporate root CA certificate file.
- Example: `export NODE_EXTRA_CA_CERTS=/path/to/your/corporate-ca.crt`
- **Issue: Unable to display UI after authentication failure**
- **Cause:** If authentication fails after selecting an authentication type, the `security.auth.selectedType` setting may be persisted in `settings.json`. On restart, the CLI may get stuck trying to authenticate with the failed auth type and fail to display the UI.
- **Solution:** Clear the `security.auth.selectedType` configuration item in your `settings.json` file:
- Open `~/.qwen/settings.json` (or `./.qwen/settings.json` for project-specific settings)
- Remove the `security.auth.selectedType` field
- Restart the CLI to allow it to prompt for authentication again
## Frequently asked questions (FAQs)
- **Q: How do I update Qwen Code to the latest version?**
- A: If you installed it globally via `npm`, update it using the command `npm install -g @qwen-code/qwen-code@latest`. If you compiled it from source, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
- **Q: Where are the Qwen Code configuration or settings files stored?**
- A: The Qwen Code configuration is stored in two `settings.json` files:
1. In your home directory: `~/.qwen/settings.json`.
2. In your project's root directory: `./.qwen/settings.json`.
Refer to [Qwen Code Configuration](/users/configuration/settings) for more details.
- **Q: Why don't I see cached token counts in my stats output?**
- A: Cached token information is only displayed when cached tokens are being used. This feature is available for API key users (Qwen API key or Google Cloud Vertex AI) but not for OAuth users (such as Google Personal/Enterprise accounts like Google Gmail or Google Workspace, respectively). This is because the Qwen Code Assist API does not support cached content creation. You can still view your total token usage using the `/stats` command.
## Common error messages and solutions
- **Error: `EADDRINUSE` (Address already in use) when starting an MCP server.**
- **Cause:** Another process is already using the port that the MCP server is trying to bind to.
- **Solution:**
Either stop the other process that is using the port or configure the MCP server to use a different port.
- **Error: Command not found (when attempting to run Qwen Code with `qwen`).**
- **Cause:** The CLI is not correctly installed or it is not in your system's `PATH`.
- **Solution:**
The update depends on how you installed Qwen Code:
- If you installed `qwen` globally, check that your `npm` global binary directory is in your `PATH`. You can update using the command `npm install -g @qwen-code/qwen-code@latest`.
- If you are running `qwen` from source, ensure you are using the correct command to invoke it (e.g. `node packages/cli/dist/index.js ...`). To update, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
- **Error: `MODULE_NOT_FOUND` or import errors.**
- **Cause:** Dependencies are not installed correctly, or the project hasn't been built.
- **Solution:**
1. Run `npm install` to ensure all dependencies are present.
2. Run `npm run build` to compile the project.
3. Verify that the build completed successfully with `npm run start`.
- **Error: "Operation not permitted", "Permission denied", or similar.**
- **Cause:** When sandboxing is enabled, Qwen Code may attempt operations that are restricted by your sandbox configuration, such as writing outside the project directory or system temp directory.
- **Solution:** Refer to the [Configuration: Sandboxing](/users/features/sandbox) documentation for more information, including how to customize your sandbox configuration.
- **Qwen Code is not running in interactive mode in "CI" environments**
- **Issue:** Qwen Code does not enter interactive mode (no prompt appears) if an environment variable starting with `CI_` (e.g. `CI_TOKEN`) is set. This is because the `is-in-ci` package, used by the underlying UI framework, detects these variables and assumes a non-interactive CI environment.
- **Cause:** The `is-in-ci` package checks for the presence of `CI`, `CONTINUOUS_INTEGRATION`, or any environment variable with a `CI_` prefix. When any of these are found, it signals that the environment is non-interactive, which prevents the CLI from starting in its interactive mode.
- **Solution:** If the `CI_` prefixed variable is not needed for the CLI to function, you can temporarily unset it for the command. e.g. `env -u CI_TOKEN qwen`
- **DEBUG mode not working from project .env file**
- **Issue:** Setting `DEBUG=true` in a project's `.env` file doesn't enable debug mode for the CLI.
- **Cause:** The `DEBUG` and `DEBUG_MODE` variables are automatically excluded from project `.env` files to prevent interference with the CLI behavior.
- **Solution:** Use a `.qwen/.env` file instead, or configure the `advanced.excludedEnvVars` setting in your `settings.json` to exclude fewer variables.
## IDE Companion not connecting
- Ensure VS Code has a single workspace folder open.
- Restart the integrated terminal after installing the extension so it inherits:
- `QWEN_CODE_IDE_WORKSPACE_PATH`
- `QWEN_CODE_IDE_SERVER_PORT`
- If running in a container, verify `host.docker.internal` resolves. Otherwise, map the host appropriately.
- Reinstall the companion with `/ide install` and use “Qwen Code: Run” in the Command Palette to verify it launches.
## Exit Codes
The Qwen Code uses specific exit codes to indicate the reason for termination. This is especially useful for scripting and automation.
| Exit Code | Error Type | Description |
| --------- | -------------------------- | --------------------------------------------------------------------------------------------------- |
| 41 | `FatalAuthenticationError` | An error occurred during the authentication process. |
| 42 | `FatalInputError` | Invalid or missing input was provided to the CLI. (non-interactive mode only) |
| 44 | `FatalSandboxError` | An error occurred with the sandboxing environment (e.g. Docker, Podman, or Seatbelt). |
| 52 | `FatalConfigError` | A configuration file (`settings.json`) is invalid or contains errors. |
| 53 | `FatalTurnLimitedError` | The maximum number of conversational turns for the session was reached. (non-interactive mode only) |
## Debugging Tips
- **CLI debugging:**
- Use the `--verbose` flag (if available) with CLI commands for more detailed output.
- Check the CLI logs, often found in a user-specific configuration or cache directory.
- **Core debugging:**
- Check the server console output for error messages or stack traces.
- Increase log verbosity if configurable.
- Use Node.js debugging tools (e.g. `node --inspect`) if you need to step through server-side code.
- **Tool issues:**
- If a specific tool is failing, try to isolate the issue by running the simplest possible version of the command or operation the tool performs.
- For `run_shell_command`, check that the command works directly in your shell first.
- For _file system tools_, verify that paths are correct and check the permissions.
- **Pre-flight checks:**
- Always run `npm run preflight` before committing code. This can catch many common issues related to formatting, linting, and type errors.
## Existing GitHub Issues similar to yours or creating new Issues
If you encounter an issue that was not covered here in this _Troubleshooting guide_, consider searching the Qwen Code [Issue tracker on GitHub](https://github.com/QwenLM/qwen-code/issues). If you can't find an issue similar to yours, consider creating a new GitHub Issue with a detailed description. Pull requests are also welcome!