docs: update headless doc

This commit is contained in:
mingholy.lmh
2025-11-06 12:43:16 +08:00
parent 9d26095bd6
commit edb4b36408
4 changed files with 121 additions and 122 deletions

View File

@@ -5,6 +5,7 @@ export default {
commands: 'Commands', commands: 'Commands',
configuration: 'Configuration', configuration: 'Configuration',
'configuration-v1': 'Configuration (v1)', 'configuration-v1': 'Configuration (v1)',
'structured-output': 'Structured Output',
themes: 'Themes', themes: 'Themes',
tutorials: 'Tutorials', tutorials: 'Tutorials',
'keyboard-shortcuts': 'Keyboard Shortcuts', 'keyboard-shortcuts': 'Keyboard Shortcuts',

View File

@@ -508,12 +508,25 @@ Arguments passed directly when running the CLI can override other configurations
- The prompt is processed within the interactive session, not before it. - The prompt is processed within the interactive session, not before it.
- Cannot be used when piping input from stdin. - Cannot be used when piping input from stdin.
- Example: `qwen -i "explain this code"` - Example: `qwen -i "explain this code"`
- **`--output-format <format>`**: - **`--output-format <format>`** (**`-o <format>`**):
- **Description:** Specifies the format of the CLI output for non-interactive mode. - **Description:** Specifies the format of the CLI output for non-interactive mode.
- **Values:** - **Values:**
- `text`: (Default) The standard human-readable output. - `text`: (Default) The standard human-readable output.
- `json`: A machine-readable JSON output. - `json`: A machine-readable JSON output emitted at the end of execution.
- **Note:** For structured output and scripting, use the `--output-format json` flag. - `stream-json`: Streaming JSON messages emitted as they occur during execution.
- **Note:** For structured output and scripting, use the `--output-format json` or `--output-format stream-json` flag. See [Headless Mode](../features/headless.md) for detailed information.
- **`--input-format <format>`**:
- **Description:** Specifies the format consumed from standard input.
- **Values:**
- `text`: (Default) Standard text input from stdin or command-line arguments.
- `stream-json`: JSON message protocol via stdin for bidirectional communication.
- **Requirement:** `--input-format stream-json` requires `--output-format stream-json` to be set.
- **Note:** When using `stream-json`, stdin is reserved for protocol messages. See [Headless Mode](../features/headless.md) for detailed information.
- **`--include-partial-messages`**:
- **Description:** Include partial assistant messages when using `stream-json` output format. When enabled, emits stream events (message_start, content_block_delta, etc.) as they occur during streaming.
- **Default:** `false`
- **Requirement:** Requires `--output-format stream-json` to be set.
- **Note:** See [Headless Mode](../features/headless.md) for detailed information about stream events.
- **`--sandbox`** (**`-s`**): - **`--sandbox`** (**`-s`**):
- Enables sandbox mode for this session. - Enables sandbox mode for this session.
- **`--sandbox-image`**: - **`--sandbox-image`**:

View File

@@ -13,8 +13,9 @@ scripting, automation, CI/CD pipelines, and building AI-powered tools.
- [Output Formats](#output-formats) - [Output Formats](#output-formats)
- [Text Output (Default)](#text-output-default) - [Text Output (Default)](#text-output-default)
- [JSON Output](#json-output) - [JSON Output](#json-output)
- [Response Schema](#response-schema)
- [Example Usage](#example-usage) - [Example Usage](#example-usage)
- [Stream-JSON Output](#stream-json-output)
- [Input Format](#input-format)
- [File Redirection](#file-redirection) - [File Redirection](#file-redirection)
- [Configuration Options](#configuration-options) - [Configuration Options](#configuration-options)
- [Examples](#examples) - [Examples](#examples)
@@ -22,7 +23,7 @@ scripting, automation, CI/CD pipelines, and building AI-powered tools.
- [Generate commit messages](#generate-commit-messages) - [Generate commit messages](#generate-commit-messages)
- [API documentation](#api-documentation) - [API documentation](#api-documentation)
- [Batch code analysis](#batch-code-analysis) - [Batch code analysis](#batch-code-analysis)
- [Code review](#code-review-1) - [PR code review](#pr-code-review)
- [Log analysis](#log-analysis) - [Log analysis](#log-analysis)
- [Release notes generation](#release-notes-generation) - [Release notes generation](#release-notes-generation)
- [Model and tool usage tracking](#model-and-tool-usage-tracking) - [Model and tool usage tracking](#model-and-tool-usage-tracking)
@@ -66,6 +67,8 @@ cat README.md | qwen --prompt "Summarize this documentation"
## Output Formats ## Output Formats
Qwen Code supports multiple output formats for different use cases:
### Text Output (Default) ### Text Output (Default)
Standard human-readable output: Standard human-readable output:
@@ -82,56 +85,9 @@ The capital of France is Paris.
### JSON Output ### JSON Output
Returns structured data including response, statistics, and metadata. This 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.
format is ideal for programmatic processing and automation scripts.
#### Response Schema 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).
The JSON output follows this high-level structure:
```json
{
"response": "string", // The main AI-generated content answering your prompt
"stats": {
// Usage metrics and performance data
"models": {
// Per-model API and token usage statistics
"[model-name]": {
"api": {
/* request counts, errors, latency */
},
"tokens": {
/* prompt, response, cached, total counts */
}
}
},
"tools": {
// Tool execution statistics
"totalCalls": "number",
"totalSuccess": "number",
"totalFail": "number",
"totalDurationMs": "number",
"totalDecisions": {
/* accept, reject, modify, auto_accept counts */
},
"byName": {
/* per-tool detailed stats */
}
},
"files": {
// File modification statistics
"totalLinesAdded": "number",
"totalLinesRemoved": "number"
}
},
"error": {
// Present only when an error occurred
"type": "string", // Error type (e.g., "ApiError", "AuthError")
"message": "string", // Human-readable error description
"code": "number" // Optional error code
}
}
```
#### Example Usage #### Example Usage
@@ -139,63 +95,81 @@ The JSON output follows this high-level structure:
qwen -p "What is the capital of France?" --output-format json qwen -p "What is the capital of France?" --output-format json
``` ```
Response: Output (at end of execution):
```json ```json
[
{ {
"response": "The capital of France is Paris.", "type": "system",
"stats": { "subtype": "session_start",
"models": { "uuid": "...",
"qwen3-coder-plus": { "session_id": "...",
"api": { "model": "qwen3-coder-plus",
"totalRequests": 2, ...
"totalErrors": 0,
"totalLatencyMs": 5053
}, },
"tokens": { {
"prompt": 24939, "type": "assistant",
"candidates": 20, "uuid": "...",
"total": 25113, "session_id": "...",
"cached": 21263, "message": {
"thoughts": 154, "id": "...",
"tool": 0 "type": "message",
} "role": "assistant",
"model": "qwen3-coder-plus",
"content": [
{
"type": "text",
"text": "The capital of France is Paris."
} }
],
"usage": {...}
}, },
"tools": { "parent_tool_use_id": null
"totalCalls": 1,
"totalSuccess": 1,
"totalFail": 0,
"totalDurationMs": 1881,
"totalDecisions": {
"accept": 0,
"reject": 0,
"modify": 0,
"auto_accept": 1
}, },
"byName": { {
"google_web_search": { "type": "result",
"count": 1, "subtype": "success",
"success": 1, "uuid": "...",
"fail": 0, "session_id": "...",
"durationMs": 1881, "is_error": false,
"decisions": { "duration_ms": 1234,
"accept": 0, "result": "The capital of France is Paris.",
"reject": 0, "usage": {...}
"modify": 0,
"auto_accept": 1
}
}
}
},
"files": {
"totalLinesAdded": 0,
"totalLinesRemoved": 0
}
}
} }
]
``` ```
### 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 ### File Redirection
Save output to files or pipe to other commands: Save output to files or pipe to other commands:
@@ -212,6 +186,10 @@ qwen -p "Add more details" >> docker-explanation.txt
qwen -p "What is Kubernetes?" --output-format json | jq '.response' qwen -p "What is Kubernetes?" --output-format json | jq '.response'
qwen -p "Explain microservices" | wc -w qwen -p "Explain microservices" | wc -w
qwen -p "List programming languages" | grep -i "python" 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 ## Configuration Options
@@ -219,10 +197,11 @@ qwen -p "List programming languages" | grep -i "python"
Key command-line options for headless usage: Key command-line options for headless usage:
| Option | Description | Example | | Option | Description | Example |
| ----------------------- | ---------------------------------- | ------------------------------------------------ | | ---------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------ |
| `--prompt`, `-p` | Run in headless mode | `qwen -p "query"` | | `--prompt`, `-p` | Run in headless mode | `qwen -p "query"` |
| `--output-format` | Specify output format (text, json) | `qwen -p "query" --output-format json` | | `--output-format`, `-o` | Specify output format (text, json, stream-json) | `qwen -p "query" --output-format json` |
| `--model`, `-m` | Specify the Qwen model | `qwen -p "query" -m qwen3-coder-plus` | | `--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` | | `--debug`, `-d` | Enable debug mode | `qwen -p "query" --debug` |
| `--all-files`, `-a` | Include all files in context | `qwen -p "query" --all-files` | | `--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` | | `--include-directories` | Include additional directories | `qwen -p "query" --include-directories src,docs` |
@@ -233,27 +212,27 @@ For complete details on all available configuration options, settings files, and
## Examples ## Examples
#### Code review ### Code review
```bash ```bash
cat src/auth.py | qwen -p "Review this authentication code for security issues" > security-review.txt cat src/auth.py | qwen -p "Review this authentication code for security issues" > security-review.txt
``` ```
#### Generate commit messages ### Generate commit messages
```bash ```bash
result=$(git diff --cached | qwen -p "Write a concise commit message for these changes" --output-format json) result=$(git diff --cached | qwen -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response' echo "$result" | jq -r '.response'
``` ```
#### API documentation ### API documentation
```bash ```bash
result=$(cat api/routes.js | qwen -p "Generate OpenAPI spec for these routes" --output-format json) result=$(cat api/routes.js | qwen -p "Generate OpenAPI spec for these routes" --output-format json)
echo "$result" | jq -r '.response' > openapi.json echo "$result" | jq -r '.response' > openapi.json
``` ```
#### Batch code analysis ### Batch code analysis
```bash ```bash
for file in src/*.py; do for file in src/*.py; do
@@ -264,20 +243,20 @@ for file in src/*.py; do
done done
``` ```
#### Code review ### PR code review
```bash ```bash
result=$(git diff origin/main...HEAD | qwen -p "Review these changes for bugs, security issues, and code quality" --output-format json) 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 echo "$result" | jq -r '.response' > pr-review.json
``` ```
#### Log analysis ### Log analysis
```bash ```bash
grep "ERROR" /var/log/app.log | tail -20 | qwen -p "Analyze these errors and suggest root cause and fixes" > error-analysis.txt 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 ### Release notes generation
```bash ```bash
result=$(git log --oneline v1.0.0..HEAD | qwen -p "Generate release notes from these commits" --output-format json) result=$(git log --oneline v1.0.0..HEAD | qwen -p "Generate release notes from these commits" --output-format json)
@@ -286,7 +265,7 @@ echo "$response"
echo "$response" >> CHANGELOG.md echo "$response" >> CHANGELOG.md
``` ```
#### Model and tool usage tracking ### Model and tool usage tracking
```bash ```bash
result=$(qwen -p "Explain this database schema" --include-directories db --output-format json) result=$(qwen -p "Explain this database schema" --include-directories db --output-format json)

View File

@@ -444,6 +444,12 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
) { ) {
return '--include-partial-messages requires --output-format stream-json'; return '--include-partial-messages requires --output-format stream-json';
} }
if (
argv['inputFormat'] === 'stream-json' &&
argv['outputFormat'] !== OutputFormat.STREAM_JSON
) {
return '--input-format stream-json requires --output-format stream-json';
}
return true; return true;
}), }),
) )