### Example: Install 'prompts.chat' Plugin Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/extension/introduction.md Example demonstrating how to install the 'prompts.chat' plugin from the 'f/awesome-chatgpt-prompts' marketplace using both marketplace name and GitHub URL. ```bash qwen extensions install f/awesome-chatgpt-prompts:prompts.chat # or qwen extensions install https://github.com/f/awesome-chatgpt-prompts:prompts.chat ``` -------------------------------- ### Install the package Source: https://github.com/qwenlm/qwen-code/blob/main/packages/channels/plugin-example/README.md Install the plugin example package using npm. ```bash npm install @qwen-code/channel-plugin-example ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/apps/electron/README.md Installs project dependencies using Bun and starts the Electron development server. ```bash bun install bun run electron:start ``` -------------------------------- ### Install and Run Development Server Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/README.md Install project dependencies using Bun and start the development server. ```bash bun install bun run dev ``` -------------------------------- ### Canonical Multi-Step Workflow Example Source: https://github.com/qwenlm/qwen-code/blob/main/packages/cua-driver/swift/Skills/cua-driver/SKILL.md A sequence of commands demonstrating a typical workflow: starting the daemon, launching an app, getting window state, clicking an element, and stopping the daemon. ```bash open -n -g -a CuaDriver --args serve cua-driver launch_app '{"bundle_id":"com.apple.calculator"}' # → {pid: 844, windows: [{window_id: 10725, ...}]} cua-driver get_window_state '{"pid":844,"window_id":10725}' cua-driver click '{"pid":844,"window_id":10725,"element_index":14}' cua-driver stop ``` -------------------------------- ### ModelStudio Standard API Key Setup Flow Source: https://github.com/qwenlm/qwen-code/blob/main/docs/design/custom-api-key-auth-wizard-prd.md Example of a guided setup flow already present for 'Alibaba Cloud ModelStudio Standard API Key', which the custom API key wizard aims to emulate for other providers. ```text Alibaba Cloud ModelStudio Standard API Key └─ Select Region └─ Enter API Key └─ Enter Model IDs └─ Save + authenticate ``` -------------------------------- ### Qwen Serve Output Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/daemon/20-quickstart-operations.md Example output when starting the qwen serve daemon, indicating the listening address, mode, and workspace. ```text qwen serve listening on http://127.0.0.1:4170 (mode=http-bridge, workspace=/your/cwd) qwen serve: bound to workspace "/your/cwd" qwen serve: bearer auth disabled (loopback default). Set QWEN_SERVER_TOKEN to enable. ``` -------------------------------- ### Install State JSON Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/superpowers/plans/2026-05-28-computer-use-built-in.md This is an example of the JSON structure used to persist the installation state, including the approved package specification and the approval timestamp. ```json { "approvedPackageSpec": "open-computer-use@^0.3.0", "approvedAtIso": "2026-05-28T10:00:00Z" } ``` -------------------------------- ### Setup Local Development Environment Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/tools/sandbox.md Commands to install dependencies, build the project, and create a global symbolic link to the source code. ```bash # 1. First, install the dependencies of the project npm install # 2. Build the Qwen Code project npm run build # 3. Verify that the dist directory has been generated ls -la packages/cli/dist/ # 4. Create a global link in the CLI package directory cd packages/cli npm link # 5. Verification link (it should now point to the source code) which qwen # Expected output: /xxx/xxx/.nvm/versions/node/v24.11.1/bin/qwen # Or similar paths, but it should be a symbolic link # 6. For details of the symbolic link, you can see the specific source code path ls -la $(dirname $(which qwen))/../lib/node_modules/@qwen-code/qwen-code # It should show that this is a symbolic link pointing to your source code directory # 7.Test the version of qwen qwen -v # npm link will overwrite the global qwen. To avoid being unable to distinguish the same version number, you can uninstall the global CLI first ``` -------------------------------- ### Example Agent Conversational Flow for Source Setup Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/apps/electron/resources/docs/sources.md Illustrates a typical conversational flow between a user and an agent when setting up a new source, including search, clarification, configuration, and testing steps. ```text User: I want to add Linear Agent: [FIRST: Searches for Linear guide] mcp__craft-agents-docs__SearchCraftAgents({ query: "linear source setup" }) Agent: I found the Linear setup guide! A few questions: 1. What will you primarily use Linear for? (issue tracking, sprint planning, reporting?) 2. Are there specific teams or projects you want to focus on? 3. Should I set it up for read-only exploration or full access? User: Issue tracking for my iOS team, project called "Craft iOS" Agent: [Uses WebSearch to verify current Linear MCP URL] Agent: [Creates config.json with: - icon: (searches web for app icon or uses favicon) - tagline: "Issue tracking for the Craft iOS team" - OAuth authentication] Agent: [Writes guide.md mentioning "Craft iOS" project and iOS team context] Agent: [Sets up permissions.json for read-only listing in Explore mode] Agent: [MANDATORY: Runs source_test to validate] mcp__session__source_test({ sourceSlug: "linear" }) Agent: [Triggers source_oauth_trigger for authentication] mcp__session__source_oauth_trigger({ sourceSlug: "linear" }) Agent: Linear is now set up! I've configured it to focus on the "Craft iOS" project. You can use it to: - Search and view issues in Craft iOS - Track sprint progress for the iOS team - Create and update issues Would you like me to show you what issues are currently open? ``` -------------------------------- ### Python SDK Example for Qwen Code Source: https://github.com/qwenlm/qwen-code/blob/main/README.md Demonstrates how to use the Qwen Code Python SDK to query for information, such as summarizing a repository layout. Ensure the SDK is installed and configured. ```python import asyncio from qwen_code_sdk import is_sdk_result_message, query async def main() -> None: result = query( "Summarize the repository layout.", { "cwd": "/path/to/project", "path_to_qwen_executable": "qwen", }, ) async for message in result: if is_sdk_result_message(message): print(message["result"]) asyncio.run(main()) ``` -------------------------------- ### Example Custom API Key Setup Flow Source: https://github.com/qwenlm/qwen-code/blob/main/docs/design/custom-api-key-auth-wizard-prd.md Illustrates the step-by-step process a user will follow within the terminal wizard to configure a custom API key. This flow replaces manual editing of `settings.json`. ```text Select Protocol -> Enter Base URL -> Enter API Key -> Enter Model IDs -> Review JSON -> Save + authenticate ``` -------------------------------- ### One-File `settings.json` Setup for API Key Authentication Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/configuration/auth.md This is a complete example for `~/.qwen/settings.json` to configure API key authentication for Qwen Code. It specifies model providers, environment variables for API keys, security authentication type, and the default model. ```json { "modelProviders": { "openai": { "protocol": "openai", "models": [ { "id": "qwen3-coder-plus", "name": "qwen3-coder-plus", "baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1", "description": "Qwen3-Coder via Dashscope", "envKey": "DASHSCOPE_API_KEY" } ] } }, "env": { "DASHSCOPE_API_KEY": "sk-xxxxxxxxxxxxx" }, "security": { "auth": { "selectedType": "openai" } }, "model": { "name": "qwen3-coder-plus" } } ``` -------------------------------- ### Bootstrap State Machine Source: https://github.com/qwenlm/qwen-code/blob/main/docs/superpowers/plans/2026-05-28-computer-use-built-in.md The 'bootstrap.ts' file contains the state machine logic for the computer-use integration. This includes probing for existing installations, handling installation confirmations, performing the installation, and guiding the user through permission setup. ```typescript bootstrap.ts # state machine: probe → install confirm → install → perm guide ``` -------------------------------- ### Initialize Source Guide Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/apps/electron/resources/docs/craft-cli.md Scaffolds a practical 'guide.md' file based on the source type. Supports 'generic', 'mcp', 'api', and 'local' templates. ```bash craft-agent source init-guide linear --template mcp ``` -------------------------------- ### Example Configuration in settings.json Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/features/tool-use-summaries.md An example of how to configure both the fast model and the experimental tool use summaries setting in settings.json. ```json { "fastModel": "qwen3-coder-flash", "experimental": { "emitToolUseSummaries": true } } ``` -------------------------------- ### GET /session/:id/context Response Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Example response for retrieving session context using GET /session/:id/context. It includes workspace information and the current state of models, modes, and configuration options. ```json { "v": 1, "sessionId": "", "workspaceCwd": "/canonical/path", "state": { "models": {}, "modes": {}, "configOptions": [] } } ``` -------------------------------- ### Implementation Planning Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/tools/exit-plan-mode.md An example of using the tool to present a multi-step plan for creating a user dashboard. ```text 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.") ``` -------------------------------- ### Start Documentation Development Server Source: https://github.com/qwenlm/qwen-code/blob/main/CONTRIBUTING.md Launch the local development server for the documentation site to preview changes. ```bash npm run dev ``` -------------------------------- ### Computer Use Bootstrap State Machine Implementation Source: https://github.com/qwenlm/qwen-code/blob/main/docs/superpowers/plans/2026-05-28-computer-use-built-in.md This TypeScript code defines the bootstrap state machine for the computer use feature. It handles initial setup, including user approval for installation, starting the client, and probing/managing permissions on macOS. The implementation is designed to be swappable for different approval mechanisms. ```typescript /** * @license * Copyright 2025 Qwen Team * SPDX-License-Identifier: Apache-2.0 */ /** * Computer Use bootstrap state machine. * * On first invocation of any computer_use__* tool: * 1. If not yet approved: prompt the user to install (one-time). * 2. Start the client (lazy npx spawn, may take ~60s first time). * 3. On macOS only: probe permissions by calling get_app_state on * Finder. If a permission error surfaces, spawn the upstream * doctor (which opens the system settings + onboarding window), * then poll until permissions grant or 10 min timeout. * * IMPLEMENTER: pre-step 1 (Task 10 step 1) — verify whether * qwen-code's BaseDeclarativeTool exposes a `shouldConfirmExecute()` * pathway from inside `execute()`. If not, `promptInstallApproval` * defaults to a `process.stderr.write` + readline fallback. The * dependency-injection design here keeps that decision swappable * without touching the state machine logic. */ import { spawn } from 'node:child_process'; import { homedir } from 'node:os'; import type { ComputerUseClient } from './client.js'; import { isPackageSpecApproved, saveInstallState } from './install-state.js'; import { detectPermissionError, type PermissionErrorKind, } from './permission-detector.js'; export interface BootstrapContext { signal: AbortSignal; updateOutput?: (output: string) => void; } /** Result of a permission probe. */ export type PermissionProbeResult = 'ok' | PermissionErrorKind; export interface BootstrapDeps { homeDir: string; packageSpec: string; platform: NodeJS.Platform; /** * Prompt the user to approve installing the upstream binary. Returns * true if approved. Implementation may use the qwen-code confirm * tool path or a stdin fallback. */ promptInstallApproval: (packageSpec: string) => Promise; /** * Spawn `open-computer-use doctor` (detached). The binary handles * opening the system settings window itself. */ spawnDoctor: () => void; /** * Probe the upstream MCP server for permission state by issuing a * lightweight tool call. Returns 'ok' on success or the kind of * permission error on failure. */ probePermissions: ( client: ComputerUseClient, ) => Promise; /** Poll interval for the permission watcher. Default 2000ms. */ pollIntervalMs?: number; /** Total poll timeout. Default 10 min. */ pollTimeoutMs?: number; } /** Production defaults — instantiated lazily so tests can override per call. */ function defaultDeps(): BootstrapDeps { return { homeDir: homedir(), packageSpec: process.env['QWEN_COMPUTER_USE_PACKAGE'] ?? 'open-computer-use@latest', platform: process.platform, promptInstallApproval: async (spec) => { // v0 fallback: stderr prompt + stdin read. Replace with // qwen-code's standard confirm pathway when wired in. process.stderr.write( `\n[Computer Use] First-time install\n` + ` Package: ${spec}\n` + ` This will fetch ~50MB from the npm registry the first time. ` + ` Computer Use can click, type, and read your desktop apps. ` + ` On macOS you'll be guided through Accessibility and Screen Recording permissions next. ` + `Proceed? [y/N] `, ); // IMPLEMENTER: in real interactive sessions, replace with the // qwen-code confirm system. For headless / SDK contexts the // default is to refuse — explicit user opt-in required. return process.env['QWEN_COMPUTER_USE_AUTO_APPROVE'] === '1'; }, spawnDoctor: () => { const child = spawn('npx', ['-y', defaultDeps().packageSpec, 'doctor'], { detached: true, stdio: 'ignore', }); child.unref(); }, probePermissions: async (client) => { // Use Finder as a known-running, always-installed macOS app. // get_app_state hits AccessibilitySnapshot which is the first // path that throws permissionDenied. const result = await client.callTool('get_app_state', { app: 'Finder' }); return detectPermissionError(result) === 'none' ? 'ok' : detectPermissionError(result); }, }; } export async function runBootstrap( client: ComputerUseClient, ctx: BootstrapContext, depsOverride?: Partial, ): Promise { const deps: BootstrapDeps = { ...defaultDeps(), ...depsOverride }; const pollIntervalMs = deps.pollIntervalMs ?? 2000; const pollTimeoutMs = deps.pollTimeoutMs ?? 10 * 60_000; ``` -------------------------------- ### Start Qwen Code in a Project Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/overview.md Navigate to your project directory and run the 'qwen' command to start using Qwen Code. You will be prompted to connect a model provider on first launch. ```bash cd your-project qwen ``` -------------------------------- ### Check cua-driver installation Source: https://github.com/qwenlm/qwen-code/blob/main/packages/cua-driver/rust/Skills/cua-driver/MACOS.md Verify that the cua-driver executable is available in the system's PATH. If not, guide the user to install it locally. ```bash which cua-driver ``` -------------------------------- ### Bootstrap Computer Use Installation and Permissions Source: https://github.com/qwenlm/qwen-code/blob/main/docs/superpowers/plans/2026-05-28-computer-use-built-in.md Handles the initial installation approval, starting the client, and probing/managing macOS permissions. It includes a polling mechanism to wait for user-granted permissions. ```typescript // Step 1: install approval gate. const approved = await isPackageSpecApproved(deps.homeDir, deps.packageSpec); if (!approved) { ctx.updateOutput?.('Computer Use needs to be installed (first use).'); const ok = await deps.promptInstallApproval(deps.packageSpec); if (!ok) { throw new Error( `Computer Use install declined by user. Re-invoke the tool to be prompted again.`, ); } await saveInstallState(deps.homeDir, { approvedPackageSpec: deps.packageSpec, approvedAtIso: new Date().toISOString(), }); } // Step 2: spawn (idempotent). if (!client.isStarted()) { ctx.updateOutput?.('Starting Computer Use...'); await client.start(); } // Step 3: macOS permission probe + guide. if (deps.platform !== 'darwin') return; const probe = await deps.probePermissions(client); if (probe === 'ok' || probe === 'other') { // 'other' means an error happened that isn't permission-related. // We don't block bootstrap on that — let the actual tool call surface it. return; } ctx.updateOutput?.( `Computer Use needs macOS permissions (${probe}). ` + `An onboarding window will open — please grant Accessibility and Screen Recording, then this will continue automatically.`, ); deps.spawnDoctor(); const startedAt = Date.now(); for (;;) { if (ctx.signal.aborted) { throw new Error('Computer Use bootstrap aborted.'); } if (Date.now() - startedAt > pollTimeoutMs) { throw new Error( `Computer Use permission grant timed out after ${Math.round(pollTimeoutMs / 1000)}s. Re-invoke the tool to retry.`, ); } await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); const next = await deps.probePermissions(client); if (next === 'ok' || next === 'other') return; const elapsedSec = Math.round((Date.now() - startedAt) / 1000); ctx.updateOutput?.(`Waiting for permissions... (${elapsedSec}s)`); } } ``` -------------------------------- ### Install qwen-code-sdk Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/sdk-python.md Install the SDK using pip. Use --pre for preview releases. ```bash pip install qwen-code-sdk ``` ```bash pip install --pre qwen-code-sdk ``` -------------------------------- ### Authorization Header Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md When the daemon is started with a token, this header must be included in requests to most routes. ```http Authorization: Bearer ``` -------------------------------- ### GET /file Response Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Successful response for reading a text file using the GET /file endpoint. It includes file metadata, content, and a SHA-256 hash of the file's raw bytes. ```json { "kind": "file", "path": "src/index.ts", "content": "export {};\n", "encoding": "utf-8", "bom": false, "lineEnding": "lf", "sizeBytes": 11, "returnedBytes": 11, "truncated": false, "hash": "sha256:...", "matchedIgnore": null, "originalLineCount": null } ``` -------------------------------- ### Workspace Skills Response Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Example JSON response for the GET /workspace/skills endpoint, listing available skills. ```json { "v": 1, "workspaceCwd": "/canonical/path", "initialized": true, "skills": [ { "kind": "skill", "status": "ok", "name": "review", "description": "Review code", "level": "project", "modelInvocable": true, "argumentHint": "[path]" } ] } ``` -------------------------------- ### Setup Test Directory and Clone Repository Source: https://github.com/qwenlm/qwen-code/blob/main/docs/e2e-tests/worktree-phase-d.md Initializes a temporary directory, clones the qwen-code repository into it, and extracts a project ID from the directory path. ```bash # Use qwen-code itself as the test repo TEST_DIR=$(mktemp -d -t qwen-wt-phd-pr-XXXXXX) TEST_DIR=$(cd "$TEST_DIR" && pwd -P) cd "$TEST_DIR" git clone --depth 1 https://github.com/QwenLM/qwen-code.git . PROJECT_ID=$(node -e "console.log(process.argv[1].replace(/[^a-zA-Z0-9]/g,'-'))" "$TEST_DIR") ``` -------------------------------- ### GET /file/bytes Response Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Successful response for reading raw bytes from a file using the GET /file/bytes endpoint. This is suitable for binary files and includes byte counts and a hash if the entire file is returned. ```json { "kind": "file_bytes", "path": "assets/logo.png", "offset": 0, "sizeBytes": 3912, "returnedBytes": 3912, "truncated": false, "contentBase64": "...", "hash": "sha256:..." } ``` -------------------------------- ### Simple Query Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/sdk-java.md Demonstrates the simplest way to use the SDK by performing a basic query. ```java public static void runSimpleExample() { List result = QwenCodeCli.simpleQuery("hello world"); result.forEach(logger::info); } ``` -------------------------------- ### Workspace Environment Response Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Example JSON response for the GET /workspace/env endpoint, showing runtime and environment variables. ```json { "v": 1, "workspaceCwd": "/canonical/path", "initialized": true, "acpChannelLive": false, "cells": [ { "kind": "runtime", "name": "node", "status": "ok", "value": "22.4.0" }, { "kind": "platform", "name": "darwin", "status": "ok", "value": "arm64" }, { "kind": "sandbox", "name": "SANDBOX", "status": "disabled", "present": false }, { "kind": "proxy", "name": "HTTPS_PROXY", "status": "ok", "present": true, "value": "proxy.internal:1080" }, { "kind": "proxy", "name": "NO_PROXY", "status": "disabled", "present": false }, { "kind": "env_var", "name": "OPENAI_API_KEY", "status": "ok", "present": true }, { "kind": "env_var", "name": "ANTHROPIC_BASE_URL", "status": "disabled", "present": false } ] } ``` -------------------------------- ### Example Question: MCP Integration Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/common-workflow.md Ask how to use MCP (Multi-Cloud Platform) with Qwen Code. ```text how do I use MCP with Qwen Code? ``` -------------------------------- ### Setup Local Development Environment Source: https://github.com/qwenlm/qwen-code/blob/main/docs/verification/abort-controller-refactor/README.md Sets up the local worktree, log directory, and builds the CLI packages. This is a one-time setup before running verification scenarios. ```sh # Point WT at your local checkout of the branch under review. WT=/path/to/qwen-code/worktree LOGDIR=$WT/docs/verification/abort-controller-refactor/logs mkdir -p "$LOGDIR" # Build the CLI once (skip sandbox image, skip vscode). ( cd "$WT" && npm run build:packages ) ``` -------------------------------- ### Workspace Providers Response Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Example JSON response for the GET /workspace/providers endpoint, detailing available model providers. ```json { "v": 1, "workspaceCwd": "/canonical/path", "initialized": true, "current": { "authType": "qwen", "modelId": "qwen3(qwen)" }, "providers": [ { "kind": "model_provider", "status": "ok", "authType": "qwen", "current": true, "models": [ { "modelId": "qwen3(qwen)", "baseModelId": "qwen3", "name": "Qwen 3", "description": null, "contextLimit": 4096, "isCurrent": true, "isRuntime": false } ] } ] } ``` -------------------------------- ### Query Instance Methods Example Source: https://github.com/qwenlm/qwen-code/blob/main/packages/sdk-typescript/README.md Demonstrates how to use various methods on a Query instance, including getting session ID, checking if closed, interrupting, changing permission mode and model, getting context usage, and closing the session. ```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'); // Get context window usage breakdown (token counts per category) const usage = await q.getContextUsage(); // Pass true to hint that per-item details should be displayed const detail = await q.getContextUsage(true); // Close the session await q.close(); ``` -------------------------------- ### Basic Sub-agent Configuration Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/features/sub-agents.md A simple sub-agent configuration example focusing on name and description, suitable for basic agent setup. ```yaml --- name: project-documenter description: Creates project documentation and README files --- You are a documentation specialist. Focus on creating clear, comprehensive documentation that helps both new contributors and end users understand the project. ``` -------------------------------- ### Install qwen-code-sdk Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/sdk-python.md Install the SDK using pip. Preview releases are available with the --pre flag. ```bash pip install qwen-code-sdk # For preview releases: pip install --pre qwen-code-sdk ``` -------------------------------- ### Start Qwen Code CLI Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/configuration/auth.md Run this command to start the Qwen Code CLI and access the authentication menu. This is the initial step for configuring authentication. ```bash qwen ``` -------------------------------- ### Capabilities Response Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Example response for the `GET /capabilities` endpoint. This provides information about the daemon's protocol versions, features, and workspace configuration. ```json { "v": 1, "protocolVersions": { "current": "v1", "supported": ["v1"] }, "mode": "http-bridge", "features": ["health", "daemon_status", "capabilities", "..."], "modelServices": [], "workspaceCwd": "/canonical/path/to/workspace" } ``` -------------------------------- ### Start Qwen Code Session Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/quickstart.md Open your terminal in a project directory and start Qwen Code. Type `/help` for available commands. ```bash # optional cd /path/to/your/project # start qwen qwen ``` -------------------------------- ### Daemon Status Response (Summary) Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Example response for the `GET /daemon/status` endpoint with `detail=summary`. This provides a high-level overview of the daemon's state. ```json { "v": 1, "detail": "summary", "generatedAt": "2026-06-16T00:00:00.000Z", "status": "ok", "issues": [], "daemon": { "pid": 12345, "uptimeMs": 3600000, "mode": "http-bridge", "workspaceCwd": "/repo", "qwenCodeVersion": "0.18.1", "daemonId": "serve-..." }, "security": { "tokenConfigured": true, "requireAuth": false, "loopbackBind": true, "allowOriginConfigured": false, "allowOriginMode": "none", "sessionShellCommandEnabled": false }, "limits": { "maxSessions": 20, "maxPendingPromptsPerSession": 5, "listenerMaxConnections": 256, "eventRingSize": 8000, "promptDeadlineMs": null, "writerIdleTimeoutMs": null, "channelIdleTimeoutMs": 0, "sessionIdleTimeoutMs": 1800000, "acpConnectionCap": 64 }, "runtime": { "sessions": { "active": 0 }, "permissions": { "pending": 0, "policy": "first-responder" }, "channel": { "live": false }, "transport": { "restSseActive": 0, "acp": { "enabled": true, "connections": 0, "connectionStreams": 0, "sessionStreams": 0, "sseStreams": 0, "wsStreams": 0, "pendingClientRequests": 0 } } } } ``` -------------------------------- ### SKILL.md requiredSources Example Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/apps/electron/resources/docs/skills.md The 'requiredSources' field specifies source slugs that should be auto-enabled when the skill is invoked. This ensures necessary data sources are available from the start of the session. ```yaml requiredSources: - linear # Auto-enable Linear source - github # Auto-enable GitHub source ``` -------------------------------- ### Async Quick Start with qwen-code-sdk Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/sdk-python.md Demonstrates how to use the async query function for interacting with Qwen Code. Requires an asyncio event loop. ```python import asyncio from qwen_code_sdk import ( is_sdk_assistant_message, is_sdk_result_message, query, ) def extract_text(message): content = message.get("message", {}).get("content", []) if not isinstance(content, list): return repr(content) texts = [ block.get("text", "") for block in content if isinstance(block, dict) and block.get("type") == "text" ] return "".join(texts) if texts else "[no text content]" def print_result(message): if message.get("is_error"): error = message.get("error") or {} print(f"Error: {error.get('message', 'Unknown error')}") return print(message.get("result", "")) async def main() -> None: async with query( "Explain the repository structure.", { "cwd": "/path/to/project", "path_to_qwen_executable": "qwen", }, ) as result: async for message in result: if is_sdk_assistant_message(message): print(extract_text(message)) elif is_sdk_result_message(message): print_result(message) asyncio.run(main()) ``` -------------------------------- ### Stream-JSON Output Example Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/features/headless.md Streaming JSON output provides immediate feedback on session events, such as session start, assistant messages, and execution results, as they happen. ```json {"type":"system","subtype":"session_start","uuid":"...","session_id":"..."} {"type":"assistant","uuid":"...","session_id":"...","message":{...}} {"type":"result","subtype":"success","uuid":"...","session_id":"..."} ``` -------------------------------- ### Start the mock server Source: https://github.com/qwenlm/qwen-code/blob/main/packages/channels/plugin-example/README.md Start the mock WebSocket server using the provided command. Ports can be customized using environment variables. ```bash npx qwen-channel-plugin-example-server ``` ```bash HTTP_PORT=8080 WS_PORT=8081 npx qwen-channel-plugin-example-server ``` -------------------------------- ### Device-flow SSE Event: auth_device_flow_started Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/qwen-serve-protocol.md Emitted when a device flow is successfully started. The SDK should subscribe to this event and can fetch user code/verification URI via GET if needed. ```json { "deviceFlowId": "fa07c61b-…", "providerId": "qwen-oauth", "expiresAt": 1700000600000 } ``` -------------------------------- ### Source Icon Configuration Examples Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/apps/electron/resources/docs/sources.md Examples demonstrating different ways to configure the source icon, including emoji, local paths, and URLs. ```json { "icon": "📝" } ``` ```json { "icon": "./icon.svg" } ``` ```json { "icon": "https://linear.app/static/favicon.svg" } ``` ```json {} ``` -------------------------------- ### Canonical Multi-Step Workflow Example Source: https://github.com/qwenlm/qwen-code/blob/main/packages/cua-driver/rust/Skills/cua-driver/SKILL.md An example demonstrating a typical sequence of cua-driver commands for launching an application and interacting with its windows. ```bash cua-driver serve cua-driver launch_app '{"bundle_id":"..."}' # → {pid: 844, windows: [{window_id: 10725, ...}]} cua-driver get_window_state '{"pid":844,"window_id":10725}' cua-driver click '{"pid":844,"window_id":10725,"element_index":14}' cua-driver stop ``` -------------------------------- ### Async Quick Start with Qwen Code SDK Source: https://github.com/qwenlm/qwen-code/blob/main/packages/sdk-python/README.md Example of using the asynchronous query API to interact with Qwen Code. Handles assistant messages and result messages, including errors. ```python import asyncio from qwen_code_sdk import ( is_sdk_assistant_message, is_sdk_result_message, query, ) def text_from_message(message): content = message.get("message", {}).get("content", []) if not isinstance(content, list): return repr(content) texts = [ block.get("text", "") for block in content if isinstance(block, dict) and block.get("type") == "text" ] return "".join(texts) if texts else "[no text content]" def print_result(message): if message.get("is_error"): error = message.get("error") or {} print(f"Error: {error.get('message', 'Unknown error')}") return print(message.get("result", "")) async def main() -> None: async with query( "List the top-level packages in this repository.", { "cwd": "/path/to/project", "path_to_qwen_executable": "qwen", }, ) as result: async for message in result: if is_sdk_assistant_message(message): print(text_from_message(message)) elif is_sdk_result_message(message): print_result(message) asyncio.run(main()) ``` -------------------------------- ### Install SDK Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/examples/daemon-client-quickstart.md Install the Qwen SDK package using npm in your project directory. ```bash npm install @qwen-code/sdk ``` -------------------------------- ### Google Credentials OAuth Configuration Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/tools/mcp-server.md Example JSON configuration for an MCP server using Google credentials for authentication. This setup requires specifying the HTTP URL and the necessary OAuth scopes. ```json { "mcpServers": { "googleCloudServer": { "httpUrl": "https://my-gcp-service.run.app/mcp", "authProviderType": "google_credentials", "oauth": { "scopes": ["https://www.googleapis.com/auth/userinfo.email"] } } } } ``` -------------------------------- ### Start qwen serve daemon Source: https://github.com/qwenlm/qwen-code/blob/main/docs/developers/examples/daemon-client-quickstart.md Start a qwen serve daemon in a terminal. Ensure you are in your project directory and the daemon listens on the specified port. ```bash cd your-project/ qwen serve --port 4170 # → qwen serve listening on http://127.0.0.1:4170 (mode=http-bridge, workspace=/path/to/your-project) ``` -------------------------------- ### Full Example Workspace Configuration Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/apps/electron/resources/docs/labels.md A comprehensive `config.json` example demonstrating auto-label rules for Linear issues, deadlines, contacts, and budgets. This illustrates how to define multiple labels with their respective regex patterns and value types. ```json { "version": 1, "labels": [ { "id": "linear-issue", "name": "Linear Issue", "color": "purple", "valueType": "string", "autoRules": [ { "pattern": "linear\.app/[\w-]+/issue/([A-Z]+-\d+)", "valueTemplate": "$1", "description": "Linear URLs" }, { "pattern": "\b([A-Z]{2,5}-\d+)\b", "valueTemplate": "$1", "description": "Bare issue keys" } ] }, { "id": "deadline", "name": "Deadline", "color": "orange", "valueType": "date", "autoRules": [ { "pattern": "(\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2})?)", "valueTemplate": "$1", "description": "ISO dates" } ] }, { "id": "contact", "name": "Contact", "color": "blue", "valueType": "string", "autoRules": [ { "pattern": "([\w.+-]+@[\w.-]+\.[a-zA-Z]{2,})", "valueTemplate": "$1", "description": "Email addresses" } ] }, { "id": "budget", "name": "Budget", "color": "green", "valueType": "number", "autoRules": [ { "pattern": "\$([\d,.]+[kKmMbB]?)", "valueTemplate": "$1", "description": "Dollar amounts" } ] } ] } ``` -------------------------------- ### Java (jdtls) LSP Configuration Source: https://github.com/qwenlm/qwen-code/blob/main/docs/users/features/lsp.md Configure the JDTLS language server for Java development. Requires a JDK and JDTLS to be installed and available in PATH. This example specifies configuration and workspace data paths. ```json { "java": { "command": "jdtls", "args": ["-configuration", ".jdtls-config", "-data", ".jdtls-workspace"] } } ``` -------------------------------- ### Calculate Request Setup Time Source: https://github.com/qwenlm/qwen-code/blob/main/docs/design/telemetry-llm-request-timing-design.md This snippet defines the calculation for `request_setup_ms`, which measures the wall-clock time from the entry of a request to the start of its successful attempt. It includes time spent on retries and backoff sleeps. ```typescript request_setup_ms = attemptStart_of_successful_attempt - requestEntryTime; ``` -------------------------------- ### guide.md API Reference Example Source: https://github.com/qwenlm/qwen-code/blob/main/packages/desktop/apps/electron/resources/docs/sources.md Example of a POST /search endpoint definition within a guide.md file. ```json { "query": "machine learning", "limit": 5 } ```