Merge branch 'main' into 1179-add-resume-cmd

This commit is contained in:
tanzhenxin
2025-12-16 15:29:58 +08:00
180 changed files with 6068 additions and 5534 deletions

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,265 @@
# 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 |
| ----------- | --------------------------------------------------------- | ------------------------------------ |
| `/init` | Analyze current directory and create initial context file | `/init` |
| `/summary` | Generate project summary based on conversation history | `/summary` |
| `/compress` | Replace chat history with summary to save Tokens | `/compress` |
| `/resume` | Resume a previous conversation session | `/resume` |
| `/restore` | Restore files to state before tool execution | `/restore` (list) or `/restore <ID>` |
### 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.