mirror of
https://github.com/QwenLM/qwen-code.git
synced 2025-12-19 01:23:53 +00:00
feat: update docs
This commit is contained in:
@@ -40,6 +40,9 @@ export default async function RootLayout({ children }) {
|
||||
navbar={navbar}
|
||||
pageMap={await getPageMap()}
|
||||
docsRepositoryBase="https://github.com/QwenLM/qwen-code/docs"
|
||||
// Use a very large finite integer to expand all folders by default.
|
||||
// (Some schema validators reject `Infinity`.)
|
||||
sidebar={{ defaultMenuCollapseLevel: 9999 }}
|
||||
footer={footer}
|
||||
search={false}
|
||||
// ... Your additional layout options
|
||||
|
||||
@@ -10,6 +10,7 @@ export default {
|
||||
title: 'Qwen Code SDK',
|
||||
type: 'separator',
|
||||
},
|
||||
'sdk-typescript': 'Typescript SDK',
|
||||
'Dive Into Qwen Code': {
|
||||
title: 'Dive Into Qwen Code',
|
||||
type: 'separator',
|
||||
@@ -17,7 +18,16 @@ export default {
|
||||
cli: {
|
||||
display: 'hidden',
|
||||
},
|
||||
core: 'Core',
|
||||
|
||||
tools: 'Tools',
|
||||
// development: 'Development',
|
||||
core: {
|
||||
display: 'hidden',
|
||||
},
|
||||
extensions: {
|
||||
display: 'hidden',
|
||||
},
|
||||
examples: {
|
||||
display: 'hidden',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -3,4 +3,7 @@ export default {
|
||||
telemetry: 'Telemetry',
|
||||
'integration-tests': 'Integration Tests',
|
||||
'issue-and-pr-automation': 'Issue and PR Automation',
|
||||
deployment: {
|
||||
display: 'hidden',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -6,13 +6,12 @@ Learn how to enable and setup OpenTelemetry for Qwen Code.
|
||||
- [Key Benefits](#key-benefits)
|
||||
- [OpenTelemetry Integration](#opentelemetry-integration)
|
||||
- [Configuration](#configuration)
|
||||
- [Google Cloud Telemetry](#google-cloud-telemetry)
|
||||
- [Aliyun Telemetry](#aliyun-telemetry)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Direct Export (Recommended)](#direct-export-recommended)
|
||||
- [Collector-Based Export (Advanced)](#collector-based-export-advanced)
|
||||
- [Local Telemetry](#local-telemetry)
|
||||
- [File-based Output (Recommended)](#file-based-output-recommended)
|
||||
- [Collector-Based Export (Advanced)](#collector-based-export-advanced-1)
|
||||
- [Collector-Based Export (Advanced)](#collector-based-export-advanced)
|
||||
- [Logs and Metrics](#logs-and-metrics)
|
||||
- [Logs](#logs)
|
||||
- [Metrics](#metrics)
|
||||
@@ -35,8 +34,8 @@ Learn how to enable and setup OpenTelemetry for Qwen Code.
|
||||
Built on **[OpenTelemetry]** — the vendor-neutral, industry-standard
|
||||
observability framework — Qwen Code's observability system provides:
|
||||
|
||||
- **Universal Compatibility**: Export to any OpenTelemetry backend (Google
|
||||
Cloud, Jaeger, Prometheus, Datadog, etc.)
|
||||
- **Universal Compatibility**: Export to any OpenTelemetry backend (Aliyun,
|
||||
Jaeger, Prometheus, Datadog, etc.)
|
||||
- **Standardized Data**: Use consistent formats and collection methods across
|
||||
your toolchain
|
||||
- **Future-Proof Integration**: Connect with existing and future observability
|
||||
@@ -51,15 +50,15 @@ observability framework — Qwen Code's observability system provides:
|
||||
All telemetry behavior is controlled through your `.qwen/settings.json` file.
|
||||
These settings can be overridden by environment variables or CLI flags.
|
||||
|
||||
| Setting | Environment Variable | CLI Flag | Description | Values | Default |
|
||||
| -------------- | -------------------------------- | -------------------------------------------------------- | ------------------------------------------------- | ----------------- | ----------------------- |
|
||||
| `enabled` | `GEMINI_TELEMETRY_ENABLED` | `--telemetry` / `--no-telemetry` | Enable or disable telemetry | `true`/`false` | `false` |
|
||||
| `target` | `GEMINI_TELEMETRY_TARGET` | `--telemetry-target <local\|gcp>` | Where to send telemetry data | `"gcp"`/`"local"` | `"local"` |
|
||||
| `otlpEndpoint` | `GEMINI_TELEMETRY_OTLP_ENDPOINT` | `--telemetry-otlp-endpoint <URL>` | OTLP collector endpoint | URL string | `http://localhost:4317` |
|
||||
| `otlpProtocol` | `GEMINI_TELEMETRY_OTLP_PROTOCOL` | `--telemetry-otlp-protocol <grpc\|http>` | OTLP transport protocol | `"grpc"`/`"http"` | `"grpc"` |
|
||||
| `outfile` | `GEMINI_TELEMETRY_OUTFILE` | `--telemetry-outfile <path>` | Save telemetry to file (overrides `otlpEndpoint`) | file path | - |
|
||||
| `logPrompts` | `GEMINI_TELEMETRY_LOG_PROMPTS` | `--telemetry-log-prompts` / `--no-telemetry-log-prompts` | Include prompts in telemetry logs | `true`/`false` | `true` |
|
||||
| `useCollector` | `GEMINI_TELEMETRY_USE_COLLECTOR` | - | Use external OTLP collector (advanced) | `true`/`false` | `false` |
|
||||
| Setting | Environment Variable | CLI Flag | Description | Values | Default |
|
||||
| -------------- | ------------------------------ | -------------------------------------------------------- | ------------------------------------------------- | ------------------ | ----------------------- |
|
||||
| `enabled` | `QWEN_TELEMETRY_ENABLED` | `--telemetry` / `--no-telemetry` | Enable or disable telemetry | `true`/`false` | `false` |
|
||||
| `target` | `QWEN_TELEMETRY_TARGET` | `--telemetry-target <local\|qwen>` | Where to send telemetry data | `"qwen"`/`"local"` | `"local"` |
|
||||
| `otlpEndpoint` | `QWEN_TELEMETRY_OTLP_ENDPOINT` | `--telemetry-otlp-endpoint <URL>` | OTLP collector endpoint | URL string | `http://localhost:4317` |
|
||||
| `otlpProtocol` | `QWEN_TELEMETRY_OTLP_PROTOCOL` | `--telemetry-otlp-protocol <grpc\|http>` | OTLP transport protocol | `"grpc"`/`"http"` | `"grpc"` |
|
||||
| `outfile` | `QWEN_TELEMETRY_OUTFILE` | `--telemetry-outfile <path>` | Save telemetry to file (overrides `otlpEndpoint`) | file path | - |
|
||||
| `logPrompts` | `QWEN_TELEMETRY_LOG_PROMPTS` | `--telemetry-log-prompts` / `--no-telemetry-log-prompts` | Include prompts in telemetry logs | `true`/`false` | `true` |
|
||||
| `useCollector` | `QWEN_TELEMETRY_USE_COLLECTOR` | - | Use external OTLP collector (advanced) | `true`/`false` | `false` |
|
||||
|
||||
**Note on boolean environment variables:** For the boolean settings (`enabled`,
|
||||
`logPrompts`, `useCollector`), setting the corresponding environment variable to
|
||||
@@ -68,98 +67,23 @@ These settings can be overridden by environment variables or CLI flags.
|
||||
For detailed information about all configuration options, see the
|
||||
[Configuration Guide](./cli/configuration.md).
|
||||
|
||||
## Google Cloud Telemetry
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before using either method below, complete these steps:
|
||||
|
||||
1. Set your Google Cloud project ID:
|
||||
- For telemetry in a separate project from inference:
|
||||
```bash
|
||||
export OTLP_GOOGLE_CLOUD_PROJECT="your-telemetry-project-id"
|
||||
```
|
||||
- For telemetry in the same project as inference:
|
||||
```bash
|
||||
export GOOGLE_CLOUD_PROJECT="your-project-id"
|
||||
```
|
||||
|
||||
2. Authenticate with Google Cloud:
|
||||
- If using a user account:
|
||||
```bash
|
||||
gcloud auth application-default login
|
||||
```
|
||||
- If using a service account:
|
||||
```bash
|
||||
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account.json"
|
||||
```
|
||||
3. Make sure your account or service account has these IAM roles:
|
||||
- Cloud Trace Agent
|
||||
- Monitoring Metric Writer
|
||||
- Logs Writer
|
||||
|
||||
4. Enable the required Google Cloud APIs (if not already enabled):
|
||||
```bash
|
||||
gcloud services enable \
|
||||
cloudtrace.googleapis.com \
|
||||
monitoring.googleapis.com \
|
||||
logging.googleapis.com \
|
||||
--project="$OTLP_GOOGLE_CLOUD_PROJECT"
|
||||
```
|
||||
## Aliyun Telemetry
|
||||
|
||||
### Direct Export (Recommended)
|
||||
|
||||
Sends telemetry directly to Google Cloud services. No collector needed.
|
||||
Sends telemetry directly to Aliyun services. No collector needed.
|
||||
|
||||
1. Enable telemetry in your `.qwen/settings.json`:
|
||||
```json
|
||||
{
|
||||
"telemetry": {
|
||||
"enabled": true,
|
||||
"target": "gcp"
|
||||
"target": "qwen"
|
||||
}
|
||||
}
|
||||
```
|
||||
2. Run Qwen Code and send prompts.
|
||||
3. View logs and metrics:
|
||||
- Open the Google Cloud Console in your browser after sending prompts:
|
||||
- Logs: https://console.cloud.google.com/logs/
|
||||
- Metrics: https://console.cloud.google.com/monitoring/metrics-explorer
|
||||
- Traces: https://console.cloud.google.com/traces/list
|
||||
|
||||
### Collector-Based Export (Advanced)
|
||||
|
||||
For custom processing, filtering, or routing, use an OpenTelemetry collector to
|
||||
forward data to Google Cloud.
|
||||
|
||||
1. Configure your `.qwen/settings.json`:
|
||||
```json
|
||||
{
|
||||
"telemetry": {
|
||||
"enabled": true,
|
||||
"target": "gcp",
|
||||
"useCollector": true
|
||||
}
|
||||
}
|
||||
```
|
||||
2. Run the automation script:
|
||||
```bash
|
||||
npm run telemetry -- --target=gcp
|
||||
```
|
||||
This will:
|
||||
- Start a local OTEL collector that forwards to Google Cloud
|
||||
- Configure your workspace
|
||||
- Provide links to view traces, metrics, and logs in Google Cloud Console
|
||||
- Save collector logs to `~/.qwen/tmp/<projectHash>/otel/collector-gcp.log`
|
||||
- Stop collector on exit (e.g. `Ctrl+C`)
|
||||
3. Run Qwen Code and send prompts.
|
||||
4. View logs and metrics:
|
||||
- Open the Google Cloud Console in your browser after sending prompts:
|
||||
- Logs: https://console.cloud.google.com/logs/
|
||||
- Metrics: https://console.cloud.google.com/monitoring/metrics-explorer
|
||||
- Traces: https://console.cloud.google.com/traces/list
|
||||
- Open `~/.qwen/tmp/<projectHash>/otel/collector-gcp.log` to view local
|
||||
collector logs.
|
||||
3. View logs and metrics in the Aliyun Console.
|
||||
|
||||
## Local Telemetry
|
||||
|
||||
|
||||
375
docs/developers/sdk-typescript.md
Normal file
375
docs/developers/sdk-typescript.md
Normal file
@@ -0,0 +1,375 @@
|
||||
# Typescript SDK
|
||||
|
||||
## @qwen-code/sdk
|
||||
|
||||
A minimum experimental TypeScript SDK for programmatic access to Qwen Code.
|
||||
|
||||
Feel free to submit a feature request/issue/PR.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @qwen-code/sdk
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
- Node.js >= 20.0.0
|
||||
- [Qwen Code](https://github.com/QwenLM/qwen-code) >= 0.4.0 (stable) installed and accessible in PATH
|
||||
|
||||
> **Note for nvm users**: If you use nvm to manage Node.js versions, the SDK may not be able to auto-detect the Qwen Code executable. You should explicitly set the `pathToQwenExecutable` option to the full path of the `qwen` binary.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { query } from '@qwen-code/sdk';
|
||||
|
||||
// Single-turn query
|
||||
const result = query({
|
||||
prompt: 'What files are in the current directory?',
|
||||
options: {
|
||||
cwd: '/path/to/project',
|
||||
},
|
||||
});
|
||||
|
||||
// Iterate over messages
|
||||
for await (const message of result) {
|
||||
if (message.type === 'assistant') {
|
||||
console.log('Assistant:', message.message.content);
|
||||
} else if (message.type === 'result') {
|
||||
console.log('Result:', message.result);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `query(config)`
|
||||
|
||||
Creates a new query session with the Qwen Code.
|
||||
|
||||
#### Parameters
|
||||
|
||||
- `prompt`: `string | AsyncIterable<SDKUserMessage>` - The prompt to send. Use a string for single-turn queries or an async iterable for multi-turn conversations.
|
||||
- `options`: `QueryOptions` - Configuration options for the query session.
|
||||
|
||||
#### QueryOptions
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| ------------------------ | ---------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. |
|
||||
| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. |
|
||||
| `pathToQwenExecutable` | `string` | Auto-detected | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, auto-detects from: `QWEN_CODE_CLI_PATH` env var, `~/.volta/bin/qwen`, `~/.npm-global/bin/qwen`, `/usr/local/bin/qwen`, `~/.local/bin/qwen`, `~/node_modules/.bin/qwen`, `~/.yarn/bin/qwen`. |
|
||||
| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. |
|
||||
| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). |
|
||||
| `env` | `Record<string, string>` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. |
|
||||
| `mcpServers` | `Record<string, McpServerConfig>` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. |
|
||||
| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. |
|
||||
| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. |
|
||||
| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. A turn consists of a user message and an assistant response. |
|
||||
| `coreTools` | `string[]` | - | Equivalent to `tool.core` in settings.json. If specified, only these tools will be available to the AI. Example: `['read_file', 'write_file', 'run_terminal_cmd']`. |
|
||||
| `excludeTools` | `string[]` | - | Equivalent to `tool.exclude` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports pattern matching: tool name (`'write_file'`), tool class (`'ShellTool'`), or shell command prefix (`'ShellTool(rm )'`). |
|
||||
| `allowedTools` | `string[]` | - | Equivalent to `tool.allowed` in settings.json. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Supports same pattern matching as `excludeTools`. |
|
||||
| `authType` | `'openai' \| 'qwen-oauth'` | `'openai'` | Authentication type for the AI service. Using `'qwen-oauth'` in SDK is not recommended as credentials are stored in `~/.qwen` and may need periodic refresh. |
|
||||
| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. |
|
||||
| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. |
|
||||
|
||||
### Timeouts
|
||||
|
||||
The SDK enforces the following default timeouts:
|
||||
|
||||
| Timeout | Default | Description |
|
||||
| ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `canUseTool` | 1 minute | Maximum time for `canUseTool` callback to respond. If exceeded, the tool request is auto-denied. |
|
||||
| `mcpRequest` | 1 minute | Maximum time for SDK MCP tool calls to complete. |
|
||||
| `controlRequest` | 1 minute | Maximum time for control operations like `initialize()`, `setModel()`, `setPermissionMode()`, and `interrupt()` to complete. |
|
||||
| `streamClose` | 1 minute | Maximum time to wait for initialization to complete before closing CLI stdin in multi-turn mode with SDK MCP servers. |
|
||||
|
||||
You can customize these timeouts via the `timeout` option:
|
||||
|
||||
```typescript
|
||||
const query = qwen.query('Your prompt', {
|
||||
timeout: {
|
||||
canUseTool: 60000, // 60 seconds for permission callback
|
||||
mcpRequest: 600000, // 10 minutes for MCP tool calls
|
||||
controlRequest: 60000, // 60 seconds for control requests
|
||||
streamClose: 15000, // 15 seconds for stream close wait
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Message Types
|
||||
|
||||
The SDK provides type guards to identify different message types:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
isSDKUserMessage,
|
||||
isSDKAssistantMessage,
|
||||
isSDKSystemMessage,
|
||||
isSDKResultMessage,
|
||||
isSDKPartialAssistantMessage,
|
||||
} from '@qwen-code/sdk';
|
||||
|
||||
for await (const message of result) {
|
||||
if (isSDKAssistantMessage(message)) {
|
||||
// Handle assistant message
|
||||
} else if (isSDKResultMessage(message)) {
|
||||
// Handle result message
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Query Instance Methods
|
||||
|
||||
The `Query` instance returned by `query()` provides several methods:
|
||||
|
||||
```typescript
|
||||
const q = query({ prompt: 'Hello', options: {} });
|
||||
|
||||
// Get session ID
|
||||
const sessionId = q.getSessionId();
|
||||
|
||||
// Check if closed
|
||||
const closed = q.isClosed();
|
||||
|
||||
// Interrupt the current operation
|
||||
await q.interrupt();
|
||||
|
||||
// Change permission mode mid-session
|
||||
await q.setPermissionMode('yolo');
|
||||
|
||||
// Change model mid-session
|
||||
await q.setModel('qwen-max');
|
||||
|
||||
// Close the session
|
||||
await q.close();
|
||||
```
|
||||
|
||||
## Permission Modes
|
||||
|
||||
The SDK supports different permission modes for controlling tool execution:
|
||||
|
||||
- **`default`**: Write tools are denied unless approved via `canUseTool` callback or in `allowedTools`. Read-only tools execute without confirmation.
|
||||
- **`plan`**: Blocks all write tools, instructing AI to present a plan first.
|
||||
- **`auto-edit`**: Auto-approve edit tools (edit, write_file) while other tools require confirmation.
|
||||
- **`yolo`**: All tools execute automatically without confirmation.
|
||||
|
||||
### Permission Priority Chain
|
||||
|
||||
1. `excludeTools` - Blocks tools completely
|
||||
2. `permissionMode: 'plan'` - Blocks non-read-only tools
|
||||
3. `permissionMode: 'yolo'` - Auto-approves all tools
|
||||
4. `allowedTools` - Auto-approves matching tools
|
||||
5. `canUseTool` callback - Custom approval logic
|
||||
6. Default behavior - Auto-deny in SDK mode
|
||||
|
||||
## Examples
|
||||
|
||||
### Multi-turn Conversation
|
||||
|
||||
```typescript
|
||||
import { query, type SDKUserMessage } from '@qwen-code/sdk';
|
||||
|
||||
async function* generateMessages(): AsyncIterable<SDKUserMessage> {
|
||||
yield {
|
||||
type: 'user',
|
||||
session_id: 'my-session',
|
||||
message: { role: 'user', content: 'Create a hello.txt file' },
|
||||
parent_tool_use_id: null,
|
||||
};
|
||||
|
||||
// Wait for some condition or user input
|
||||
yield {
|
||||
type: 'user',
|
||||
session_id: 'my-session',
|
||||
message: { role: 'user', content: 'Now read the file back' },
|
||||
parent_tool_use_id: null,
|
||||
};
|
||||
}
|
||||
|
||||
const result = query({
|
||||
prompt: generateMessages(),
|
||||
options: {
|
||||
permissionMode: 'auto-edit',
|
||||
},
|
||||
});
|
||||
|
||||
for await (const message of result) {
|
||||
console.log(message);
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Permission Handler
|
||||
|
||||
```typescript
|
||||
import { query, type CanUseTool } from '@qwen-code/sdk';
|
||||
|
||||
const canUseTool: CanUseTool = async (toolName, input, { signal }) => {
|
||||
// Allow all read operations
|
||||
if (toolName.startsWith('read_')) {
|
||||
return { behavior: 'allow', updatedInput: input };
|
||||
}
|
||||
|
||||
// Prompt user for write operations (in a real app)
|
||||
const userApproved = await promptUser(`Allow ${toolName}?`);
|
||||
|
||||
if (userApproved) {
|
||||
return { behavior: 'allow', updatedInput: input };
|
||||
}
|
||||
|
||||
return { behavior: 'deny', message: 'User denied the operation' };
|
||||
};
|
||||
|
||||
const result = query({
|
||||
prompt: 'Create a new file',
|
||||
options: {
|
||||
canUseTool,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### With External MCP Servers
|
||||
|
||||
```typescript
|
||||
import { query } from '@qwen-code/sdk';
|
||||
|
||||
const result = query({
|
||||
prompt: 'Use the custom tool from my MCP server',
|
||||
options: {
|
||||
mcpServers: {
|
||||
'my-server': {
|
||||
command: 'node',
|
||||
args: ['path/to/mcp-server.js'],
|
||||
env: { PORT: '3000' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### With SDK-Embedded MCP Servers
|
||||
|
||||
The SDK provides `tool` and `createSdkMcpServer` to create MCP servers that run in the same process as your SDK application. This is useful when you want to expose custom tools to the AI without running a separate server process.
|
||||
|
||||
#### `tool(name, description, inputSchema, handler)`
|
||||
|
||||
Creates a tool definition with Zod schema type inference.
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| ------------- | ---------------------------------- | ------------------------------------------------------------------------ |
|
||||
| `name` | `string` | Tool name (1-64 chars, starts with letter, alphanumeric and underscores) |
|
||||
| `description` | `string` | Human-readable description of what the tool does |
|
||||
| `inputSchema` | `ZodRawShape` | Zod schema object defining the tool's input parameters |
|
||||
| `handler` | `(args, extra) => Promise<Result>` | Async function that executes the tool and returns MCP content blocks |
|
||||
|
||||
The handler must return a `CallToolResult` object with the following structure:
|
||||
|
||||
```typescript
|
||||
{
|
||||
content: Array<
|
||||
| { type: 'text'; text: string }
|
||||
| { type: 'image'; data: string; mimeType: string }
|
||||
| { type: 'resource'; uri: string; mimeType?: string; text?: string }
|
||||
>;
|
||||
isError?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
#### `createSdkMcpServer(options)`
|
||||
|
||||
Creates an SDK-embedded MCP server instance.
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| --------- | ------------------------ | --------- | ------------------------------------ |
|
||||
| `name` | `string` | Required | Unique name for the MCP server |
|
||||
| `version` | `string` | `'1.0.0'` | Server version |
|
||||
| `tools` | `SdkMcpToolDefinition[]` | - | Array of tools created with `tool()` |
|
||||
|
||||
Returns a `McpSdkServerConfigWithInstance` object that can be passed directly to the `mcpServers` option.
|
||||
|
||||
#### Example
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
import { query, tool, createSdkMcpServer } from '@qwen-code/sdk';
|
||||
|
||||
// Define a tool with Zod schema
|
||||
const calculatorTool = tool(
|
||||
'calculate_sum',
|
||||
'Add two numbers',
|
||||
{ a: z.number(), b: z.number() },
|
||||
async (args) => ({
|
||||
content: [{ type: 'text', text: String(args.a + args.b) }],
|
||||
}),
|
||||
);
|
||||
|
||||
// Create the MCP server
|
||||
const server = createSdkMcpServer({
|
||||
name: 'calculator',
|
||||
tools: [calculatorTool],
|
||||
});
|
||||
|
||||
// Use the server in a query
|
||||
const result = query({
|
||||
prompt: 'What is 42 + 17?',
|
||||
options: {
|
||||
permissionMode: 'yolo',
|
||||
mcpServers: {
|
||||
calculator: server,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
for await (const message of result) {
|
||||
console.log(message);
|
||||
}
|
||||
```
|
||||
|
||||
### Abort a Query
|
||||
|
||||
```typescript
|
||||
import { query, isAbortError } from '@qwen-code/sdk';
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
const result = query({
|
||||
prompt: 'Long running task...',
|
||||
options: {
|
||||
abortController,
|
||||
},
|
||||
});
|
||||
|
||||
// Abort after 5 seconds
|
||||
setTimeout(() => abortController.abort(), 5000);
|
||||
|
||||
try {
|
||||
for await (const message of result) {
|
||||
console.log(message);
|
||||
}
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) {
|
||||
console.log('Query was aborted');
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The SDK provides an `AbortError` class for handling aborted queries:
|
||||
|
||||
```typescript
|
||||
import { AbortError, isAbortError } from '@qwen-code/sdk';
|
||||
|
||||
try {
|
||||
// ... query operations
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) {
|
||||
// Handle abort
|
||||
} else {
|
||||
// Handle other errors
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,9 +1,11 @@
|
||||
export default {
|
||||
index: 'Introduction',
|
||||
introduction: 'Introduction',
|
||||
'file-system': 'File System',
|
||||
'multi-file': 'Multi-File Read',
|
||||
shell: 'Shell',
|
||||
'todo-write': 'Todo Write',
|
||||
task: 'Task',
|
||||
'exit-plan-mode': 'Exit Plan Mode',
|
||||
'web-fetch': 'Web Fetch',
|
||||
'web-search': 'Web Search',
|
||||
memory: 'Memory',
|
||||
|
||||
149
docs/developers/tools/exit-plan-mode.md
Normal file
149
docs/developers/tools/exit-plan-mode.md
Normal file
@@ -0,0 +1,149 @@
|
||||
# Exit Plan Mode Tool (`exit_plan_mode`)
|
||||
|
||||
This document describes the `exit_plan_mode` tool for Qwen Code.
|
||||
|
||||
## Description
|
||||
|
||||
Use `exit_plan_mode` when you are in plan mode and have finished presenting your implementation plan. This tool prompts the user to approve or reject the plan and transitions from planning mode to implementation mode.
|
||||
|
||||
The tool is specifically designed for tasks that require planning implementation steps before writing code. It should NOT be used for research or information-gathering tasks.
|
||||
|
||||
### Arguments
|
||||
|
||||
`exit_plan_mode` takes one argument:
|
||||
|
||||
- `plan` (string, required): The implementation plan you want to present to the user for approval. This should be a concise, markdown-formatted plan describing the implementation steps.
|
||||
|
||||
## How to use `exit_plan_mode` with Qwen Code
|
||||
|
||||
The Exit Plan Mode tool is part of Qwen Code's planning workflow. When you're in plan mode (typically after exploring a codebase and designing an implementation approach), you use this tool to:
|
||||
|
||||
1. Present your implementation plan to the user
|
||||
2. Request approval to proceed with implementation
|
||||
3. Transition from plan mode to implementation mode based on user response
|
||||
|
||||
The tool will prompt the user with your plan and provide options to:
|
||||
|
||||
- **Proceed Once**: Approve the plan for this session only
|
||||
- **Proceed Always**: Approve the plan and enable auto-approval for future edit operations
|
||||
- **Cancel**: Reject the plan and remain in planning mode
|
||||
|
||||
Usage:
|
||||
|
||||
```
|
||||
exit_plan_mode(plan="Your detailed implementation plan here...")
|
||||
```
|
||||
|
||||
## When to Use This Tool
|
||||
|
||||
Use `exit_plan_mode` when:
|
||||
|
||||
1. **Implementation tasks**: You are planning the implementation steps for a coding task
|
||||
2. **Plan completion**: You have finished exploring and designing your implementation approach
|
||||
3. **User approval needed**: You need user confirmation before proceeding with code changes
|
||||
4. **Code writing tasks**: The task involves writing, modifying, or refactoring code
|
||||
|
||||
### Examples of appropriate usage:
|
||||
|
||||
- "Help me implement user authentication" → Use after planning the auth system implementation
|
||||
- "Add a new API endpoint for user management" → Use after designing the endpoint structure
|
||||
- "Refactor the database layer to use TypeORM" → Use after planning the refactoring approach
|
||||
|
||||
## When NOT to Use This Tool
|
||||
|
||||
Do NOT use `exit_plan_mode` for:
|
||||
|
||||
1. **Research tasks**: Tasks focused on understanding or exploring existing code
|
||||
2. **Information gathering**: When you're searching, reading, or analyzing without implementing
|
||||
3. **Documentation tasks**: When creating documentation without code changes
|
||||
4. **Analysis tasks**: When providing explanations or reviews without implementation
|
||||
|
||||
### Examples of inappropriate usage:
|
||||
|
||||
- "Search for and understand the implementation of vim mode in the codebase" → Don't use (research task)
|
||||
- "Explain how the authentication system works" → Don't use (analysis task)
|
||||
- "Find all TODO comments in the project" → Don't use (information gathering)
|
||||
|
||||
## `exit_plan_mode` examples
|
||||
|
||||
### Implementation planning example
|
||||
|
||||
```
|
||||
exit_plan_mode(plan="## Implementation Plan for User Dashboard
|
||||
|
||||
### 1. Create Dashboard Components
|
||||
- Create `UserDashboard.tsx` with main dashboard layout
|
||||
- Add `DashboardStats.tsx` for displaying user statistics
|
||||
- Implement `ActivityFeed.tsx` for recent user activities
|
||||
|
||||
### 2. Add API Integration
|
||||
- Create `dashboardApi.ts` for dashboard data fetching
|
||||
- Add endpoints for user stats and activity data
|
||||
- Implement error handling and loading states
|
||||
|
||||
### 3. Update Routing
|
||||
- Add dashboard route in `App.tsx`
|
||||
- Update navigation component with dashboard link
|
||||
- Add route protection for authenticated users
|
||||
|
||||
### 4. Testing and Documentation
|
||||
- Write unit tests for dashboard components
|
||||
- Add integration tests for API calls
|
||||
- Update user documentation with dashboard features
|
||||
|
||||
This implementation will take approximately 4-6 hours and requires changes to 8-10 files.")
|
||||
```
|
||||
|
||||
### Refactoring plan example
|
||||
|
||||
```
|
||||
exit_plan_mode(plan="## Database Layer Refactoring Plan
|
||||
|
||||
### Phase 1: Setup and Configuration
|
||||
- Install and configure TypeORM dependencies
|
||||
- Create database connection configuration
|
||||
- Set up entity definitions for existing models
|
||||
|
||||
### Phase 2: Migration
|
||||
- Create migration scripts for existing data
|
||||
- Implement new repository pattern using TypeORM
|
||||
- Replace raw SQL queries with TypeORM query builder
|
||||
|
||||
### Phase 3: Testing and Validation
|
||||
- Update all database tests to use TypeORM
|
||||
- Validate data integrity after migration
|
||||
- Performance testing to ensure no regressions
|
||||
|
||||
This refactoring will modernize our database layer while maintaining backward compatibility.")
|
||||
```
|
||||
|
||||
## User Response Handling
|
||||
|
||||
After calling `exit_plan_mode`, the user can respond in several ways:
|
||||
|
||||
- **Proceed Once**: The plan is approved for immediate implementation with default confirmation settings
|
||||
- **Proceed Always**: The plan is approved and auto-approval is enabled for subsequent edit operations
|
||||
- **Cancel**: The plan is rejected, and the system remains in plan mode for further planning
|
||||
|
||||
The tool automatically adjusts the approval mode based on the user's choice, streamlining the implementation process according to user preferences.
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Plan mode only**: This tool should only be used when you are currently in plan mode
|
||||
- **Implementation focus**: Only use for tasks that involve writing or modifying code
|
||||
- **Concise plans**: Keep plans focused and concise - aim for clarity over exhaustive detail
|
||||
- **Markdown support**: Plans support markdown formatting for better readability
|
||||
- **Single use**: The tool should be used once per planning session when ready to proceed
|
||||
- **User control**: The final decision to proceed always rests with the user
|
||||
|
||||
## Integration with Planning Workflow
|
||||
|
||||
The Exit Plan Mode tool is part of a larger planning workflow:
|
||||
|
||||
1. **Enter Plan Mode**: User requests or system determines planning is needed
|
||||
2. **Exploration Phase**: Analyze codebase, understand requirements, explore options
|
||||
3. **Plan Design**: Create implementation strategy based on exploration
|
||||
4. **Plan Presentation**: Use `exit_plan_mode` to present plan to user
|
||||
5. **Implementation Phase**: Upon approval, proceed with planned implementation
|
||||
|
||||
This workflow ensures thoughtful implementation approaches and gives users control over significant code changes.
|
||||
@@ -83,7 +83,7 @@ Qwen Code provides a comprehensive suite of tools for interacting with the local
|
||||
|
||||
- **Tool name:** `grep_search`
|
||||
- **Display name:** Grep
|
||||
- **File:** `ripGrep.ts` (with `grep.ts` as fallback)
|
||||
- **File:** `grep.ts` (with `ripGrep.ts` as fallback)
|
||||
- **Parameters:**
|
||||
- `pattern` (string, required): The regular expression pattern to search for in file contents (e.g., `"function\\s+myFunction"`, `"log.*Error"`).
|
||||
- `path` (string, optional): File or directory to search in. Defaults to current working directory.
|
||||
@@ -141,7 +141,7 @@ grep_search(pattern="function", glob="*.js", limit=10)
|
||||
- `file_path` (string, required): The absolute path to the file to modify.
|
||||
- `old_string` (string, required): The exact literal text to replace.
|
||||
|
||||
**CRITICAL:** This string must uniquely identify the single instance to change. It should include at least 3 lines of context _before_ and _after_ the target text, matching whitespace and indentation precisely. If `old_string` is empty, the tool attempts to create a new file at `file_path` with `new_string` as content.
|
||||
**CRITICAL:** This string must uniquely identify the single instance to change. It should include sufficient context around the target text, matching whitespace and indentation precisely. If `old_string` is empty, the tool attempts to create a new file at `file_path` with `new_string` as content.
|
||||
|
||||
- `new_string` (string, required): The exact literal text to replace `old_string` with.
|
||||
- `replace_all` (boolean, optional): Replace all occurrences of `old_string`. Defaults to `false`.
|
||||
|
||||
@@ -50,6 +50,8 @@ Qwen Code's built-in tools can be broadly categorized as follows:
|
||||
- **[Multi-File Read Tool](./multi-file.md) (`read_many_files`):** A specialized tool for reading content from multiple files or directories, often used by the `@` command.
|
||||
- **[Memory Tool](./memory.md) (`save_memory`):** For saving and recalling information across sessions.
|
||||
- **[Todo Write Tool](./todo-write.md) (`todo_write`):** For creating and managing structured task lists during coding sessions.
|
||||
- **[Task Tool](./task.md) (`task`):** For delegating complex tasks to specialized subagents.
|
||||
- **[Exit Plan Mode Tool](./exit-plan-mode.md) (`exit_plan_mode`):** For exiting plan mode and proceeding with implementation.
|
||||
|
||||
Additionally, these tools incorporate:
|
||||
|
||||
145
docs/developers/tools/task.md
Normal file
145
docs/developers/tools/task.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# Task Tool (`task`)
|
||||
|
||||
This document describes the `task` tool for Qwen Code.
|
||||
|
||||
## Description
|
||||
|
||||
Use `task` to launch a specialized subagent to handle complex, multi-step tasks autonomously. The Task tool delegates work to specialized agents that can work independently with access to their own set of tools, allowing for parallel task execution and specialized expertise.
|
||||
|
||||
### Arguments
|
||||
|
||||
`task` takes the following arguments:
|
||||
|
||||
- `description` (string, required): A short (3-5 word) description of the task for user visibility and tracking purposes.
|
||||
- `prompt` (string, required): The detailed task prompt for the subagent to execute. Should contain comprehensive instructions for autonomous execution.
|
||||
- `subagent_type` (string, required): The type of specialized agent to use for this task. Must match one of the available configured subagents.
|
||||
|
||||
## How to use `task` with Qwen Code
|
||||
|
||||
The Task tool dynamically loads available subagents from your configuration and delegates tasks to them. Each subagent runs independently and can use its own set of tools, allowing for specialized expertise and parallel execution.
|
||||
|
||||
When you use the Task tool, the subagent will:
|
||||
|
||||
1. Receive the task prompt with full autonomy
|
||||
2. Execute the task using its available tools
|
||||
3. Return a final result message
|
||||
4. Terminate (subagents are stateless and single-use)
|
||||
|
||||
Usage:
|
||||
|
||||
```
|
||||
task(description="Brief task description", prompt="Detailed task instructions for the subagent", subagent_type="agent_name")
|
||||
```
|
||||
|
||||
## Available Subagents
|
||||
|
||||
The available subagents depend on your configuration. Common subagent types might include:
|
||||
|
||||
- **general-purpose**: For complex multi-step tasks requiring various tools
|
||||
- **code-reviewer**: For reviewing and analyzing code quality
|
||||
- **test-runner**: For running tests and analyzing results
|
||||
- **documentation-writer**: For creating and updating documentation
|
||||
|
||||
You can view available subagents by using the `/agents` command in Qwen Code.
|
||||
|
||||
## Task Tool Features
|
||||
|
||||
### Real-time Progress Updates
|
||||
|
||||
The Task tool provides live updates showing:
|
||||
|
||||
- Subagent execution status
|
||||
- Individual tool calls being made by the subagent
|
||||
- Tool call results and any errors
|
||||
- Overall task progress and completion status
|
||||
|
||||
### Parallel Execution
|
||||
|
||||
You can launch multiple subagents concurrently by calling the Task tool multiple times in a single message, allowing for parallel task execution and improved efficiency.
|
||||
|
||||
### Specialized Expertise
|
||||
|
||||
Each subagent can be configured with:
|
||||
|
||||
- Specific tool access permissions
|
||||
- Specialized system prompts and instructions
|
||||
- Custom model configurations
|
||||
- Domain-specific knowledge and capabilities
|
||||
|
||||
## `task` examples
|
||||
|
||||
### Delegating to a general-purpose agent
|
||||
|
||||
```
|
||||
task(
|
||||
description="Code refactoring",
|
||||
prompt="Please refactor the authentication module in src/auth/ to use modern async/await patterns instead of callbacks. Ensure all tests still pass and update any related documentation.",
|
||||
subagent_type="general-purpose"
|
||||
)
|
||||
```
|
||||
|
||||
### Running parallel tasks
|
||||
|
||||
```
|
||||
# Launch code review and test execution in parallel
|
||||
task(
|
||||
description="Code review",
|
||||
prompt="Review the recent changes in the user management module for code quality, security issues, and best practices compliance.",
|
||||
subagent_type="code-reviewer"
|
||||
)
|
||||
|
||||
task(
|
||||
description="Run tests",
|
||||
prompt="Execute the full test suite and analyze any failures. Provide a summary of test coverage and recommendations for improvement.",
|
||||
subagent_type="test-runner"
|
||||
)
|
||||
```
|
||||
|
||||
### Documentation generation
|
||||
|
||||
```
|
||||
task(
|
||||
description="Update docs",
|
||||
prompt="Generate comprehensive API documentation for the newly implemented REST endpoints in the orders module. Include request/response examples and error codes.",
|
||||
subagent_type="documentation-writer"
|
||||
)
|
||||
```
|
||||
|
||||
## When to Use the Task Tool
|
||||
|
||||
Use the Task tool when:
|
||||
|
||||
1. **Complex multi-step tasks** - Tasks requiring multiple operations that can be handled autonomously
|
||||
2. **Specialized expertise** - Tasks that benefit from domain-specific knowledge or tools
|
||||
3. **Parallel execution** - When you have multiple independent tasks that can run simultaneously
|
||||
4. **Delegation needs** - When you want to hand off a complete task rather than micromanaging steps
|
||||
5. **Resource-intensive operations** - Tasks that might take significant time or computational resources
|
||||
|
||||
## When NOT to Use the Task Tool
|
||||
|
||||
Don't use the Task tool for:
|
||||
|
||||
- **Simple, single-step operations** - Use direct tools like Read, Edit, etc.
|
||||
- **Interactive tasks** - Tasks requiring back-and-forth communication
|
||||
- **Specific file reads** - Use Read tool directly for better performance
|
||||
- **Simple searches** - Use Grep or Glob tools directly
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Stateless execution**: Each subagent invocation is independent with no memory of previous executions
|
||||
- **Single communication**: Subagents provide one final result message - no ongoing communication
|
||||
- **Comprehensive prompts**: Your prompt should contain all necessary context and instructions for autonomous execution
|
||||
- **Tool access**: Subagents only have access to tools configured in their specific configuration
|
||||
- **Parallel capability**: Multiple subagents can run simultaneously for improved efficiency
|
||||
- **Configuration dependent**: Available subagent types depend on your system configuration
|
||||
|
||||
## Configuration
|
||||
|
||||
Subagents are configured through Qwen Code's agent configuration system. Use the `/agents` command to:
|
||||
|
||||
- View available subagents
|
||||
- Create new subagent configurations
|
||||
- Modify existing subagent settings
|
||||
- Set tool permissions and capabilities
|
||||
|
||||
For more information on configuring subagents, refer to the subagents documentation.
|
||||
@@ -11,9 +11,9 @@ Use `todo_write` to create and manage a structured task list for your current co
|
||||
`todo_write` takes one argument:
|
||||
|
||||
- `todos` (array, required): An array of todo items, where each item contains:
|
||||
- `id` (string, required): A unique identifier for the todo item.
|
||||
- `content` (string, required): The description of the task.
|
||||
- `status` (string, required): The current status (`pending`, `in_progress`, or `completed`).
|
||||
- `activeForm` (string, required): The present continuous form describing what is being done (e.g., "Running tests", "Building the project").
|
||||
|
||||
## How to use `todo_write` with Qwen Code
|
||||
|
||||
@@ -39,19 +39,19 @@ Creating a feature implementation plan:
|
||||
```
|
||||
todo_write(todos=[
|
||||
{
|
||||
"id": "create-model",
|
||||
"content": "Create user preferences model",
|
||||
"status": "pending"
|
||||
"status": "pending",
|
||||
"activeForm": "Creating user preferences model"
|
||||
},
|
||||
{
|
||||
"id": "add-endpoints",
|
||||
"content": "Add API endpoints for preferences",
|
||||
"status": "pending"
|
||||
"status": "pending",
|
||||
"activeForm": "Adding API endpoints for preferences"
|
||||
},
|
||||
{
|
||||
"id": "implement-ui",
|
||||
"content": "Implement frontend components",
|
||||
"status": "pending"
|
||||
"status": "pending",
|
||||
"activeForm": "Implementing frontend components"
|
||||
}
|
||||
])
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user