mirror of
https://github.com/QwenLM/qwen-code.git
synced 2025-12-22 01:37:50 +00:00
feat: restructure docs
This commit is contained in:
8
docs/users/features/_meta.ts
Normal file
8
docs/users/features/_meta.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export default {
|
||||
subagents: 'Subagents',
|
||||
checkpointing: 'Checkpointing',
|
||||
sandbox: 'Sandbox Support',
|
||||
headless: 'Headless Mode',
|
||||
'welcome-back': 'Welcome Back',
|
||||
'token-caching': 'Token Caching',
|
||||
};
|
||||
77
docs/users/features/checkpointing.md
Normal file
77
docs/users/features/checkpointing.md
Normal 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.
|
||||
307
docs/users/features/headless.md
Normal file
307
docs/users/features/headless.md
Normal file
@@ -0,0 +1,307 @@
|
||||
# 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.
|
||||
|
||||
- [Headless Mode](#headless-mode)
|
||||
- [Overview](#overview)
|
||||
- [Basic Usage](#basic-usage)
|
||||
- [Direct Prompts](#direct-prompts)
|
||||
- [Stdin Input](#stdin-input)
|
||||
- [Combining with File Input](#combining-with-file-input)
|
||||
- [Output Formats](#output-formats)
|
||||
- [Text Output (Default)](#text-output-default)
|
||||
- [JSON Output](#json-output)
|
||||
- [Example Usage](#example-usage)
|
||||
- [Stream-JSON Output](#stream-json-output)
|
||||
- [Input Format](#input-format)
|
||||
- [File Redirection](#file-redirection)
|
||||
- [Configuration Options](#configuration-options)
|
||||
- [Examples](#examples)
|
||||
- [Code review](#code-review)
|
||||
- [Generate commit messages](#generate-commit-messages)
|
||||
- [API documentation](#api-documentation)
|
||||
- [Batch code analysis](#batch-code-analysis)
|
||||
- [PR code review](#pr-code-review)
|
||||
- [Log analysis](#log-analysis)
|
||||
- [Release notes generation](#release-notes-generation)
|
||||
- [Model and tool usage tracking](#model-and-tool-usage-tracking)
|
||||
- [Resources](#resources)
|
||||
|
||||
## 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"
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- 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](./cli/configuration.md).
|
||||
|
||||
## 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](./cli/configuration.md) - Complete configuration guide
|
||||
- [Authentication](./cli/authentication.md) - Setup authentication
|
||||
- [Commands](./cli/commands.md) - Interactive commands reference
|
||||
- [Tutorials](./cli/tutorials.md) - Step-by-step automation guides
|
||||
157
docs/users/features/sandbox.md
Normal file
157
docs/users/features/sandbox.md
Normal file
@@ -0,0 +1,157 @@
|
||||
# Sandboxing in Qwen Code
|
||||
|
||||
This document provides a guide to sandboxing in Qwen Code, including prerequisites, quickstart, and configuration.
|
||||
|
||||
## 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 AI operations 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.
|
||||
|
||||
## 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 project directory but allows most other operations.
|
||||
|
||||
### 2. Container-based (Docker/Podman)
|
||||
|
||||
Cross-platform sandboxing with complete process isolation.
|
||||
|
||||
**Note**: Requires building the sandbox image locally or using a published image from your organization's registry.
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
# Enable sandboxing with command flag
|
||||
qwen -s -p "analyze the code structure"
|
||||
|
||||
# Use environment variable
|
||||
export GEMINI_SANDBOX=true
|
||||
qwen -p "run the test suite"
|
||||
|
||||
# Configure in settings.json
|
||||
{
|
||||
"tools": {
|
||||
"sandbox": "docker"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Enable sandboxing (in order of precedence)
|
||||
|
||||
1. **Command flag**: `-s` or `--sandbox`
|
||||
2. **Environment variable**: `GEMINI_SANDBOX=true|docker|podman|sandbox-exec`
|
||||
3. **Settings file**: `"sandbox": true` in the `tools` object of your `settings.json` file (e.g., `{"tools": {"sandbox": true}}`).
|
||||
|
||||
### 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
|
||||
|
||||
### 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"
|
||||
```
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common issues
|
||||
|
||||
**"Operation not permitted"**
|
||||
|
||||
- Operation requires access outside sandbox.
|
||||
- Try more permissive profile or add mount points.
|
||||
|
||||
**Missing commands**
|
||||
|
||||
- Add to custom Dockerfile.
|
||||
- Install via `sandbox.bashrc`.
|
||||
|
||||
**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 first build.
|
||||
- GUI applications may not work in sandboxes.
|
||||
|
||||
## Related documentation
|
||||
|
||||
- [Configuration](./cli/configuration.md): Full configuration options.
|
||||
- [Commands](./cli/commands.md): Available commands.
|
||||
- [Troubleshooting](./troubleshooting.md): General troubleshooting.
|
||||
512
docs/users/features/subagents.md
Normal file
512
docs/users/features/subagents.md
Normal file
@@ -0,0 +1,512 @@
|
||||
# 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 subagent 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 subagent.
|
||||
[Delegates to "testing-expert" subagent]
|
||||
[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:
|
||||
|
||||
#### `/agents create`
|
||||
|
||||
Creates a new subagent through a guided step wizard.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```
|
||||
/agents create
|
||||
```
|
||||
|
||||
#### `/agents manage`
|
||||
|
||||
Opens an interactive management dialog for viewing and managing existing subagents.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```
|
||||
/agents manage
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
```markdown
|
||||
---
|
||||
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
|
||||
|
||||
```markdown
|
||||
---
|
||||
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 subagent configurations
|
||||
- Current context and available tools
|
||||
|
||||
To encourage more proactive subagent 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 subagent create unit tests for the payment module
|
||||
> Have the documentation-writer subagent update the API reference
|
||||
> Get the react-specialist subagent to optimize this component's performance
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Development Workflow Agents
|
||||
|
||||
#### Testing Specialist
|
||||
|
||||
Perfect for comprehensive test creation and test-driven development.
|
||||
|
||||
```markdown
|
||||
---
|
||||
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.
|
||||
|
||||
```markdown
|
||||
---
|
||||
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.
|
||||
|
||||
```markdown
|
||||
---
|
||||
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.
|
||||
|
||||
```markdown
|
||||
---
|
||||
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.
|
||||
|
||||
```markdown
|
||||
---
|
||||
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:**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: testing-expert
|
||||
description: Writes comprehensive unit tests and integration tests
|
||||
---
|
||||
```
|
||||
|
||||
**❌ Avoid:**
|
||||
|
||||
```markdown
|
||||
---
|
||||
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:**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: react-performance-optimizer
|
||||
description: Optimizes React applications for performance using profiling and best practices
|
||||
---
|
||||
```
|
||||
|
||||
**❌ Avoid:**
|
||||
|
||||
```markdown
|
||||
---
|
||||
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:**
|
||||
|
||||
```markdown
|
||||
description: Reviews code for security vulnerabilities, performance issues, and maintainability concerns
|
||||
```
|
||||
|
||||
**❌ Avoid:**
|
||||
|
||||
```markdown
|
||||
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:**
|
||||
|
||||
```markdown
|
||||
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:**
|
||||
|
||||
```markdown
|
||||
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:**
|
||||
|
||||
```markdown
|
||||
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 subagent 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
|
||||
14
docs/users/features/token-caching.md
Normal file
14
docs/users/features/token-caching.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Token Caching and Cost Optimization
|
||||
|
||||
Qwen Code automatically optimizes API costs through token caching when using API key authentication (e.g., OpenAI-compatible providers). This feature reuses previous system instructions and context to reduce the number of tokens processed in subsequent requests.
|
||||
|
||||
**Token caching is available for:**
|
||||
|
||||
- API key users (Qwen API key)
|
||||
- Vertex AI users (with project and location setup)
|
||||
|
||||
**Token caching is not available for:**
|
||||
|
||||
- OAuth users (Google Personal/Enterprise accounts) - the Code Assist API does not support cached content creation at this time
|
||||
|
||||
You can view your token usage and cached token savings using the `/stats` command. When cached tokens are available, they will be displayed in the stats output.
|
||||
133
docs/users/features/welcome-back.md
Normal file
133
docs/users/features/welcome-back.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# Welcome Back Feature
|
||||
|
||||
The Welcome Back feature helps you seamlessly resume your work by automatically detecting when you return to a project with existing conversation history and offering to continue from where you left off.
|
||||
|
||||
## Overview
|
||||
|
||||
When you start Qwen Code in a project directory that contains a previously generated project summary (`.qwen/PROJECT_SUMMARY.md`), the Welcome Back dialog will automatically appear, giving you the option to either start fresh or continue your previous conversation.
|
||||
|
||||
## How It Works
|
||||
|
||||
### Automatic Detection
|
||||
|
||||
The Welcome Back feature automatically detects:
|
||||
|
||||
- **Project Summary File:** Looks for `.qwen/PROJECT_SUMMARY.md` in your current project directory
|
||||
- **Conversation History:** Checks if there's meaningful conversation history to resume
|
||||
- **Settings:** Respects your `enableWelcomeBack` setting (enabled by default)
|
||||
|
||||
### Welcome Back Dialog
|
||||
|
||||
When a project summary is found, you'll see a dialog with:
|
||||
|
||||
- **Last Updated Time:** Shows when the summary was last generated
|
||||
- **Overall Goal:** Displays the main objective from your previous session
|
||||
- **Current Plan:** Shows task progress with status indicators:
|
||||
- `[DONE]` - Completed tasks
|
||||
- `[IN PROGRESS]` - Currently working on
|
||||
- `[TODO]` - Planned tasks
|
||||
- **Task Statistics:** Summary of total tasks, completed, in progress, and pending
|
||||
|
||||
### Options
|
||||
|
||||
You have two choices when the Welcome Back dialog appears:
|
||||
|
||||
1. **Start new chat session**
|
||||
- Closes the dialog and begins a fresh conversation
|
||||
- No previous context is loaded
|
||||
|
||||
2. **Continue previous conversation**
|
||||
- Automatically fills the input with: `@.qwen/PROJECT_SUMMARY.md, Based on our previous conversation, Let's continue?`
|
||||
- Loads the project summary as context for the AI
|
||||
- Allows you to seamlessly pick up where you left off
|
||||
|
||||
## Configuration
|
||||
|
||||
### Enable/Disable Welcome Back
|
||||
|
||||
You can control the Welcome Back feature through settings:
|
||||
|
||||
**Via Settings Dialog:**
|
||||
|
||||
1. Run `/settings` in Qwen Code
|
||||
2. Find "Enable Welcome Back" in the UI category
|
||||
3. Toggle the setting on/off
|
||||
|
||||
**Via Settings File:**
|
||||
Add to your `.qwen/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"enableWelcomeBack": true
|
||||
}
|
||||
```
|
||||
|
||||
**Settings Locations:**
|
||||
|
||||
- **User settings:** `~/.qwen/settings.json` (affects all projects)
|
||||
- **Project settings:** `.qwen/settings.json` (project-specific)
|
||||
|
||||
### Keyboard Shortcuts
|
||||
|
||||
- **Escape:** Close the Welcome Back dialog (defaults to "Start new chat session")
|
||||
|
||||
## Integration with Other Features
|
||||
|
||||
### Project Summary Generation
|
||||
|
||||
The Welcome Back feature works seamlessly with the `/summary` command:
|
||||
|
||||
1. **Generate Summary:** Use `/summary` to create a project summary
|
||||
2. **Automatic Detection:** Next time you start Qwen Code in this project, Welcome Back will detect the summary
|
||||
3. **Resume Work:** Choose to continue and the summary will be loaded as context
|
||||
|
||||
### Quit Confirmation
|
||||
|
||||
When exiting with `/quit-confirm` and choosing "Generate summary and quit":
|
||||
|
||||
1. A project summary is automatically created
|
||||
2. Next session will trigger the Welcome Back dialog
|
||||
3. You can seamlessly continue your work
|
||||
|
||||
## File Structure
|
||||
|
||||
The Welcome Back feature creates and uses:
|
||||
|
||||
```
|
||||
your-project/
|
||||
├── .qwen/
|
||||
│ └── PROJECT_SUMMARY.md # Generated project summary
|
||||
```
|
||||
|
||||
### PROJECT_SUMMARY.md Format
|
||||
|
||||
The generated summary follows this structure:
|
||||
|
||||
```markdown
|
||||
# Project Summary
|
||||
|
||||
## Overall Goal
|
||||
|
||||
<!-- Single, concise sentence describing the high-level objective -->
|
||||
|
||||
## Key Knowledge
|
||||
|
||||
<!-- Crucial facts, conventions, and constraints -->
|
||||
<!-- Includes: technology choices, architecture decisions, user preferences -->
|
||||
|
||||
## Recent Actions
|
||||
|
||||
<!-- Summary of significant recent work and outcomes -->
|
||||
<!-- Includes: accomplishments, discoveries, recent changes -->
|
||||
|
||||
## Current Plan
|
||||
|
||||
<!-- The current development roadmap and next steps -->
|
||||
<!-- Uses status markers: [DONE], [IN PROGRESS], [TODO] -->
|
||||
|
||||
---
|
||||
|
||||
## Summary Metadata
|
||||
|
||||
**Update time**: 2025-01-10T15:30:00.000Z
|
||||
```
|
||||
4
docs/users/ide-integration/_meta.ts
Normal file
4
docs/users/ide-integration/_meta.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export default {
|
||||
'ide-integration': 'Introduction',
|
||||
'ide-companion-spec': 'IDE Companion Spec',
|
||||
};
|
||||
184
docs/users/ide-integration/ide-companion-spec.md
Normal file
184
docs/users/ide-integration/ide-companion-spec.md
Normal 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.
|
||||
144
docs/users/ide-integration/ide-integration.md
Normal file
144
docs/users/ide-integration/ide-integration.md
Normal 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](./ide-companion-spec.md).
|
||||
|
||||
## 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.
|
||||
4
docs/users/support/_meta.ts
Normal file
4
docs/users/support/_meta.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export default {
|
||||
troubleshooting: 'Troubleshooting',
|
||||
'tos-privacy': 'Terms of Service',
|
||||
};
|
||||
98
docs/users/support/tos-privacy.md
Normal file
98
docs/users/support/tos-privacy.md
Normal file
@@ -0,0 +1,98 @@
|
||||
# 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](./cli/authentication.md).
|
||||
|
||||
## 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 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.
|
||||
|
||||
### Opt-Out Instructions
|
||||
|
||||
You can disable usage statistics collection by following the instructions in the [Usage Statistics Configuration](./cli/configuration.md#usage-statistics) documentation.
|
||||
|
||||
## 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.
|
||||
|
||||
You can disable Usage Statistics collection by following the instructions in the [Usage Statistics Configuration](./cli/configuration.md#usage-statistics) documentation.
|
||||
|
||||
### 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](./cli/authentication.md) documentation.
|
||||
116
docs/users/support/troubleshooting.md
Normal file
116
docs/users/support/troubleshooting.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# Troubleshooting guide
|
||||
|
||||
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](./cli/configuration.md) 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](./cli/configuration.md#sandboxing) 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!
|
||||
Reference in New Issue
Block a user