{
  "canonical_name": "QwenLM/qwen-code",
  "compilation_id": "pack_2afb382a7def420c81898b7ed277033c",
  "created_at": "2026-05-16T01:17:28.345079+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=skill, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=skill, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npm install -g @qwen-code/qwen-code@latest` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npm install -g @qwen-code/qwen-code@latest",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_fcdedcc455ac4013aa0fe2b3eddf2f67"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_62115ea84d5368bcff8e5c95b5abcb06",
    "canonical_name": "QwenLM/qwen-code",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/QwenLM/qwen-code",
    "slug": "qwen-code",
    "source_packet_id": "phit_ddd2ea3a5cbd48288cf13d83edf73cc3",
    "source_validation_id": "dval_d750a4261ee247f2afff5933a37f8cf2"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 claude的用户",
    "github_forks": null,
    "github_stars": null,
    "one_liner_en": "<div align=\"center\">",
    "one_liner_zh": "<div align=\"center\">",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "high",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:code, test, git"
    },
    "target_user": "使用 claude, claude_code, chatgpt 等宿主 AI 的用户",
    "title_en": "qwen-code",
    "title_zh": "qwen-code 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Natural-language Web Actions",
        "label_zh": "自然语言网页操作",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-natural-language-web-actions",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_ddd2ea3a5cbd48288cf13d83edf73cc3",
  "page_model": {
    "artifacts": {
      "artifact_slug": "qwen-code",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npm install -g @qwen-code/qwen-code@latest",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/QwenLM/qwen-code#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "断点恢复流程",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 claude的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "<div align=\"center\">"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "claude, claude_code, chatgpt",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "skill, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | host_targets=claude, claude_code, chatgpt"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "No sandbox install has been executed yet; downstream must verify before user use.",
            "category": "安全/权限坑",
            "evidence": [
              "risks.safety_notes | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | No sandbox install has been executed yet; downstream must verify before user use."
            ],
            "severity": "medium",
            "suggested_check": "转成明确权限清单和安全审查提示。",
            "title": "存在安全注意事项",
            "user_impact": "用户安装前需要知道权限边界和敏感操作。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 8 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": null,
        "forks": null,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": null
      },
      "source_url": "https://github.com/QwenLM/qwen-code",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "<div align=\"center\">",
      "title": "qwen-code 能力包",
      "trial_prompt": "# qwen-code - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for QwenLM/qwen-code.\n\nProject:\n- Name: qwen-code\n- Repository: https://github.com/QwenLM/qwen-code\n- Summary: <div align=\"center\">\n- Host target: claude, claude_code, chatgpt\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: <div align=\"center\">\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. project-overview: Project Overview. Produce one small intermediate artifact and wait for confirmation.\n2. architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. agent-runtime: Core Agent Runtime. Produce one small intermediate artifact and wait for confirmation.\n4. turn-processing: Turn Processing and LLM Communication. Produce one small intermediate artifact and wait for confirmation.\n5. tools-system: Tools System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/QwenLM/qwen-code#readme\n- .qwen/skills/bugfix/SKILL.md\n- .qwen/skills/codegraph/SKILL.md\n- .qwen/skills/docs-audit-and-refresh/SKILL.md\n- .qwen/skills/docs-update-from-diff/SKILL.md\n- .qwen/skills/e2e-testing/SKILL.md\n- .qwen/skills/feat-dev/SKILL.md\n- .qwen/skills/qwen-code-claw/SKILL.md\n- .qwen/skills/structured-debugging/SKILL.md\n- .qwen/skills/terminal-capture/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: /language output 切换后必须重启才能生效（https://github.com/QwenLM/qwen-code/issues/4142）；github/github_issue: node 26.0.0 - API Error: Connection error. (cause: fetch failed)（https://github.com/QwenLM/qwen-code/issues/4140）；github/github_issue: не работает сжатие контекста（https://github.com/QwenLM/qwen-code/issues/4141）；github/github_issue: 400 {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"i（https://github.com/QwenLM/qwen-code/issues/4139）；github/github_issue: Daemon mode (qwen serve): proposal & open decisions（https://github.com/QwenLM/qwen-code/issues/3803）；github/github_release: Release v0.15.11（https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11）；github/github_release: Release v0.15.11-preview.2（https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11-preview.2）；github/github_release: Release v0.15.10-preview.1（https://github.com/QwenLM/qwen-code/releases/tag/v0.15.10-preview.1）；github/github_release: Release v0.15.10-nightly.20260513.14512080e（https://github.com/QwenLM/qwen-code/releases/tag/v0.15.10-nightly.20260513.14512080e）；github/github_release: Release v0.15.11-preview.1（https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11-preview.1）；github/github_release: Release v0.15.11-preview.0（https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11-preview.0）；github/github_release: Release v0.15.10-nightly.20260511.0a05ea800（https://github.com/QwenLM/qwen-code/releases/tag/v0.15.10-nightly.20260511.0a05ea800）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "/language output 切换后必须重启才能生效",
              "url": "https://github.com/QwenLM/qwen-code/issues/4142"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "node 26.0.0 - API Error: Connection error. (cause: fetch failed)",
              "url": "https://github.com/QwenLM/qwen-code/issues/4140"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "не работает сжатие контекста",
              "url": "https://github.com/QwenLM/qwen-code/issues/4141"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "400 {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"i",
              "url": "https://github.com/QwenLM/qwen-code/issues/4139"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Daemon mode (qwen serve): proposal & open decisions",
              "url": "https://github.com/QwenLM/qwen-code/issues/3803"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.15.11",
              "url": "https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.15.11-preview.2",
              "url": "https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11-preview.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.15.10-preview.1",
              "url": "https://github.com/QwenLM/qwen-code/releases/tag/v0.15.10-preview.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.15.10-nightly.20260513.14512080e",
              "url": "https://github.com/QwenLM/qwen-code/releases/tag/v0.15.10-nightly.20260513.14512080e"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.15.11-preview.1",
              "url": "https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11-preview.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.15.11-preview.0",
              "url": "https://github.com/QwenLM/qwen-code/releases/tag/v0.15.11-preview.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.15.10-nightly.20260511.0a05ea800",
              "url": "https://github.com/QwenLM/qwen-code/releases/tag/v0.15.10-nightly.20260511.0a05ea800"
            }
          ],
          "status": "已收录 13 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "<div align=\"center\">",
      "effort": "安装已验证",
      "forks": null,
      "icon": "code",
      "name": "qwen-code 能力包",
      "risk": "可发布",
      "slug": "qwen-code",
      "stars": null,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "断点恢复流程",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "Skill Pack"
    },
    "manual": {
      "markdown": "# https://github.com/QwenLM/qwen-code 项目说明书\n\n生成时间：2026-05-16 00:58:51 UTC\n\n## 目录\n\n- [Project Overview](#project-overview)\n- [System Architecture](#architecture)\n- [Core Agent Runtime](#agent-runtime)\n- [Turn Processing and LLM Communication](#turn-processing)\n- [Tools System](#tools-system)\n- [Authentication and Model Providers](#authentication)\n- [Memory System](#memory-system)\n- [Session Management](#session-management)\n- [Skills System](#skills-system)\n- [Extensions System](#extensions)\n\n<a id='project-overview'></a>\n\n## Project Overview\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [Authentication and Model Providers](#authentication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/QwenLM/qwen-code/blob/main/README.md)\n- [packages/cli/package.json](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/package.json)\n- [packages/core/package.json](https://github.com/QwenLM/qwen-code/blob/main/packages/core/package.json)\n- [packages/webui/README.md](https://github.com/QwenLM/qwen-code/blob/main/packages/webui/README.md)\n- [packages/webui/package.json](https://github.com/QwenLM/qwen-code/blob/main/packages/webui/package.json)\n- [packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n- [packages/core/src/memory/extractionAgentPlanner.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/extractionAgentPlanner.ts)\n</details>\n\n# Project Overview\n\nQwen Code is an AI-powered coding assistant developed by the Qwen team. It provides an intelligent CLI (Command-Line Interface) tool that leverages large language models to assist developers with coding tasks, code review, refactoring, and automated programming workflows.\n\n## What is Qwen Code\n\nQwen Code is a multi-agent coding system that combines AI language model capabilities with traditional development tools. It enables developers to:\n\n- **Execute coding tasks** through natural language commands\n- **Manage complex development workflows** with multiple sub-agents\n- **Access external tools** via MCP (Model Context Protocol) servers\n- **Compare AI models** using an Arena feature for side-by-side evaluation\n\n资料来源：[README.md:1-50]()\n\n## Architecture Overview\n\nThe project follows a **monorepo structure** with three main packages:\n\n```mermaid\ngraph TD\n    subgraph \"Qwen Code Repository\"\n        CLI[\"packages/cli<br/>CLI Application\"]\n        CORE[\"packages/core<br/>Core Engine\"]\n        WEBUI[\"packages/webui<br/>Web UI Components\"]\n    end\n    \n    CLI --> CORE\n    CLI --> WEBUI\n```\n\n### Package Breakdown\n\n| Package | Purpose | Technology |\n|---------|---------|------------|\n| `packages/cli` | Command-line interface and terminal UI | TypeScript, React-like rendering (blessed) |\n| `packages/core` | Core AI logic, memory management, agent planning | TypeScript |\n| `packages/webui` | Reusable web components for React applications | React, Tailwind CSS |\n\n资料来源：[README.md:30-45]()\n资料来源：[packages/cli/package.json]()\n资料来源：[packages/core/package.json]()\n\n## Core Components\n\n### CLI Application (`packages/cli`)\n\nThe CLI package provides the terminal-based user interface for interacting with Qwen Code. It includes:\n\n- **Interactive terminal UI** built with `blessed` and `react-blessed`\n- **Arena functionality** for comparing multiple AI agents side-by-side\n- **Background task management** for long-running operations\n- **Sub-agent creation and management** system\n- **MCP server integration** for external tool access\n\n```mermaid\ngraph TD\n    UI[\"UI Layer<br/>React-Blessed Components\"]\n    CB[\"Context & State<br/>Management\"]\n    CORE[\"Core Engine<br/>packages/core\"]\n    IO[\"Non-Interactive<br/>CLI Mode\"]\n    \n    UI --> CB\n    CB --> CORE\n    IO --> CORE\n```\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx:1-50]()\n资料来源：[packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx:1-30]()\n\n### Core Engine (`packages/core`)\n\nThe core package contains the fundamental AI capabilities:\n\n- **Memory Management** - Handles persistent memory with topic-based organization\n- **Agent Planning** - Extraction and planning agents for task decomposition\n- **Managed Memory System** - Durable storage for project-specific information\n\n#### Memory System Architecture\n\n```mermaid\ngraph TD\n    Input[\"User Input / Conversation\"]\n    TopicScan[\"Topic Scanner\"]\n    MemoryBlock[\"Memory Block<br/>Builder\"]\n    PromptGen[\"Task Prompt<br/>Generator\"]\n    Output[\"AI Context\"]\n    \n    Input --> TopicScan\n    TopicScan --> MemoryBlock\n    MemoryBlock --> PromptGen\n    PromptGen --> Output\n    \n    subgraph \"Managed Memory\"\n        TopicDocs[\"Topic Documents<br/>scanAutoMemoryTopicDocuments\"]\n    end\n    TopicScan --> TopicDocs\n```\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-60]()\n资料来源：[packages/core/src/memory/prompt.ts:1-50]()\n\n### Web UI Components (`packages/webui`)\n\nThe webui package provides a React component library for building web-based interfaces:\n\n#### Available Component Categories\n\n| Category | Components |\n|----------|------------|\n| **Icons** | FileIcon, FolderIcon, CheckIcon, ErrorIcon, WarningIcon, SendIcon, etc. |\n| **Layout** | Container, Header, Footer, Sidebar, Main |\n| **Messages** | Message, MessageList, MessageInput, WaitingMessage, InterruptedMessage |\n| **UI Primitives** | Button, Input, Tooltip, Select, etc. |\n\n#### ToolCall Components\n\nSpecialized components for displaying tool interactions:\n\n```tsx\n// ToolCallCard with status indicators\n<ToolCallCard icon=\"💭\">\n  <ToolCallRow label=\"SaveMemory\">\n    <div>The user wants to refactor...</div>\n  </ToolCallRow>\n</ToolCallCard>\n```\n\n资料来源：[packages/webui/README.md:1-80]()\n资料来源：[packages/webui/src/components/toolcalls/shared/ToolCallCard.stories.tsx:1-50]()\n\n## Key Features\n\n### Arena Mode\n\nThe Arena feature enables side-by-side comparison of different AI agents:\n\n- Multiple agent selection with status indicators\n- Token and file count tracking\n- Diff visualization with additions/deletions\n- Duration and performance metrics\n\n```mermaid\ngraph LR\n    Agent1[\"Agent A<br/>qwen3.6-plus\"]\n    Agent2[\"Agent B<br///>glm-4.7\"]\n    Arena[\"Arena Dialog\"]\n    Results[\"Side-by-side<br/>Results\"]\n    \n    Agent1 --> Arena\n    Agent2 --> Arena\n    Arena --> Results\n```\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx:20-40]()\n资料来源：[packages/cli/src/ui/components/arena/ArenaStopDialog.tsx:1-30]()\n\n### Sub-agents System\n\nDevelopers can create custom sub-agents with:\n\n- Custom system prompts\n- Tool configurations\n- Model selection\n- Color coding for visual distinction\n- Project-level or user-level scope\n\n资料来源：[packages/cli/src/ui/components/subagents/create/CreationSummary.tsx:1-50]()\n资料来源：[packages/cli/src/ui/components/subagents/manage/AgentViewerStep.tsx:1-40]()\n\n### Extension System\n\nQwen Code supports extensions through:\n\n- MCP server integration\n- Version tracking\n- Status monitoring\n- Command registration\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-40]()\n\n## Configuration\n\n### Model Provider Configuration\n\nQwen Code supports multiple AI model providers configured via JSON:\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3.6-plus\",\n        \"name\": \"qwen3.6-plus (Coding Plan)\",\n        \"baseUrl\": \"https://coding.dashscope.aliyuncs.com/v1\",\n        \"envKey\": \"BAILIAN_CODING_PLAN_API_KEY\"\n      }\n    ]\n  }\n}\n```\n\n### Environment Variables\n\n| Variable | Purpose |\n|----------|---------|\n| `BAILIAN_CODING_PLAN_API_KEY` | API key for ModelStudio Coding Plan |\n| `QWEN_MODEL` | Default model selection |\n\n资料来源：[README.md:50-80]()\n\n## Project Structure\n\n```\nqwen-code/\n├── packages/\n│   ├── cli/\n│   │   ├── src/\n│   │   │   ├── ui/           # Terminal UI components\n│   │   │   │   ├── components/\n│   │   │   │   └── contexts/\n│   │   │   └── nonInteractiveCli.ts\n│   │   └── package.json\n│   ├── core/\n│   │   ├── src/\n│   │   │   └── memory/       # Memory management\n│   │   └── package.json\n│   └── webui/\n│       ├── src/\n│       │   ├── components/\n│       │   ├── context/\n│       │   └── hooks/\n│       └── package.json\n├── docs-site/               # Documentation website\n└── README.md\n```\n\n## Technology Stack\n\n| Layer | Technology |\n|-------|------------|\n| **Runtime** | Node.js |\n| **Language** | TypeScript |\n| **CLI UI** | blessed, react-blessed |\n| **Web UI** | React, Tailwind CSS, Vite |\n| **Docs** | Next.js, Nextra |\n| **Testing** | Vitest, React Testing Library |\n\n## Installation & Usage\n\n### Quick Start\n\n```bash\n# Install globally\nnpm install -g qwen-code\n\n# Configure (optional, can use defaults)\nqwen config set openai.apiKey your-key\n\n# Start Qwen Code\nqwen\n```\n\n### Development Setup\n\n```bash\n# Clone repository\ngit clone https://github.com/QwenLM/qwen-code.git\ncd qwen-code\n\n# Install dependencies\nnpm install\n\n# Start development\nnpm run dev\n```\n\n资料来源：[README.md:1-60]()\n\n## Statistics & Performance\n\nThe CLI provides detailed performance metrics including:\n\n- **Wall Time** - Total execution duration\n- **Agent Active Time** - Time spent actively processing\n- **API Time** - Time waiting for model responses\n- **Tool Time** - Time executing tools\n- **Cache Efficiency** - Token cache utilization\n\n资料来源：[packages/cli/src/ui/components/StatsDisplay.tsx:1-50]()\n\n## Summary\n\nQwen Code is a comprehensive AI coding assistant that combines:\n\n1. **CLI-first design** for terminal-based workflows\n2. **Modular architecture** with separate core, CLI, and UI packages\n3. **Multi-agent support** via Arena and sub-agent systems\n4. **Extensible tooling** through MCP integration\n5. **Web component library** for building custom interfaces\n\nThe project is well-suited for developers who prefer command-line workflows while wanting access to powerful AI-assisted coding capabilities.\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Core Agent Runtime](#agent-runtime), [Tools System](#tools-system), [Memory System](#memory-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n- [packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx)\n- [packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx)\n- [packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx)\n- [packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx)\n- [packages/cli/src/ui/components/arena/ArenaStopDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaStopDialog.tsx)\n- [packages/cli/src/ui/components/arena/ArenaCards.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaCards.tsx)\n- [packages/cli/src/ui/components/StatsDisplay.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/StatsDisplay.tsx)\n</details>\n\n# System Architecture\n\n## Overview\n\nQwen Code is a multi-package monorepo designed as an AI-powered coding assistant. The system architecture follows a modular design pattern with clear separation between core logic, CLI interface, UI components, and channel integrations.\n\n## Package Structure\n\nThe repository is organized as a monorepo under the `packages/` directory:\n\n| Package | Purpose |\n|---------|---------|\n| `cli` | Command-line interface with terminal-based UI |\n| `core` | Core functionality and business logic |\n| `webui` | Web-based user interface components |\n| `channels` | Abstraction layer for platform-specific capabilities |\n\n资料来源：[packages/webui/README.md](packages/webui/README.md)\n\n## Core Architectural Patterns\n\n### Agent Session Model\n\nThe system operates on an agent-based session model where agents perform coding tasks within isolated sessions.\n\n```mermaid\ngraph TD\n    A[User Query] --> B[Session Manager]\n    B --> C[Agent Executor]\n    C --> D[Tool Registry]\n    D --> E[File System]\n    D --> F[MCP Servers]\n    C --> G[Token Tracker]\n    G --> H[Stats Aggregator]\n```\n\nThe `BackgroundTasksDialog.tsx` component manages agent sessions with support for:\n- Session counting and tracking\n- Progress reporting\n- Topic metadata\n- Lock-release mechanisms for session management\n- Metadata write operations\n\n资料来源：[packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx](packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx)\n\n### Task and Monitor System\n\nTasks flow through the system with monitoring capabilities:\n\n```mermaid\ngraph LR\n    A[Task Created] --> B[Monitor Registry]\n    B --> C[Task Notification XML]\n    C --> D[Status: running|completed|failed|cancelled]\n```\n\nThe monitor system emits notifications via XML format:\n```xml\n<task-notification>\n  <task-id>mon_1</task-id>\n  <kind>monitor</kind>\n  <status>running</status>\n  <summary>Monitor emitted event #1.</summary>\n  <result>ready</result>\n</task-notification>\n```\n\n资料来源：[packages/cli/src/nonInteractiveCli.test.ts](packages/cli/src/nonInteractiveCli.test.ts)\n\n## CLI Architecture\n\n### UI Component Hierarchy\n\nThe CLI package (`packages/cli/src/ui/components/`) organizes UI components by functional domain:\n\n| Directory | Function |\n|-----------|----------|\n| `arena/` | Arena comparison sessions and dialogs |\n| `background-view/` | Background task management |\n| `extensions/` | Extension management steps |\n| `mcp/steps/` | MCP server and tool listing |\n| `views/` | General view components |\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n\n### Arena System\n\nThe Arena system enables comparative evaluation of multiple agents:\n\n```mermaid\ngraph TD\n    A[Arena Session] --> B[Agent Selection]\n    A --> C[Result Comparison]\n    A --> D[Diff Analysis]\n    B --> E{Stop Action}\n    E --> F[Cleanup]\n    E --> G[Preserve Artifacts]\n```\n\n**Arena Components:**\n\n1. **ArenaSelectDialog** - Agent selection interface with status indicators\n2. **ArenaStopDialog** - Session termination with cleanup/preserve options\n3. **ArenaCards** - Visual comparison of agent outputs\n\nThe `ArenaSelectDialog.tsx` displays agent status with the following metadata:\n- Status (success/error/running)\n- Duration\n- Token count\n- File count\n- Diff statistics (additions/deletions)\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n\n**Stop Actions:**\n\n| Action | Behavior |\n|--------|----------|\n| `cleanup` | Remove all worktrees and session files |\n| `preserve` | Keep worktrees and session files for later inspection |\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaStopDialog.tsx](packages/cli/src/ui/components/arena/ArenaStopDialog.tsx)\n\n### Stats and Performance Tracking\n\nThe `StatsDisplay.tsx` component aggregates performance metrics:\n\n| Metric Category | Tracked Data |\n|-----------------|--------------|\n| **Performance** | Wall time, agent active time, API time, tool time |\n| **Tokens** | Total cached tokens, cache efficiency |\n| **Models** | Per-model usage statistics |\n\nThe system calculates percentages for API and tool time relative to total execution time.\n\n资料来源：[packages/cli/src/ui/components/StatsDisplay.tsx](packages/cli/src/ui/components/StatsDisplay.tsx)\n\n## MCP (Model Context Protocol) Integration\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[CLI] --> B[MCP Registry]\n    B --> C[Server List]\n    B --> D[Tool List]\n    C --> E[ServerListStep]\n    D --> F[ToolListStep]\n    E --> G[Status: connected/disconnected]\n    F --> H[Validation]\n```\n\n### Server Management\n\nThe `ServerListStep.tsx` component displays MCP server status:\n\n```typescript\ninterface MCPServer {\n  status: 'connected' | 'disconnected';\n  isDisabled?: boolean;\n}\n```\n\nDisconnected servers display a debug hint:\n> \"Run qwen --debug to see error logs\"\n\n资料来源：[packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx](packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx)\n\n### Tool Listing\n\nThe `ToolListStep.tsx` provides:\n- Scrollable tool list with fixed-width name column\n- Validation status indicators\n- Tool annotations display\n- Pagination for large tool sets (VISIBLE_TOOLS_COUNT)\n\nTool validation feedback:\n```typescript\ninterface Tool {\n  name: string;\n  isValid: boolean;\n  invalidReason?: string;\n}\n```\n\n资料来源：[packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx](packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx)\n\n## Extension System\n\n### Extension Metadata\n\nThe `ExtensionDetailStep.tsx` displays extension information:\n\n| Field | Description |\n|-------|-------------|\n| `name` | Extension name |\n| `version` | Semantic version |\n| `status` | Active/inactive state |\n| `path` | Installation path |\n| `source` | Install metadata source |\n| `mcpServers` | Associated MCP server list |\n| `commands` | Available CLI commands |\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx](packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx)\n\n## Platform Abstraction\n\nThe webui package provides a `PlatformProvider` context for platform-specific capabilities:\n\n```tsx\nimport { PlatformProvider, usePlatform } from '@qwen-code/webui/context';\n```\n\nThis abstraction allows the same codebase to run in different environments while exposing platform-specific APIs through a unified interface.\n\n资料来源：[packages/webui/README.md](packages/webui/README.md)\n\n## WebUI Components\n\n### Layout Components\n- `Container` - Main layout wrapper\n- `Header` - Application header\n- `Footer` - Application footer\n- `Sidebar` - Side navigation\n- `Main` - Main content area\n\n### Message Components\n- `Message` - Chat message display\n- `MessageList` - List of messages\n- `MessageInput` - Message input field\n- `WaitingMessage` - Loading/waiting state\n- `InterruptedMessage` - Interrupted state display\n\n### UI Primitives\n- **Buttons**: `size`, `error`, `errorMessage`, `label`, `helperText`, `leftElement`, `rightElement`\n- **Tooltip**: Content wrapper for hover hints\n- **Icons**: File, Folder, Check, Error, Warning, Loading, Navigation, Edit, and Special icons\n\n资料来源：[packages/webui/README.md](packages/webui/README.md)\n\n## Key Command Processing\n\nThe `atCommandProcessor` handles special commands prefixed with `@`:\n\n```mermaid\ngraph TD\n    A[User Query] --> B{Contains @?}\n    B -->|No| C[Pass Through]\n    B -->|Yes| D[At Command Parser]\n    D --> E[Command Registry]\n    E --> F[Processed Query]\n```\n\nConfiguration options:\n- `getTruncateToolOutputThreshold` (default: 2500)\n- `getTruncateToolOutputLines` (default: 500)\n- `getUsageStatisticsEnabled`\n- `getFileExclusions` with ignore patterns\n\n资料来源：[packages/cli/src/ui/hooks/atCommandProcessor.test.ts](packages/cli/src/ui/hooks/atCommandProcessor.test.ts)\n\n## Keyboard Navigation\n\nThe `keyMatchers.ts` defines command-to-key bindings:\n\n| Command | Key Binding |\n|---------|-------------|\n| `KILL_LINE_RIGHT` | `Ctrl+k` |\n| `KILL_LINE_LEFT` | `Ctrl+u` |\n| `CLEAR_INPUT` | `Ctrl+c` |\n| `DELETE_WORD_BACKWARD` | `Ctrl+Backspace` or `Meta+Backspace` |\n| `CLEAR_SCREEN` | `Ctrl+l` |\n| `HISTORY_UP/DOWN` | `Ctrl+p` / `Ctrl+n` |\n| `NAVIGATION_UP/DOWN` | Arrow keys |\n| `COMPLETION_UP/DOWN` | Arrow keys only |\n| `ACCEPT_SUGGESTION` | `Tab` or `Enter` |\n| `ESCAPE` | `Escape` |\n\nNote: Completion navigation uses only arrow keys to preserve `Ctrl+P/N` for history navigation.\n\n资料来源：[packages/cli/src/ui/keyMatchers.test.ts](packages/cli/src/ui/keyMatchers.test.ts)\n\n## Error Handling Architecture\n\n### Status Types\n\n| Status | Color | Usage |\n|--------|-------|-------|\n| `success` | Green | Completed tasks |\n| `error` | Red | Failed operations |\n| `warning` | Yellow | Lock-release and metadata write warnings |\n| `running` | Accent | Active sessions |\n\n### Lock-Release Warnings\n\nWhen lock-release errors occur, the system displays:\n> \"Subsequent dreams may be skipped as locked until the next session's staleness sweep cleans the file.\"\n\n### Metadata Write Warnings\n\nFor metadata write failures:\n> \"The scheduler gate did not see this dream's timestamp; the next dream cycle may re-fire sooner than usual.\"\n\n资料来源：[packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx](packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx)\n\n## Token Efficiency Tracking\n\nThe `ArenaCards.tsx` component tracks token efficiency per agent:\n\n```typescript\ninterface AgentMetrics {\n  label: string;\n  totalTokens: number;\n  durationMs: number;\n  toolCalls: number;\n  diffStats: {\n    additions: number;\n    deletions: number;\n  };\n}\n```\n\nMetrics display with tree-style formatting for easy comparison.\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaCards.tsx](packages/cli/src/ui/components/arena/ArenaCards.tsx)\n\n---\n\n<a id='agent-runtime'></a>\n\n## Core Agent Runtime\n\n### 相关页面\n\n相关主题：[Turn Processing and LLM Communication](#turn-processing), [Tools System](#tools-system), [Session Management](#session-management)\n\n# Core Agent Runtime\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/subagents/subagent-manager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/subagents/subagent-manager.ts)\n- [packages/core/src/core/coreToolScheduler.test.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/coreToolScheduler.test.ts)\n- [packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n- [packages/cli/src/ui/components/StatsDisplay.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/StatsDisplay.tsx)\n- [packages/cli/src/ui/components/messages/ToolGroupMessage.test.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/messages/ToolGroupMessage.test.tsx)\n</details>\n\n## Overview\n\nThe Core Agent Runtime system in qwen-code provides the foundational infrastructure for executing AI agent tasks, managing subagents, handling tool scheduling, and coordinating background operations. This runtime architecture enables the CLI to execute complex multi-step coding tasks with support for tool calls, model routing, and persistent state management.\n\n## Architecture Components\n\n### Subagent Manager\n\nThe `SubagentManager` is the central coordinator for agent-level operations, handling registration, discovery, and lifecycle management of subagents across different storage levels.\n\n```mermaid\ngraph TD\n    A[SubagentManager] --> B[BuiltinAgentRegistry]\n    A --> C[Project Level Agents]\n    A --> D[User Level Agents]\n    A --> E[Extension Agents]\n    C --> F[~/.qwen/agents/]\n    D --> G[~/.qwen/agents/]\n```\n\n**Key Responsibilities:**\n\n| Function | Description |\n|----------|-------------|\n| `getSubagentConfig()` | Retrieves subagent configuration by name and level |\n| `listSubagentsAtLevel()` | Lists all subagents at a specific storage level |\n| `getSubagentPath()` | Resolves the file path for a subagent configuration |\n| `loadAllSubagents()` | Loads all available subagents across all levels |\n\n**Storage Levels:**\n\nThe system supports four distinct subagent levels:\n\n| Level | Path | Description |\n|-------|------|-------------|\n| `builtin` | Built-in registry | Agents bundled with the application |\n| `project` | `<project>/.qwen/agents/` | Project-scoped agents |\n| `session` | In-memory only | Session-specific agents |\n| `extension` | Extension-provided | Agents from loaded extensions |\n\n资料来源：[packages/core/src/subagents/subagent-manager.ts:1-100]()\n\n### Agent Resolution Logic\n\nThe subagent path resolution follows a hierarchical pattern:\n\n```typescript\ngetSubagentPath(name: string, level: SubagentLevel): string {\n  if (level === 'builtin') return `<builtin:${name}>`;\n  if (level === 'session') return `<session:${name}>`;\n  \n  const baseDir = level === 'project'\n    ? path.join(this.config.getProjectRoot(), QWEN_DIR, AGENT_CONFIG_DIR)\n    : path.join(Storage.getGlobalQwenDir(), AGENT_CONFIG_DIR);\n    \n  return path.join(baseDir, `${name}.md`);\n}\n```\n\n资料来源：[packages/core/src/subagents/subagent-manager.ts:40-52]()\n\n### Project vs Home Directory Handling\n\nA critical safety check prevents conflicts when the project root equals the home directory:\n\n```typescript\nconst homeDir = os.homedir();\nconst isHomeDirectory = path.resolve(projectRoot) === path.resolve(homeDir);\n\nif (level === 'project' && isHomeDirectory) {\n  return [];\n}\n```\n\n资料来源：[packages/core/src/subagents/subagent-manager.ts:77-82]()\n\n## Agent Result Display\n\nAgent execution results are represented through the `AgentResultDisplay` interface, supporting various execution states and task types:\n\n### Result Types\n\n| Type | Description |\n|------|-------------|\n| `task_execution` | Subagent task execution result |\n| `tool_execution` | Individual tool call result |\n\n### Execution Status States\n\n| Status | Description |\n|--------|-------------|\n| `running` | Agent is actively executing |\n| `completed` | Agent completed successfully |\n| `failed` | Agent encountered an error |\n| `cancelled` | Agent was cancelled |\n\n### Agent Result Structure\n\n```typescript\ninterface AgentResultDisplay {\n  type: 'task_execution';\n  subagentName: string;\n  taskDescription: string;\n  taskPrompt: string;\n  status: 'running' | 'completed' | 'failed' | 'cancelled';\n  toolCalls: ToolCall[];\n}\n```\n\n资料来源：[packages/cli/src/ui/components/messages/ToolGroupMessage.test.tsx:10-35]()\n\n## Tool Call Integration\n\n### Tool Call Status\n\nTool calls within agent execution follow a status model:\n\n| Status | Description |\n|--------|-------------|\n| `Executing` | Tool is currently running |\n| `success` | Tool completed successfully |\n| `error` | Tool failed with an error |\n\n### Tool Call Display\n\n```typescript\nconst createToolCall = ({\n  callId: string,\n  name: string,\n  status: ToolCallStatus,\n  resultDisplay?: AgentResultDisplay,\n}) => ({\n  callId,\n  name,\n  status,\n  description: '...',\n  resultDisplay,\n});\n```\n\n## Performance Metrics\n\nThe runtime tracks comprehensive performance metrics for agent execution:\n\n### Computed Statistics\n\n| Metric | Description |\n|--------|-------------|\n| `agentActiveTime` | Total time agent was actively processing |\n| `totalApiTime` | Time spent in API calls |\n| `totalToolTime` | Time spent executing tools |\n| `apiTimePercent` | Percentage of time in API calls |\n| `toolTimePercent` | Percentage of time in tool execution |\n| `totalCachedTokens` | Token usage from cache |\n| `cacheEfficiency` | Cache hit ratio |\n\n### Stats Display Component\n\nThe `StatsDisplay` component renders performance metrics with theme-aware coloring:\n\n- **Wall Time**: Total elapsed time\n- **Agent Active**: Time agent was processing\n- **API Time**: Model interaction time with percentage\n- **Tool Time**: Tool execution time with percentage\n- **Token Usage**: Lines added/removed, token counts\n\n资料来源：[packages/cli/src/ui/components/StatsDisplay.tsx:1-80]()\n\n## Arena Selection System\n\nThe arena system enables comparison of multiple agent implementations:\n\n### Agent Selection Dialog\n\nThe `ArenaSelectDialog` provides an interactive selection interface with keyboard navigation:\n\n| Key | Action |\n|-----|--------|\n| `Escape` | Close arena dialog |\n| `P` | Toggle preview |\n| `D` | Toggle detailed diff view |\n\n### Agent Display Metrics\n\nEach agent candidate displays:\n\n- Status (with color coding)\n- Duration\n- Token count\n- File count (if applicable)\n- Diff additions/deletions\n\n```typescript\nconst getAgentDisplay = (agent) => ({\n  key: agent.agentId,\n  value: agent.agentId,\n  title: agent.name,\n  description: `${statusInfo.text} · ${duration} · ${tokens} tokens`,\n  disabled: !isSuccessStatus(agent.status),\n});\n```\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx:1-60]()\n\n## Configuration Integration\n\nThe agent runtime integrates with the configuration system through the `Config` interface:\n\n### Required Configuration Methods\n\n| Method | Purpose |\n|--------|---------|\n| `getSessionId()` | Session identifier for state management |\n| `getUsageStatisticsEnabled()` | Enable/disable stats collection |\n| `getDebugMode()` | Enable verbose debugging |\n| `getToolRegistry()` | Access tool registry |\n| `getApprovalMode()` | Tool execution approval level |\n| `getTruncateToolOutputThreshold()` | Output truncation limit |\n| `getTruncateToolOutputLines()` | Line count truncation limit |\n\n### Default Test Configuration\n\n```typescript\nconst mockConfig = {\n  getSessionId: () => 'test-session-id',\n  getUsageStatisticsEnabled: () => true,\n  getDebugMode: () => false,\n  getApprovalMode: () => ApprovalMode.YOLO,\n  getToolRegistry: () => mockToolRegistry,\n  getTruncateToolOutputThreshold: () => 100,\n  getTruncateToolOutputLines: () => 10,\n};\n```\n\n资料来源：[packages/core/src/core/coreToolScheduler.test.ts:1-80]()\n\n## Extension Agent Integration\n\nAgents can also be provided by extensions through the extension registry:\n\n```typescript\nif (level === 'extension') {\n  const extensions = this.config.getActiveExtensions();\n  return extensions.flatMap((extension) => extension.agents || []);\n}\n```\n\nExtensions contribute agents via their `agents` property, which are merged with built-in and file-based agents.\n\n## Summary\n\nThe Core Agent Runtime provides a layered architecture for agent execution:\n\n1. **SubagentManager** - Coordinates agent discovery and lifecycle across storage levels\n2. **ToolRegistry** - Manages available tools and their execution\n3. **Config System** - Provides runtime configuration and state\n4. **Extension System** - Allows external contributions of agents\n5. **UI Components** - Renders agent status, results, and performance metrics\n\nThis architecture enables flexible agent composition while maintaining clear separation of concerns between agent definition, execution, and presentation layers.\n\n---\n\n<a id='turn-processing'></a>\n\n## Turn Processing and LLM Communication\n\n### 相关页面\n\n相关主题：[Core Agent Runtime](#agent-runtime), [Authentication and Model Providers](#authentication), [Tools System](#tools-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/core/turn.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/turn.ts)\n- [packages/core/src/core/client.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/client.ts)\n- [packages/core/src/core/contentGenerator.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/contentGenerator.ts)\n- [packages/core/src/core/baseLlmClient.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/baseLlmClient.ts)\n- [packages/core/src/core/coreToolScheduler.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/coreToolScheduler.ts)\n- [packages/core/src/telemetry/metrics.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/telemetry/metrics.ts)\n</details>\n\n# Turn Processing and LLM Communication\n\n## Overview\n\nTurn Processing and LLM Communication is the core message flow system that orchestrates the interaction between the Qwen Code CLI and Large Language Models. This system manages the complete lifecycle of a user interaction \"turn\" — from query processing through tool execution to final response delivery.\n\n## Architecture Components\n\nThe turn processing system consists of several interconnected components:\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| Turn Manager | `turn.ts` | Orchestrates turn lifecycle and state management |\n| Client | `client.ts` | Handles session management and configuration |\n| Content Generator | `contentGenerator.ts` | Generates prompts and processes responses |\n| Base LLM Client | `baseLlmClient.ts` | Abstract base for LLM API communication |\n| Tool Scheduler | `coreToolScheduler.ts` | Manages tool execution during turns |\n\n## Turn State Machine\n\nA turn progresses through distinct states during its lifecycle. The system tracks both the overall turn state and individual tool call states.\n\n```mermaid\ngraph TD\n    A[Turn Started] --> B[User Query Received]\n    B --> C[Content Generation]\n    C --> D{Awaiting Tool Calls?}\n    D -->|Yes| E[Tool Call Scheduled]\n    E --> F[Tool Execution]\n    F --> G[Tool Success?]\n    G -->|Yes| C\n    G -->|No| H[Tool Failure]\n    H --> I[Error Response]\n    D -->|No| J[Final Response]\n    I --> J\n    J --> K[Turn Complete]\n```\n\n## Message Flow\n\n### Input Processing\n\nWhen a user submits a query, the system processes it through several stages:\n\n1. **Query Reception** — The CLI receives the user's input\n2. **At-Command Processing** — Any `@` commands referencing subagents are parsed\n3. **Context Enrichment** — Project context and memory are retrieved\n4. **Prompt Construction** — System prompts and context are assembled\n\n### LLM Communication\n\nThe communication with the LLM API follows a structured pattern:\n\n```mermaid\ngraph LR\n    A[User Query] --> B[Content Generator]\n    B --> C[Base LLM Client]\n    C --> D[API Request]\n    D --> E[Streaming Response]\n    E --> F[Response Parser]\n    F --> G[Tool Call Detection]\n    G --> H[Tool Execution]\n    H --> B\n    F --> I[Final Response]\n```\n\n### Tool Call Lifecycle\n\nTool calls are processed through the Core Tool Scheduler. Each tool call transitions through these states:\n\n| State | Description |\n|-------|-------------|\n| `pending` | Tool call queued for execution |\n| `executing` | Tool currently running |\n| `success` | Tool completed successfully |\n| `failure` | Tool encountered an error |\n| `interrupted` | Tool execution was cancelled |\n\nThe scheduler handles both native tools and MCP (Model Context Protocol) tools through a unified interface.\n\n## Response Handling\n\n### Streaming Architecture\n\nThe system supports real-time streaming responses with several message types:\n\n- **Stream chunks** — Partial response text\n- **Thinking segments** — Model reasoning (when enabled)\n- **Tool call updates** — Progress on executing tools\n- **Waiting indicators** — User feedback during processing\n\n### Result Display\n\nTool execution results are formatted into display objects that include:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `type` | string | Result category (task_execution, error, etc.) |\n| `status` | string | Execution status |\n| `toolCalls` | array | Individual tool call results |\n| `subagentName` | string | Name of subagent (if applicable) |\n\n## Configuration\n\n### Model Configuration\n\nThe system supports multiple model providers with configurable parameters:\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3.6-plus\",\n        \"name\": \"qwen3.6-plus (Coding Plan)\",\n        \"baseUrl\": \"https://coding.dashscope.aliyuncs.com/v1\",\n        \"envKey\": \"BAILIAN_CODING_PODING_PLAN_API_KEY\"\n      }\n    ]\n  }\n}\n```\n\n### Generation Config\n\nResponse generation can be customized per request:\n\n| Parameter | Description |\n|-----------|-------------|\n| `temperature` | Sampling temperature |\n| `maxTokens` | Maximum response length |\n| `thinkingConfig.includeThoughts` | Enable model thinking |\n| `abortSignal` | Cancellation token |\n\n## Telemetry and Metrics\n\nThe turn processing system records comprehensive metrics:\n\n| Metric | Description | Tags |\n|--------|-------------|------|\n| `TOOL_CALL_COUNT` | Tool invocations | function_name, success, decision |\n| `API_REQUEST_COUNT` | LLM API calls | model, status_code |\n| `TOKEN_USAGE` | Token consumption | model, type (input/output/thought) |\n\nThese metrics enable monitoring of system performance and usage patterns.\n\n## Error Handling\n\n### Tool Execution Failures\n\nWhen a tool fails, the scheduler:\n\n1. Records the error with type classification\n2. Fires post-tool-use failure hooks\n3. Optionally appends additional context from hooks\n4. Returns formatted error response to the LLM\n\n### Graceful Degradation\n\nThe system handles various error scenarios:\n\n- **Config errors** — Individual config methods may throw; caught internally\n- **Network failures** — Retry logic with timeout handling\n- **Tool unavailability** — Tools excluded from execution but handled gracefully\n\n## Subagent Integration\n\nSubagents can be invoked during turn processing. The system supports:\n\n- **Focused execution** — Running subagent keeps focus for Ctrl+E expansion\n- **Task tracking** — Subagent tasks displayed with status indicators\n- **Nested execution** — Subagents can call other tools recursively\n\n## Data Flow Diagram\n\n```mermaid\ngraph TD\n    subgraph Input\n        A[User Input] --> B[At-Command Processor]\n        B --> C[Query Parser]\n    end\n    \n    subgraph Context\n        C --> D[Memory System]\n        C --> E[Project Context]\n        C --> F[Subagent Registry]\n    end\n    \n    subgraph LLM\n        D --> G[Content Generator]\n        E --> G\n        F --> G\n        G --> H[Base LLM Client]\n        H --> I[Model API]\n    end\n    \n    subgraph Execution\n        I --> J[Response Parser]\n        J --> K{Tool Calls?}\n        K -->|Yes| L[Core Tool Scheduler]\n        L --> M[Tool Registry]\n        M --> L\n        L --> N[Result Formatter]\n        N --> G\n        K -->|No| O[Final Response]\n    end\n```\n\n## Key Source Files\n\nThe following files implement the turn processing and LLM communication system:\n\n| File | Purpose |\n|------|---------|\n| `packages/core/src/core/turn.ts` | Core turn state management |\n| `packages/core/src/core/client.ts` | Client session handling |\n| `packages/core/src/core/contentGenerator.ts` | Prompt and response handling |\n| `packages/core/src/core/baseLlmClient.ts` | Abstract LLM communication |\n| `packages/core/src/core/coreToolScheduler.ts` | Tool execution orchestration |\n| `packages/core/src/telemetry/metrics.ts` | Usage telemetry |\n\n## Summary\n\nThe Turn Processing and LLM Communication system provides the foundation for Qwen Code's interaction with language models. It coordinates query processing, manages tool execution through the scheduler, handles streaming responses, and maintains comprehensive telemetry. The modular architecture allows flexible configuration of model providers while maintaining consistent behavior across different LLM backends.\n\n---\n\n<a id='tools-system'></a>\n\n## Tools System\n\n### 相关页面\n\n相关主题：[Core Agent Runtime](#agent-runtime), [Turn Processing and LLM Communication](#turn-processing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/tools/tools.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/tools.ts)\n- [packages/core/src/tools/tool-registry.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/tool-registry.ts)\n- [packages/core/src/tools/shell.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/shell.ts)\n- [packages/core/src/tools/edit.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/edit.ts)\n- [packages/core/src/tools/read-file.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/read-file.ts)\n- [packages/core/src/tools/write-file.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/write-file.ts)\n- [packages/core/src/tools/mcp-client.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/mcp-client.ts)\n- [packages/core/src/tools/lsp.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/lsp.ts)\n</details>\n\n# Tools System\n\n## Overview\n\nThe Tools System is a core architectural component of Qwen Code that enables the AI assistant to interact with the user's development environment. It provides a unified interface for executing code-related operations such as reading files, writing files, executing shell commands, editing code, and integrating with external services via the Model Context Protocol (MCP).\n\nTools extend the LLM's capabilities beyond text generation by allowing it to perform actions in the real world. When the model decides to use a tool, it generates a tool call that the system executes, returning results back to the model for further processing.\n\n## Architecture\n\nThe Tools System follows a plugin-based architecture with three main layers:\n\n```mermaid\ngraph TD\n    subgraph \"Presentation Layer\"\n        UI[UI Components]\n        TL[ToolListStep]\n        MS[McpStatus]\n    end\n    \n    subgraph \"Core Layer\"\n        TR[ToolRegistry]\n        TS[ToolScheduler]\n        TE[ToolExecutor]\n    end\n    \n    subgraph \"Integration Layer\"\n        MCP[MCP Client]\n        LSP[LSP Client]\n        SH[Shell Tools]\n        FS[File System Tools]\n    end\n    \n    UI --> TR\n    TL --> TR\n    MS --> TR\n    TR --> TS\n    TR --> TE\n    TE --> MCP\n    TE --> LSP\n    TE --> SH\n    TE --> FS\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| ToolRegistry | `tool-registry.ts` | Central registry for all available tools |\n| ToolScheduler | `coreToolScheduler.test.ts` | Schedules and manages tool execution |\n| BaseTool | `tools.ts` | Abstract base class for all tools |\n| MCPToolClient | `mcp-client.ts` | Handles MCP server communication |\n| LSPClient | `lsp.ts` | Language Server Protocol integration |\n\n## Built-in Tools\n\nQwen Code includes several built-in tools that provide fundamental file system and execution capabilities.\n\n### File Operations\n\n#### ReadFileTool\n\nReads the contents of files from the file system.\n\n```typescript\n// From packages/core/src/tools/read-file.ts\nclass ReadFileTool extends BaseTool {\n  readonly name = 'Bash';\n  readonly description = '...';\n}\n```\n\n#### WriteFileTool\n\nCreates or overwrites files with specified content.\n\n```typescript\n// From packages/core/src/tools/write-file.ts\nclass WriteFileTool extends BaseTool {\n  readonly name = 'Write';\n  readonly description = '...';\n}\n```\n\n#### EditTool\n\nModifies existing files by applying targeted changes, supporting search-and-replace operations.\n\n```typescript\n// From packages/core/src/tools/edit.ts\nclass EditTool extends BaseTool {\n  readonly name = 'Edit';\n  readonly description = '...';\n}\n```\n\n### Shell Execution\n\n#### ShellTool\n\nExecutes bash commands in the user's terminal environment.\n\n```typescript\n// From packages/core/src/tools/shell.ts\nclass ShellTool extends BaseTool {\n  readonly name = 'Bash';\n  readonly description = 'Executes bash commands in the user\\'s terminal';\n}\n```\n\nThe shell execution configuration includes terminal dimensions for proper output formatting:\n\n```typescript\ngetShellExecutionConfig: () => ({\n  terminalWidth: 90,\n  terminalHeight: 30,\n}),\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:45-47]()*\n\n## Tool Registry\n\nThe ToolRegistry serves as the central knowledge base for all available tools in the system.\n\n### Registry Interface\n\n```typescript\ninterface ToolRegistry {\n  getToolByName(name: string): Tool | undefined;\n  getToolByDisplayName(displayName: string): Tool | undefined;\n  getTools(): Tool[];\n  getAllTools(): Tool[];\n  getAllToolNames(): string[];\n  getToolsByServer(serverName: string): Tool[];\n  discoverTools(): Promise<void>;\n  registerTool(tool: Tool): void;\n}\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:18-27]()*\n\n### Registry Operations\n\nTools can be retrieved by various identifiers:\n\n```typescript\ngetToolByName: (name: string) =>\n  name === StrictStringTool.Name\n    ? toolA\n    : name === StrictToolAlt.Name\n      ? toolB\n      : undefined,\ngetToolByDisplayName: () => undefined,\ngetAllToolNames: () => [StrictStringTool.Name, StrictToolAlt.Name],\ngetToolsByServer: () => [],\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:28-35]()*\n\n## MCP Integration\n\nThe Model Context Protocol (MCP) allows Qwen Code to connect with external tools and services.\n\n### MCP Client Architecture\n\n```mermaid\ngraph LR\n    LLM[LLM] -->|Tool Call| QC[Qwen Code]\n    QC -->|MCP Request| MS[MCP Server]\n    MS -->|Response| QC\n    QC -->|Result| LLM\n    \n    subgraph \"MCP Servers\"\n        FS[File System]\n        DB[Database]\n        API[External APIs]\n    end\n    \n    MS --> FS\n    MS --> DB\n    MS --> API\n```\n\n### MCP Tool Display\n\nMCP tools are displayed in the UI with their server information and validation status:\n\n```tsx\n// From packages/cli/src/ui/components/views/McpStatus.tsx\n{tools.map((tool) => {\n  const schemaContent =\n    showSchema &&\n    tool.schema &&\n    (tool.schema.parametersJsonSchema || tool.schema.parameters)\n      ? JSON.stringify(tool.schema.parametersJsonSchema ?? tool.schema.parameters, null, 2)\n      : null;\n  \n  return (\n    <Box key={tool.name} flexDirection=\"column\">\n      <Text>- <Text color={theme.text.primary}>{tool.name}</Text></Text>\n      {showDescriptions && tool.description && (\n        <Box marginLeft={2}>\n          <Text color={theme.text.secondary}>{tool.description.trim()}</Text>\n        </Box>\n      )}\n    </Box>\n  );\n})}\n```\n*资料来源：[packages/cli/src/ui/components/views/McpStatus.tsx:1-20]()*\n\n### MCP Servers Configuration\n\nMCP servers can expose multiple components:\n\n| Component | Description |\n|-----------|-------------|\n| Tools | Executable operations exposed by the server |\n| Resources | Data sources that can be read |\n| Prompts | Predefined prompt templates |\n| MCP Servers | Named server connections |\n\n```tsx\n// Displaying MCP servers in UI\n{ext.mcpServers && Object.keys(ext.mcpServers).length > 0 && (\n  <Box>\n    <Box width={LABEL_WIDTH} flexShrink={0}>\n      <Text color={theme.text.primary}>{t('MCP Servers:')}</Text>\n    </Box>\n    <Text>{Object.keys(ext.mcpServers).join(', ')}</Text>\n  </Box>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-15]()*\n\n## LSP Integration\n\nThe Language Server Protocol (LSP) integration provides advanced code intelligence features including:\n\n- Symbol navigation\n- Hover information\n- Go-to-definition\n- Code completion\n- Diagnostics\n\n```typescript\n// From packages/core/src/tools/lsp.ts\nclass LSPTool extends BaseTool {\n  readonly name = 'LSP';\n  readonly description = 'Language Server Protocol integration';\n}\n```\n\n## Tool Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant LLM as LLM Model\n    participant TS as Tool Scheduler\n    participant TR as Tool Registry\n    participant EX as Tool Executor\n    participant TOOL as Specific Tool\n    \n    LLM->>TS: Request tool execution\n    TS->>TR: Lookup tool by name\n    TR-->>TS: Return tool instance\n    TS->>EX: Execute tool with parameters\n    EX->>TOOL: Call tool.run()\n    TOOL-->>EX: Return result\n    EX-->>TS: Return execution result\n    TS-->>LLM: Return result to model\n```\n\n### Execution Configuration\n\nThe tool execution system supports various configuration options:\n\n```typescript\nconst mockConfig = {\n  getTruncateToolOutputThreshold: () => 100,\n  getTruncateToolOutputLines: () => 10,\n  getToolRegistry: () => mockToolRegistry,\n  getUseModelRouter: () => false,\n  getGeminiClient: () => null,\n  isInteractive: () => true,\n};\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:40-48]()*\n\n## UI Components\n\n### Tool List Display\n\nThe ToolListStep component provides an interactive list of available tools:\n\n```tsx\n// From packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx\n<Box width={toolNameWidth}>\n  <Text\n    color={isSelected ? theme.text.accent : theme.text.primary}\n    wrap=\"truncate\"\n  >\n    {tool.name}\n  </Text>\n</Box>\n{!tool.isValid && (\n  <Text color={theme.status.warning}>\n    {t('invalid: {{reason}}', {\n      reason: tool.invalidReason || t('unknown'),\n    })}\n  </Text>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx:1-15]()*\n\n### Context Usage Display\n\nTools contribute to the overall context window usage:\n\n```tsx\n// From packages/cli/src/ui/components/views/ContextUsage.tsx\n{/* Built-in tools detail */}\n{sortedBuiltinTools.length > 0 && (\n  <Box flexDirection=\"column\" marginTop={1}>\n    <Text bold color={theme.text.primary}>{t('Built-in tools')}</Text>\n    {sortedBuiltinTools.map((tool) => (\n      <DetailRow key={tool.name} name={tool.name} tokens={tool.tokens} />\n    ))}\n  </Box>\n)}\n\n{/* MCP Tools detail */}\n{sortedMcpTools.length > 0 && (\n  <Box flexDirection=\"column\" marginTop={1}>\n    <Text bold color={theme.text.primary}>{t('MCP tools')}</Text>\n    {sortedMcpTools.map((tool) => (\n      <DetailRow key={tool.name} name={tool.name} tokens={tool.tokens} />\n    ))}\n  </Box>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/views/ContextUsage.tsx:1-25]()*\n\n## Keyboard Shortcuts\n\nThe tool system integrates with keyboard shortcuts for quick access:\n\n```typescript\n// From packages/cli/src/ui/keyMatchers.test.ts\n[Command.TOGGLE_TOOL_DESCRIPTIONS]: (key: Key) => key.ctrl && key.name === 't',\n[Command.TOGGLE_IDE_CONTEXT_DETAIL]: (key: Key) => key.ctrl && key.name === 'g',\n```\n*资料来源：[packages/cli/src/ui/keyMatchers.test.ts:1-5]()*\n\n## Tool Validation\n\nTools undergo validation before execution:\n\n| Validation | Description |\n|------------|-------------|\n| isValid | Boolean flag indicating if tool is valid |\n| invalidReason | String explaining why tool is invalid |\n| schema | JSON schema for parameters |\n| parameters | Tool input parameters |\n\n```tsx\n// Tool validation display\n{annotations && tool.isValid && (\n  <Text color={theme.text.secondary}>{annotations}</Text>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx:16-18]()*\n\n## Memory and Reference Tools\n\nThe system maintains reference memory for tools that interact with external systems:\n\n```typescript\n// From packages/core/src/memory/prompt.ts\n'<when_to_save>When you learn about resources in external systems and their purpose.</when_to_save>',\n'<how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>',\n```\n\nExamples of external system references:\n- Bug tracking systems (e.g., Linear)\n- Monitoring dashboards (e.g., Grafana)\n- Communication channels (e.g., Slack)\n\n## Configuration\n\n### Tool Registry Configuration\n\nThe tool registry is configured through the main config interface:\n\n```typescript\ngetToolRegistry: () => mockToolRegistry,\ngetTruncateToolOutputThreshold: () => 100,\ngetTruncateToolOutputLines: () => 10,\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:40-42]()*\n\n### Display Configuration\n\nTools can be configured for display with various options:\n\n```typescript\ninterface ToolDisplayConfig {\n  showDescriptions: boolean;\n  showSchema: boolean;\n  visibleCount: number;\n  scrollOffset: number;\n}\n```\n\n## Summary\n\nThe Tools System is a comprehensive framework that enables Qwen Code to interact with the development environment through:\n\n1. **Built-in Tools**: File operations, shell execution, and code editing\n2. **MCP Integration**: Connection to external tools and services via Model Context Protocol\n3. **LSP Integration**: Language server features for code intelligence\n4. **Central Registry**: Unified management of all available tools\n5. **UI Integration**: User-friendly display and interaction with tools\n6. **Validation System**: Ensuring tool validity before execution\n\nThe architecture supports extensibility through the plugin-based design, allowing new tools to be registered and discovered dynamically at runtime.\n\n---\n\n<a id='authentication'></a>\n\n## Authentication and Model Providers\n\n### 相关页面\n\n相关主题：[Turn Processing and LLM Communication](#turn-processing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/auth/providerConfig.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/auth/providerConfig.ts)\n- [packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts)\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [packages/cli/src/ui/components/mcp/steps/AuthenticateStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/mcp/steps/AuthenticateStep.tsx)\n- [packages/cli/src/ui/components/QwenOAuthProgress.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/QwenOAuthProgress.tsx)\n- [README.md](https://github.com/QwenLM/qwen-code/blob/main/README.md)\n</details>\n\n# Authentication and Model Providers\n\n## Overview\n\nThe authentication and model provider system in Qwen Code provides a flexible, pluggable architecture for connecting to various LLM providers. It handles credential management, provider configuration, authentication flows (including OAuth), and model selection across multiple backends including Alibaba ModelStudio, OpenAI-compatible APIs, Ollama, and vLLM.\n\nThe system is designed around a provider configuration model that abstracts authentication details (API keys, OAuth tokens, base URLs) from the core content generation logic, allowing users to seamlessly switch between different providers and models. 资料来源：[packages/cli/src/auth/providerConfig.ts:1-50]()\n\n## Architecture\n\n### Core Components\n\n```mermaid\ngraph TD\n    subgraph \"User Interface Layer\"\n        AD[AuthDialog]\n        AS[AuthenticateStep]\n        QP[QwenOAuthProgress]\n    end\n    \n    subgraph \"Configuration Layer\"\n        PC[ProviderConfig]\n        MC[ModelConfig]\n        SS[Settings Schema]\n    end\n    \n    subgraph \"Provider Registry\"\n        AP[All Providers]\n        PM[Provider Matching]\n    end\n    \n    subgraph \"Authentication Services\"\n        OAuth[OAuth Flow]\n        APIKey[API Key Auth]\n        BaseURL[Base URL Resolution]\n    end\n    \n    AD --> AS\n    AS --> QP\n    PC --> PM\n    PM --> AP\n    AP --> OAuth\n    AP --> APIKey\n    AP --> BaseURL\n```\n\n### Provider Configuration Model\n\nThe `ProviderConfig` interface defines the structure for all provider configurations:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | `string` | Unique provider identifier |\n| `name` | `string` | Display name for the provider |\n| `baseUrl` | `string \\| Array<BaseUrlOption>` | API endpoint base URL |\n| `envKey` | `string` | Environment variable name for API key |\n| `modelsEditable` | `boolean` | Whether users can modify model list |\n| `showAdvancedConfig` | `boolean` | Show advanced configuration options |\n| `uiLabels` | `UILabelsConfig` | UI text labels and titles |\n| `modelNamePrefix` | `string` | Prefix for model names (e.g., provider tag) |\n\n资料来源：[packages/cli/src/auth/providerConfig.ts:20-40]()\n\n## Provider Matching Logic\n\n### Credential-Based Matching\n\nThe system uses a matching algorithm to identify the correct provider based on user credentials:\n\n```mermaid\ngraph TD\n    A[Input: baseUrl, envKey] --> B{envKey match?}\n    B -->|No| C[Return false]\n    B -->|Yes| D{baseUrl type?}\n    D -->|String| E{baseUrl matches?}\n    E -->|Yes| F[Return true]\n    E -->|No| C\n    D -->|Array| G{Any option matches?}\n    G -->|Yes| F\n    G -->|No| C\n```\n\nThe `providerMatchesCredentials` function implements this logic:\n\n```typescript\nexport function providerMatchesCredentials(\n  config: ProviderConfig,\n  baseUrl: string | undefined,\n  envKey: string | undefined,\n): boolean {\n  if (typeof config.envKey !== 'string' || config.envKey !== envKey) {\n    return false;\n  }\n  if (typeof config.baseUrl === 'string') {\n    return config.baseUrl === baseUrl;\n  }\n  if (Array.isArray(config.baseUrl)) {\n    return config.baseUrl.some((opt) => opt.url === baseUrl);\n  }\n  return false;\n}\n```\n\n资料来源：[packages/cli/src/auth/providerConfig.ts:47-63]()\n\n## Model Configuration\n\n### Building Model Configurations\n\nThe `buildModelConfigs` function transforms provider specifications into usable model configurations:\n\n```typescript\nfunction buildGenerationConfig(\n  spec: Pick<ModelSpec, 'enableThinking' | 'contextWindowSize' | 'modalities'>,\n): ProviderModelConfig['generationConfig'] | undefined {\n  const parts: ProviderModelConfig['generationConfig'] = {};\n  let hasAny = false;\n  if (spec.enableThinking) {\n    parts.extra_body = { enable_thinking: true };\n    hasAny = true;\n  }\n  if (spec.contextWindowSize) {\n    parts.contextWindowSize = spec.contextWindowSize;\n    hasAny = true;\n  }\n  if (spec.modalities && Object.values(spec.modalities).some(Boolean)) {\n    parts.modalities = spec.modalities;\n    hasAny = true;\n  }\n  return hasAny ? parts : undefined;\n}\n```\n\n资料来源：[packages/cli/src/auth/providerConfig.ts:90-107]()\n\n### Generation Configuration Options\n\n| Option | Structure | Purpose |\n|--------|-----------|---------|\n| `enableThinking` | `extra_body: { enable_thinking: true }` | Enable chain-of-thought reasoning |\n| `contextWindowSize` | `contextWindowSize: number` | Set maximum context length |\n| `modalities` | `{ text?: boolean, image?: boolean }` | Enable multimodal capabilities |\n\n## Authentication Methods\n\n### Supported Authentication Types\n\n| Method | Description | Status |\n|--------|-------------|--------|\n| **Qwen OAuth** | Alibaba Cloud OAuth flow | Discontinued (2026-04-15) |\n| **Coding Plan** | Alibaba ModelStudio fixed subscription | Active |\n| **API Key** | Direct OpenAI-compatible API access | Active |\n| **OAuth** | Third-party OAuth providers | Active |\n\n资料来源：[packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts:15-20]()\n\n### OAuth Authentication Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as AuthDialog\n    participant AuthStep as AuthenticateStep\n    participant OAuth as OAuthProvider\n    participant Browser\n\n    User->>CLI: Select OAuth provider\n    CLI->>AuthStep: Initialize OAuth flow\n    AuthStep->>OAuth: Request authorization URL\n    OAuth-->>AuthStep: Return verification URL\n    AuthStep->>User: Display URL + copy option\n    User->>Browser: Open verification URL\n    Browser->>OAuth: Complete authorization\n    OAuth-->>Browser: Authorization granted\n    Browser-->>User: Success confirmation\n    AuthStep->>OAuth: Poll for token\n    OAuth-->>AuthStep: Return access token\n    AuthStep-->>CLI: Authentication complete\n```\n\n### OAuth Progress UI\n\nThe `QwenOAuthProgress` component displays the device authorization flow:\n\n```typescript\nexport function QwenOAuthProgress({\n  deviceAuth,\n  timeRemaining,\n}: QwenOAuthProgressProps): React.JSX.Element {\n  return (\n    <Box flexDirection=\"column\" padding={1} width=\"100%\">\n      <Text bold>{t('Qwen OAuth Authentication')}</Text>\n      <Link url={deviceAuth.verification_uri_complete || ''}>\n        {deviceAuth.verification_uri_complete}\n      </Link>\n      <Text>\n        {t('Waiting for authorization')}\n        {dots}\n      </Text>\n      <Text>{t('Time remaining:')} {formatTime(timeRemaining)}</Text>\n    </Box>\n  );\n}\n```\n\n资料来源：[packages/cli/src/ui/components/QwenOAuthProgress.tsx:1-30]()\n\n## Discontinued Model Detection\n\n### ACP Model ID Parsing\n\nThe ACP (Agent Communication Protocol) server emits model IDs in a wrapped format for tracking discontinued models:\n\n| Format | Example |\n|--------|---------|\n| Standard | `qwen3-coder-plus(qwen-oauth)` |\n| Runtime | `$runtime\\|qwen-oauth\\|qwen3-coder-plus(qwen-oauth)` |\n\nThe `ParsedAcpModelId` interface extracts the base model ID and auth type:\n\n```typescript\nexport interface ParsedAcpModelId {\n  /** Model id with the trailing `(authType)` marker stripped. */\n  baseModelId: string;\n  /** Auth type extracted from the trailing `(authType)` marker. */\n  authType: string;\n}\n\nexport const DISCONTINUED_MESSAGES = {\n  badge: '(Discontinued)',\n  description: 'Discontinued — switch to Coding Plan or API Key',\n  blockedError:\n    'Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.',\n} as const;\n```\n\n资料来源：[packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts:20-35]()\n\n## Configuration Settings\n\n### Settings Schema Structure\n\nThe system uses a hierarchical settings structure defined in `settingsSchema.ts`:\n\n```mermaid\ngraph TD\n    SS[settings.json] --> MP[modelProviders]\n    MP --> OP[openai Array]\n    OP --> PMC[ProviderModelConfig]\n    PMC --> id\n    PMC --> name\n    PMC --> baseUrl\n    PMC --> description\n    PMC --> envKey\n    PMC --> generationConfig\n    SS --> S[security]\n    S --> auth\n    auth --> selectedType\n    SS --> M[model]\n    M --> name\n```\n\n### Provider Setup Inputs\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `baseUrl` | `string` | Yes | API endpoint base URL |\n| `apiKey` | `string` | Yes | API key value (or empty for template) |\n| `modelIds` | `string[]` | No | Specific model IDs to include |\n\n## Supported Providers\n\n### Provider Configuration Examples\n\n#### Alibaba ModelStudio (Coding Plan)\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3.6-plus\",\n        \"name\": \"qwen3.6-plus (Coding Plan)\",\n        \"baseUrl\": \"https://coding.dashscope.aliyuncs.com/v1\",\n        \"description\": \"qwen3.6-plus from ModelStudio Coding Plan\",\n        \"envKey\": \"BAILIAN_CODING_PLAN_API_KEY\"\n      }\n    ]\n  }\n}\n```\n\n资料来源：[README.md:50-65]()\n\n#### Ollama (Local)\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3:32b\",\n        \"name\": \"Qwen3 32B (Ollama)\",\n        \"baseUrl\": \"http://localhost:11434/v1\",\n        \"description\": \"Qwen3 32B running locally via Ollama\",\n        \"generationConfig\": {\n          \"contextWindowSize\": 131072\n        }\n      }\n    ]\n  }\n}\n```\n\n资料来源：[README.md:150-165]()\n\n#### vLLM (Local)\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"Qwen/Qwen3-32B\",\n        \"name\": \"Qwen3 32B (vLLM)\",\n        \"baseUrl\": \"http://localhost:8000/v1\",\n        \"description\": \"Qwen3 32B running locally via vLLM\",\n        \"generationConfig\": {\n          \"contextWindowSize\": 131072\n        }\n      }\n    ]\n  }\n}\n```\n\n## Auth Dialog Workflow\n\n### View State Machine\n\n```mermaid\ngraph TD\n    M[main] --> AS[alibaba-select]\n    M --> TS[thirdparty-select]\n    M --> OS[oauth-select]\n    AS --> BR[baseUrl Step]\n    TS --> BR\n    OS --> BR\n    BR --> PK[apiKey Step]\n    PK --> MD[models Step]\n    MD --> AC[advancedConfig Step]\n    AC --> RV[review Step]\n    RV --> M\n```\n\nThe `AuthDialog` component manages this state:\n\n```typescript\nexport function AuthDialog(): React.JSX.Element {\n  const {\n    auth: { pendingAuthType, authError },\n  } = useUIState();\n  const {\n    auth: {\n      handleAuthSelect: onAuthSelect,\n      handleProviderSubmit,\n      handleOpenRouterSubmit,\n      onAuthError,\n    },\n  } = useUIActions();\n  const config = useConfig();\n  const settings = useSettings();\n\n  const [errorMessage, setErrorMessage] = useState<string | null>(null);\n  const [viewLevel, setViewLevel] = useState<ViewLevel>('main');\n  const [_viewStack, setViewStack] = useState<ViewStack>([]);\n```\n\n资料来源：[packages/cli/src/ui/auth/AuthDialog.tsx:60-85]()\n\n### Step Labels\n\n| Step Key | Label | Description |\n|----------|-------|-------------|\n| `protocol` | Protocol | Select communication protocol |\n| `baseUrl` | Base URL / Endpoint | Configure API endpoint |\n| `apiKey` | API Key | Enter credentials |\n| `models` | Model IDs | Select available models |\n| `advancedConfig` | Advanced Config | Show/hide advanced options |\n| `review` | Review | Confirm configuration |\n\n## Environment Variables\n\n### API Key Environment Variables\n\n| Provider | Environment Variable | Description |\n|----------|---------------------|-------------|\n| Alibaba ModelStudio | `DASHSCOPE_API_KEY` | Standard API key |\n| Alibaba Coding Plan | `BAILIAN_CODING_PLAN_API_KEY` | Subscription API key |\n| OpenAI | `OPENAI_API_KEY` | OpenAI API key |\n| Custom Providers | Variable defined in `envKey` field | Provider-specific |\n\n资料来源：[README.md:80-85]()\n\n## Security Considerations\n\n- **Never commit API keys** to version control — the `~/.qwen/settings.json` file should remain private\n- API keys via `export` or `.env` files take higher priority than `settings.json` → `env` configuration\n- The authentication system supports both key-based and OAuth-based authentication for different trust levels\n\n## Related Commands\n\n| Command | Description |\n|---------|-------------|\n| `/auth` | Launch interactive authentication setup |\n| `/model` | Switch between configured models |\n| `/mcp auth <server-name>` | Authenticate with OAuth-enabled MCP servers |\n\n资料来源：[packages/cli/src/ui/components/views/McpStatus.tsx:15-20]()\n\n---\n\n<a id='memory-system'></a>\n\n## Memory System\n\n### 相关页面\n\n相关主题：[Session Management](#session-management), [Core Agent Runtime](#agent-runtime)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/memory/manager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/manager.ts)\n- [packages/core/src/memory/entries.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/entries.ts)\n- [packages/core/src/memory/recall.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/recall.ts)\n- [packages/core/src/memory/extract.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/extract.ts)\n- [packages/core/src/memory/prompt.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/prompt.ts)\n- [packages/core/src/memory/dreamAgentPlanner.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/dreamAgentPlanner.ts)\n- [packages/core/src/memory/extractionAgentPlanner.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/extractionAgentPlanner.ts)\n</details>\n\n# Memory System\n\n## Overview\n\nThe Memory System is a persistent, file-based knowledge management component in Qwen Code that enables the AI assistant to maintain context across conversations. It allows the system to remember information about users, projects, feedback, and external references, providing personalized and context-aware assistance over time.\n\nThe memory system is built around a directory structure at a configurable root location (`~/.qwen/memory/` by default) and uses Markdown files with structured frontmatter for storing persistent information. 资料来源：[packages/core/src/memory/prompt.ts:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[User Conversation] --> B[Memory Extraction Agent]\n    B --> C[Memory Files]\n    C --> D[Index File]\n    D --> E[Memory Recall]\n    E --> A\n    \n    F[Dream Agent] -->|Periodic Consolidation| C\n    F --> D\n    \n    G[CLI Remember Command] -->|Manual Save| C\n    G --> D\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| Memory Manager | `manager.ts` | Core memory operations and configuration |\n| Memory Entries | `entries.ts` | Data structures for memory items |\n| Memory Recall | `recall.ts` | Retrieval and context injection |\n| Memory Extraction | `extract.ts` | Automatic memory extraction from conversations |\n| Prompt Builder | `prompt.ts` | Prompt templates for memory operations |\n| Dream Agent | `dreamAgentPlanner.ts` | Periodic memory consolidation |\n| Extraction Agent | `extractionAgentPlanner.ts` | Extraction prompt generation |\n\n## Memory Types\n\nThe system supports four primary memory types, each stored in its own subdirectory:\n\n### Memory Type Structure\n\n```mermaid\ngraph LR\n    A[Memory Root] --> B[user/]\n    A --> C[feedback/]\n    A --> D[project/]\n    A --> E[reference/]\n```\n\n### Type Definitions\n\n| Type | Directory | Purpose | When to Save |\n|------|-----------|---------|--------------|\n| **User** | `user/` | User preferences, working style, collaboration patterns | When learning about user preferences, habits, or personal context |\n| **Feedback** | `feedback/` | Feedback on AI outputs, corrections, style preferences | When user corrects or provides feedback on AI responses |\n| **Project** | `project/` | Project-specific context, architecture, conventions | When learning about project structure, requirements, or technical decisions |\n| **Reference** | `reference/` | External systems, resources, documentation links | When learning about external systems (e.g., bug trackers, dashboards) |\n\n资料来源：[packages/core/src/memory/prompt.ts:50-120]()\n\n### What NOT to Save\n\nPer the system guidelines, the following should not be stored in memory:\n\n- Code patterns, conventions, architecture, file paths, or project structure\n- Git history, recent changes, or who-changed-what\n- Debugging solutions or fix recipes\n- Date-based information outside of the project directory\n\n资料来源：[packages/core/src/memory/prompt.ts:100-115]()\n\n## Memory File Format\n\nMemory files use structured Markdown with YAML frontmatter:\n\n```yaml\n---\ntitle: <Title>\ntype: <user | feedback | project | reference>\ncreated: <ISO timestamp>\nupdated: <ISO timestamp>\n---\n# Memory Content\n\n<Detailed memory information>\n```\n\n### Index File\n\nThe `index.md` file serves as a catalog of all memories:\n\n```markdown\n# index\n\n- [Title](relative/path.md) — one-line hook\n- [Another Memory](another/file.md) — brief description\n```\n\nEach index entry must be a single line with the format: `- [Title](relative/path.md) — one-line hook`\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-50]()\n\n## Memory Operations\n\n### Memory Extraction\n\nMemory extraction is an automated process that identifies valuable information during conversations. The extraction agent uses a limited tool set:\n\n**Available Tools:**\n- `grep_search`\n- `glob`\n- `list_directory`\n- `read_file` / `write_file` / `edit` (memory directory only)\n\n**Extraction Workflow:**\n\n```mermaid\nsequenceDiagram\n    participant User as User Message\n    participant Extract as Extraction Agent\n    participant FS as Memory Files\n    \n    User->>Extract: Conversation with new information\n    Extract->>FS: Read existing memory files\n    Extract->>FS: Check for duplicates\n    Extract->>FS: Write/Update memory file\n    Extract->>FS: Update index.md\n```\n\n**Efficient Strategy:**\n1. Issue all reads in parallel for files that might be updated\n2. Issue all writes/edits in parallel\n3. Never interleave reads and writes across multiple turns\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-30]()\n\n### Memory Recall\n\nMemory recall retrieves relevant memories based on context. The system:\n\n1. Maintains a rolling context of recent memories\n2. Dynamically loads memories based on conversation relevance\n3. Limits loaded memories to prevent context overflow\n\n**Memory Truncation:**\n\nThe system warns when `MEMORY.md` exceeds size limits:\n- Maximum managed auto memory index lines: 512\n- Warning message format: `> WARNING: MEMORY.md is [reason]. Only part of it was loaded.`\n\n资料来源：[packages/core/src/memory/prompt.ts:1-30]()\n\n### Memory Consolidation (Dream Agent)\n\nThe Dream Agent runs periodically to consolidate and clean up memories:\n\n**Consolidation Phases:**\n\n```mermaid\ngraph TD\n    A[Phase 1: Orient] --> B[Phase 2: Gather Signal]\n    B --> C[Phase 3: Consolidate]\n    C --> D[Phase 4: Prune]\n```\n\n#### Phase 1 — Orient\n- List the memory directory to see existing files\n- Read `memoryRoot/index.md` to understand current state\n- Skim topic subdirectories (`user/`, `project/`, `feedback/`, `reference/`)\n- Review recent entries in `logs/` or `sessions/` subdirectories\n\n#### Phase 2 — Gather Recent Signal\n- Look for new information worth persisting\n- Check for existing memories that have drifted\n- Grep session transcripts for narrow terms if context is needed\n\n#### Phase 3 — Consolidate\nFor each topic directory:\n- Identify duplicate or near-duplicate `.md` files\n- Merge duplicates into canonical versions\n- Fix stale or contradicted facts\n- Convert relative dates to absolute dates\n\n资料来源：[packages/core/src/memory/dreamAgentPlanner.ts:1-60]()\n\n## Manual Memory Operations\n\n### CLI Remember Command\n\nUsers can manually save information using the `/remember` command:\n\n```bash\n/remember <fact-to-remember>\n```\n\n**Behavior:**\n- When managed auto-memory is enabled: The system asks the agent to save to the appropriate memory type directory\n- When disabled: The system asks the agent to append to `QWEN.md` in the project root\n\n**Implementation Flow:**\n\n```mermaid\ngraph LR\n    A[/remember command] --> B{Memory Enabled?}\n    B -->|Yes| C[Submit to Agent]\n    C --> D[Prompt Agent to Save]\n    D --> E[Choose memory type]\n    E --> F[Save to appropriate directory]\n    \n    B -->|No| G[Submit to Agent]\n    G --> H[Append to QWEN.md]\n```\n\n资料来源：[packages/cli/src/ui/commands/rememberCommand.ts:1-60]()\n\n## UI Integration\n\n### Memory Statistics Display\n\nThe UI displays memory operation statistics in tool call summaries:\n\n```typescript\n// Memory statistics shown in ToolGroupMessage\nif (memoryRecallCount > 0) {\n    parts.push(`Recalled ${n} ${n === 1 ? 'memory' : 'memories'}`);\n}\nif (memoryWriteCount > 0) {\n    parts.push(`Wrote ${n} ${n === 1 ? 'memory' : 'memories'}`);\n}\n```\n\n**Display Format:**\n- Shows count of recalled memories\n- Shows count of written memories\n- Rendered as inline summary after tool execution\n\n资料来源：[packages/cli/src/ui/components/messages/ToolGroupMessage.tsx:1-50]()\n\n### Memory Usage Metrics\n\nThe telemetry system tracks memory operations:\n\n| Metric | Type | Description |\n|--------|------|-------------|\n| `memory.dream.count` | Counter | Number of memory consolidation runs |\n| `memory.dream.duration` | Histogram | Duration of consolidation operations |\n| `memory.recall.count` | Counter | Number of memory recall operations |\n| `memory.recall.duration` | Histogram | Duration of recall operations |\n| `memory.extract.duration` | Histogram | Duration of extraction operations |\n| `memory.usage` | Histogram | Memory usage in bytes |\n\n资料来源：[packages/core/src/telemetry/metrics.ts:1-50]()\n\n## Configuration\n\n### Memory Root Path\n\nThe memory system is configured at:\n\n```\n~/.qwen/memory/  (default)\n```\n\n### Directory Structure\n\n```\nmemoryRoot/\n├── index.md           # Master index of all memories\n├── user/              # User preference memories\n│   └── *.md\n├── feedback/          # Feedback memories\n│   └── *.md\n├── project/           # Project-specific memories\n│   └── *.md\n├── reference/         # External reference memories\n│   └── *.md\n├── logs/              # Session logs (optional)\n└── sessions/          # Session transcripts (optional)\n```\n\n## Best Practices\n\n### Index Entry Guidelines\n\n- Keep index entries to one line under ~200 characters\n- Move detailed content into topic files\n- Each entry format: `- [Title](relative/path.md) — one-line hook`\n\n### Memory File Guidelines\n\n- One durable memory per file\n- Use frontmatter with title, type, created, and updated fields\n- Avoid duplicate or near-duplicate content\n- Convert relative dates to absolute dates\n\n### When to Update vs. Create\n\n- Prefer updating an existing memory file over creating duplicates\n- Check for existing entries before creating new ones\n- Consolidate related information into single files\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-40]()\n\n## Related Documentation\n\n- [Managed Auto Memory Prompt Template](packages/core/src/memory/prompt.ts) — Complete prompt for memory system\n- [Dream Agent Planner](packages/core/src/memory/dreamAgentPlanner.ts) — Consolidation workflow\n- [Extraction Agent Planner](packages/core/src/memory/extractionAgentPlanner.ts) — Extraction guidelines\n- [Remember Command](packages/cli/src/ui/commands/rememberCommand.ts) — Manual memory saving\n\n---\n\n<a id='session-management'></a>\n\n## Session Management\n\n### 相关页面\n\n相关主题：[Memory System](#memory-system), [Core Agent Runtime](#agent-runtime)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/services/sessionService.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/services/sessionService.ts)\n- [packages/core/src/services/sessionRecap.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/services/sessionRecap.ts)\n- [packages/core/src/services/sessionTitle.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/services/sessionTitle.ts)\n- [packages/core/src/config/storage.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/config/storage.ts)\n- [packages/vscode-ide-companion/src/services/qwenAgentManager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/vscode-ide-companion/src/services/qwenAgentManager.ts)\n- [packages/cli/src/ui/contexts/UIActionsContext.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/contexts/UIActionsContext.tsx)\n- [packages/cli/src/ui/hooks/useBranchCommand.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/hooks/useBranchCommand.ts)\n</details>\n\n# Session Management\n\n## Overview\n\nSession Management is a core system in Qwen Code that orchestrates the lifecycle of agent conversations. It handles creating new sessions, persisting conversation history, enabling session branching (forking), resuming previous sessions, and managing session metadata. The system ensures continuity across interactions and supports features like session recap generation, title derivation, and artifact preservation.\n\nSession management operates across multiple packages including `packages/core`, `packages/cli`, and `packages/vscode-ide-companion`, with data persisted to the file system in JSONL format.\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"CLI Layer\"\n        UI[UI Components]\n        Actions[UIActionsContext]\n        BranchCmd[useBranchCommand]\n    end\n    \n    subgraph \"Core Services\"\n        SessionService[SessionService]\n        SessionRecap[SessionRecap]\n        SessionTitle[SessionTitle]\n    end\n    \n    subgraph \"Storage Layer\"\n        Storage[Storage Config]\n        FileSystem[File System]\n        ACP[ACP Protocol]\n    end\n    \n    UI --> Actions\n    Actions --> BranchCmd\n    BranchCmd --> SessionService\n    SessionService --> Storage\n    SessionService --> SessionTitle\n    SessionService --> SessionRecap\n    Storage --> FileSystem\n    ACP --> SessionService\n    \n    QwenAgent[QwenAgentManager] --> ACP\n    QwenAgent --> Storage\n```\n\n## Core Services\n\n### SessionService\n\nThe `SessionService` is the central orchestrator for all session operations. It provides APIs for:\n\n| Method | Description |\n|--------|-------------|\n| `createSession()` | Creates a new session with unique ID |\n| `forkSession()` | Creates a branch (fork) of an existing session |\n| `getSession()` | Retrieves a session by ID |\n| `listSessions()` | Lists all sessions, optionally filtered by project |\n| `deleteSession()` | Removes a session and its artifacts |\n| `saveSession()` | Persists session state to disk |\n| `loadSession()` | Loads session from storage |\n\n资料来源：[packages/core/src/services/sessionService.ts]()\n\n#### Session Data Model\n\n```typescript\ninterface QwenSession {\n  sessionId: string;\n  title: string;\n  name: string;\n  startTime: number;\n  lastUpdated: number;\n  messageCount: number;\n  projectHash?: string;\n  filePath?: string;\n  cwd?: string;\n}\n```\n\n资料来源：[packages/vscode-ide-companion/src/services/qwenAgentManager.ts:24-33]()\n\n### SessionTitle Service\n\nThe `SessionTitle` service automatically derives session titles from conversation content. It analyzes the first user prompt and generates a human-readable title that identifies the session's purpose.\n\n| Feature | Description |\n|---------|-------------|\n| Title Derivation | Extracts meaningful title from initial prompt |\n| Auto-naming | Provides default names like \"Untitled Session\" when no title is available |\n| Persistence | Titles are saved with session metadata |\n\n资料来源：[packages/core/src/services/sessionTitle.ts]()\n\n### SessionRecap Service\n\nThe `SessionRecap` service generates summary information about sessions, providing context for:\n\n- Session status display\n- Background task tracking\n- Conversation metadata\n\n资料来源：[packages/core/src/services/sessionRecap.ts]()\n\n## Storage Architecture\n\n### File System Storage\n\nSessions are persisted to the file system using a structured directory layout:\n\n```mermaid\ngraph TD\n    Root[Project/Root Directory]\n    QwenDir[.qwen/]\n    SessionsDir[sessions/]\n    Session1[session-id-1.jsonl]\n    Session2[session-id-2.jsonl]\n    \n    Root --> QwenDir\n    QwenDir --> SessionsDir\n    SessionsDir --> Session1\n    SessionsDir --> Session2\n```\n\nThe `Storage` config provides methods for:\n\n| Method | Purpose |\n|--------|---------|\n| `getProjectTempDir()` | Get temporary directory for session artifacts |\n| `getSessionDir()` | Get the sessions directory path |\n| `getSessionFile()` | Get path for a specific session file |\n\n资料来源：[packages/core/src/config/storage.ts]()\n\n### Session File Format\n\nSession data is stored in JSONL (JSON Lines) format, with each line representing a single message or event in the conversation. This format allows for:\n\n- Efficient streaming writes\n- Incremental reading\n- Easy append operations\n\n### ACP Protocol Fallback\n\nWhen the Agent Communication Protocol (ACP) session list fails, the system automatically falls back to reading sessions directly from the file system:\n\n```typescript\n// From qwenAgentManager.ts\ntry {\n  const items = await acpClient.listSessions();\n  if (items.length > 0) {\n    return items.map(/* transform to session format */);\n  }\n} catch (error) {\n  console.warn('[QwenAgentManager] ACP session list failed, falling back...');\n}\n\n// Fallback to file system\nconst sessions = await this.sessionReader.getAllSessions(undefined, true);\n```\n\n资料来源：[packages/vscode-ide-companion/src/services/qwenAgentManager.ts:55-71]()\n\n## Session Lifecycle Operations\n\n### Creating a New Session\n\n```mermaid\ngraph LR\n    A[Start] --> B[Generate Session ID]\n    B --> C[Create Session Object]\n    C --> D[Initialize Message Queue]\n    D --> E[Save to File System]\n    E --> F[Update UI State]\n```\n\n### Session Branching (Forking)\n\nThe branch command allows creating a fork of an existing session, enabling parallel exploration of different approaches:\n\n```mermaid\ngraph TD\n    A[Original Session] --> B[Invoke /branch Command]\n    B --> C[Capture Parent Session ID]\n    B --> D[Finalize Current Recording]\n    C --> E[forkSession Service Call]\n    D --> E\n    E --> F[Write New JSONL File]\n    F --> G[Load Forked Session]\n    G --> H[Update UI Context]\n    H --> I[Fire SessionStart Hook]\n```\n\nThe branching process:\n\n1. Captures the current session ID for resume hint\n2. Finalizes the ChatRecordingService to persist last metadata\n3. Calls `SessionService.forkSession()` to create a new JSONL file\n4. Loads the fork back via `loadSession`\n5. Computes custom title with \"(Branch)\" suffix\n6. Announces the fork with Claude-style info\n\n资料来源：[packages/cli/src/ui/hooks/useBranchCommand.ts]()\n\n### Session Resumption\n\nResuming a session allows returning to a previous conversation:\n\n| Step | Action |\n|------|--------|\n| 1 | User invokes `/resume` command |\n| 2 | System loads session from storage |\n| 3 | Chat history is restored |\n| 4 | Context and configuration are restored |\n\n### Session Deletion\n\nSessions can be deleted individually or in bulk:\n\n```typescript\n// From UIActionsContext.tsx\nhandleDelete: (sessionId: string) => void;\nhandleDeleteMany: (sessionIds: string[]) => void;\n```\n\n资料来源：[packages/cli/src/ui/contexts/UIActionsContext.tsx:89-90]()\n\n## UI Integration\n\n### UIActionsContext\n\nThe `UIActionsContext` provides a comprehensive interface for session-related UI operations:\n\n| Action | Description |\n|--------|-------------|\n| `openResumeDialog()` | Opens dialog to resume a previous session |\n| `closeResumeDialog()` | Closes resume dialog |\n| `handleResume(sessionId)` | Resumes specific session |\n| `handleBranch(name?)` | Creates a branch/fork |\n| `openDeleteDialog()` | Opens delete confirmation dialog |\n| `handleDelete(sessionId)` | Deletes a single session |\n| `handleDeleteMany(sessionIds)` | Bulk deletes sessions |\n\n资料来源：[packages/cli/src/ui/contexts/UIActionsContext.tsx:76-92]()\n\n### Background Tasks Dialog\n\nSession information is displayed in the background tasks dialog, showing:\n\n- Session review status\n- Session count\n- Topics touched in the conversation\n- Error states and lock-release warnings\n\n```typescript\n// From BackgroundTasksDialog.tsx\n{entry.sessionCount !== undefined && (\n  <Fragment>\n    <Text bold dimColor>{t('Sessions reviewing')}</Text>\n    <Text>{String(entry.sessionCount)}</Text>\n  </Fragment>\n)}\n```\n\n## Arena Session Management\n\nArena sessions have specialized management options for handling artifacts:\n\n```typescript\ntype StopAction = 'cleanup' | 'preserve';\n```\n\n| Action | Behavior |\n|--------|----------|\n| `cleanup` | Remove all worktrees and session files |\n| `preserve` | Keep worktrees and session files for later inspection |\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaStopDialog.tsx]()\n\n## Configuration\n\n### Session-Related Configuration\n\n```typescript\ninterface SessionConfig {\n  getSessionId: () => string;\n  getUsageStatisticsEnabled: () => boolean;\n  getDebugMode: () => boolean;\n  getApprovalMode: () => ApprovalMode;\n  storage: {\n    getProjectTempDir: () => string;\n  };\n}\n```\n\n## Related Commands\n\n| Command | Description |\n|---------|-------------|\n| `/branch` | Fork current session |\n| `/resume` | Resume a previous session |\n| `/delete` | Delete session(s) |\n| `/sessions` | List all sessions |\n\n## Summary\n\nThe Session Management system in Qwen Code provides a robust framework for:\n\n1. **Lifecycle Management** - Creating, forking, resuming, and deleting sessions\n2. **Persistence** - Storing sessions in JSONL format on the file system\n3. **Metadata** - Managing titles, timestamps, and conversation statistics\n4. **UI Integration** - Rich dialogs and context providers for session operations\n5. **Cross-Platform** - Unified session management across CLI and VS Code IDE companion\n\nAll session operations are designed to be atomic and reliable, with automatic fallbacks (e.g., ACP → file system) to ensure data accessibility.\n\n---\n\n<a id='skills-system'></a>\n\n## Skills System\n\n### 相关页面\n\n相关主题：[Extensions System](#extensions), [Core Agent Runtime](#agent-runtime)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/skills/skill-manager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/skill-manager.ts)\n- [packages/core/src/skills/skill-load.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/skill-load.ts)\n- [packages/core/src/skills/skill-activation.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/skill-activation.ts)\n- [packages/core/src/skills/types.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/types.ts)\n- [packages/core/src/skills/bundled/review/SKILL.md](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/bundled/review/SKILL.md)\n- [packages/cli/src/ui/components/views/ContextUsage.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/views/ContextUsage.tsx)\n- [packages/cli/src/ui/components/HistoryItemDisplay.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/HistoryItemDisplay.tsx)\n- [packages/core/src/core/coreToolScheduler.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/coreToolScheduler.ts)\n</details>\n\n# Skills System\n\n## Overview\n\nThe Skills System is a modular extension framework within qwen-code that enables dynamic loading and activation of predefined capabilities. Skills are specialized modules that extend the agent's functionality beyond built-in tools, allowing users to configure and utilize domain-specific capabilities through a standardized interface.\n\nSkills serve as a composition layer between the core agent and specialized functionality, providing:\n- **Modular capability packaging** - Skills bundle related functionality into self-contained units\n- **Dynamic loading** - Skills can be loaded on-demand without restarting the application\n- **Token-based resource tracking** - Each skill reports its token consumption for context management\n- **Model override support** - Skills can influence which model handles specific requests\n\n资料来源：[packages/core/src/skills/types.ts]()\n\n## Architecture\n\nThe Skills System follows a layered architecture with clear separation of concerns:\n\n```mermaid\ngraph TD\n    A[Agent Request] --> B[Skill Manager]\n    B --> C[Skill Loader]\n    C --> D[Skill Activation]\n    D --> E[Skill Execution]\n    \n    F[Skill Manifest<br/>SKILL.md] --> C\n    G[User Config] --> B\n    H[Token Budget] --> E\n    \n    E --> I[Response with<br/>Model Override]\n    E --> J[Tool Results]\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| Skill Manager | `skill-manager.ts` | Orchestrates skill lifecycle, registration, and retrieval |\n| Skill Loader | `skill-load.ts` | Parses skill manifests, validates, and instantiates skills |\n| Skill Activation | `skill-activation.ts` | Manages skill activation state and context injection |\n| Skill Types | `types.ts` | Defines interfaces, enums, and type contracts |\n\n资料来源：[packages/core/src/skills/skill-manager.ts]()\n\n## Skill Structure\n\n### Skill Manifest (SKILL.md)\n\nEach skill is defined by a `SKILL.md` manifest file that describes its metadata and behavior:\n\n```markdown\n# Skill: Review\n\n## Description\nPerforms code review analysis with configurable rules.\n\n## Triggers\n- Command: `/review`\n- Auto-suggest: On file save\n\n## Actions\n- analyze(code): ReviewResult\n- suggest_fixes(issues): Fix[]\n```\n\n资料来源：[packages/core/src/skills/bundled/review/SKILL.md]()\n\n### Skill Data Model\n\n```typescript\ninterface Skill {\n  name: string;           // Unique identifier\n  loaded: boolean;        // Current activation state\n  tokens: number;         // Token consumption for context\n  bodyTokens?: number;    // Additional body tokens if loaded\n  description?: string;   // Human-readable description\n}\n```\n\n资料来源：[packages/cli/src/ui/components/views/ContextUsage.tsx:55-61]()\n\n## Skill Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Unregistered\n    Unregistered --> Registered: Register Skill\n    Registered --> Loading: Activate Skill\n    Loading --> Active: Load Complete\n    Active --> Loading: Re-activate\n    Active --> Inactive: Deactivate\n    Inactive --> Active: Reactivate\n    Inactive --> Unregistered: Unregister\n    Registered --> Unregistered: Unregister\n```\n\n### States\n\n| State | Description |\n|-------|-------------|\n| `Unregistered` | Skill not known to the system |\n| `Registered` | Skill manifest parsed and indexed |\n| `Loading` | Skill resources being prepared |\n| `Active` | Skill ready for execution |\n| `Inactive` | Skill loaded but temporarily disabled |\n\n## Skill Loading Process\n\nThe skill loading process involves multiple stages:\n\n```mermaid\nsequenceDiagram\n    participant SM as Skill Manager\n    participant SL as Skill Loader\n    participant SA as Skill Activator\n    participant FS as File System\n    \n    SM->>FS: Read SKILL.md manifest\n    FS-->>SL: Manifest content\n    SL->>SL: Parse YAML frontmatter\n    SL->>SL: Validate schema\n    SL->>SA: Validated manifest\n    SA->>SA: Allocate token budget\n    SA-->>SM: Skill activated\n    SM->>SM: Update skill registry\n```\n\n资料来源：[packages/core/src/skills/skill-load.ts]()\n\n## Integration with Tool System\n\nSkills integrate with the core tool scheduler through a unified execution model:\n\n```mermaid\ngraph LR\n    A[Agent Request] --> B{Request Type}\n    B -->|Tool Call| C[Tool Scheduler]\n    B -->|Skill Action| D[Skill Activation]\n    \n    C --> E[Tool Executor]\n    D --> E\n    \n    E --> F[Function Response]\n    F --> G[Response with Metadata]\n    \n    H[Model Override] --> G\n    D --> H\n```\n\n### Model Override Propagation\n\nSkills can return a `modelOverride` field that influences which model handles subsequent requests:\n\n```typescript\nconst successResponse: ToolCallResponseInfo = {\n  callId,\n  responseParts: response,\n  resultDisplay: toolResult.returnDisplay,\n  error: undefined,\n  errorType: undefined,\n  contentLength,\n  // Propagate modelOverride from skill tools\n  ...('modelOverride' in toolResult\n    ? { modelOverride: toolResult.modelOverride }\n    : {}),\n};\n```\n\n资料来源：[packages/core/src/core/coreToolScheduler.ts:248-258]()\n\n## Context Usage Tracking\n\nThe system tracks skill resource consumption for context management:\n\n```typescript\ninterface ContextUsage {\n  modelName: string;\n  totalTokens: number;\n  contextWindowSize: number;\n  breakdown: TokenBreakdown;\n  skills: Skill[];\n  builtinTools: Tool[];\n  mcpTools: Tool[];\n  memoryFiles: FileInfo[];\n  isEstimated: boolean;\n  showDetails: boolean;\n}\n```\n\n资料来源：[packages/cli/src/ui/components/HistoryItemDisplay.tsx:89-98]()\n\n### Skill Display in Context Usage\n\nSkills are rendered with the following information hierarchy:\n\n| Field | Display | Description |\n|-------|---------|-------------|\n| `name` | Link text | Skill identifier |\n| `loaded` | Badge \"active\" | Green indicator when active |\n| `tokens` | Numeric count | Total tokens consumed |\n| `bodyTokens` | Italic secondary | Body content token count |\n\n```typescript\n{sortedSkills.map((skill) => (\n  <Box key={skill.name} flexDirection=\"column\">\n    <Box width={CONTENT_WIDTH} paddingLeft={2}>\n      <Text>{'\\u2514'} </Text>\n      <Box width={32}>\n        <Text color={theme.text.link}>\n          {truncateName(skill.name, DETAIL_NAME_MAX_LEN)}\n        </Text>\n        {skill.loaded && (\n          <Text color={theme.status.success}> {t('active')}</Text>\n        )}\n      </Box>\n      <Box flexGrow={1} justifyContent=\"flex-end\">\n        <Text color={theme.text.secondary}>\n          {formatTokens(skill.tokens)} {t('tokens')}\n        </Text>\n      </Box>\n    </Box>\n  </Box>\n))}\n```\n\n资料来源：[packages/cli/src/ui/components/views/ContextUsage.tsx:55-73]()\n\n## User Interface Components\n\n### Skills List Component\n\nThe `SkillsList` component renders available skills in the history view:\n\n```typescript\n{itemForDisplay.type === 'skills_list' && (\n  <SkillsList skills={itemForDisplay.skills} />\n)}\n```\n\n资料来源：[packages/cli/src/ui/components/HistoryItemDisplay.tsx:54-56]()\n\n### Skill Registration Flow\n\n```mermaid\ngraph TD\n    A[Start CLI] --> B[Load User Config]\n    B --> C[Scan Skill Directories]\n    C --> D{skill found?}\n    D -->|Yes| E[Parse SKILL.md]\n    D -->|No| F[Skip]\n    E --> G{Valid manifest?}\n    G -->|Yes| H[Register in Manager]\n    G -->|No| I[Log warning]\n    H --> J[Add to active list]\n    J --> K[Ready for use]\n```\n\n## Configuration\n\nSkills can be configured through the main configuration system:\n\n| Config Option | Type | Default | Description |\n|---------------|------|---------|-------------|\n| `skills.enabled` | boolean | `true` | Enable/disable skills system |\n| `skills.maxTokens` | number | `8000` | Maximum tokens for all skills |\n| `skills.autoLoad` | boolean | `true` | Load skills on startup |\n\nConfiguration is accessed through the central `Config` interface which provides access to skill-related settings.\n\n## Bundled Skills\n\nThe repository includes bundled skills that provide out-of-the-box functionality:\n\n| Skill | Path | Purpose |\n|-------|------|---------|\n| Review | `bundled/review/` | Code review and analysis |\n\n资料来源：[packages/core/src/skills/bundled/review/SKILL.md]()\n\n## Error Handling\n\nThe skill system integrates with the tool scheduler's error handling mechanism:\n\n```typescript\n// Failure handling in skill execution\nif (hooksEnabled && messageBus) {\n  const failureHookResult = await safelyFirePostToolUseFailureHook(\n    messageBus,\n    toolUseId,\n    toolName,\n    toolInput,\n    toolResult.error.message,\n    false,\n    this.config.getApprovalMode(),\n  );\n\n  // Append additional context from hook if provided\n  if (failureHookResult.additionalContext) {\n    errorMessage += `\\n\\n${failureHookResult.additionalContext}`;\n  }\n}\n```\n\n资料来源：[packages/core/src/core/coreToolScheduler.ts:263-274]()\n\n## Best Practices\n\n1. **Manifest Validation** - Always validate SKILL.md against the schema before distribution\n2. **Token Budgeting** - Monitor skill token usage to stay within context limits\n3. **Lazy Loading** - Prefer loading skills on-demand rather than at startup\n4. **Model Override** - Use sparingly and document the override behavior clearly\n5. **Error Boundaries** - Wrap skill execution in try-catch to prevent cascading failures\n\n## Summary\n\nThe Skills System provides a flexible, extensible framework for adding capabilities to the qwen-code agent. By standardizing skill definition through manifests, tracking resource consumption, and integrating with the tool execution pipeline, skills enable users to customize and expand the agent's functionality without modifying core code.\n\n---\n\n<a id='extensions'></a>\n\n## Extensions System\n\n### 相关页面\n\n相关主题：[Skills System](#skills-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/extension/extensionManager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/extension/extensionManager.ts)\n- [packages/cli/src/ui/components/extensions/steps/ExtensionListStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/extensions/steps/ExtensionListStep.tsx)\n- [packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx)\n- [packages/cli/src/commands/extensions/settings.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/commands/extensions/settings.ts)\n- [packages/core/src/tools/skill.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/skill.ts)\n- [packages/core/src/skills/bundled/qc-helper/SKILL.md](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/bundled/qc-helper/SKILL.md)\n</details>\n\n# Extensions System\n\n## Overview\n\nThe Extensions System is a modular plugin architecture that allows Qwen Code to extend its core functionality through dynamically loadable extensions. Extensions can provide MCP servers, skills, tools, commands, and configuration options that integrate seamlessly with the main application.\n\nExtensions enable third-party developers to extend Qwen Code without modifying the core codebase, while providing users with additional capabilities through a standardized interface.\n\n## Architecture\n\n### Extension Manager\n\nThe `ExtensionManager` is the central orchestrator responsible for loading, enabling, disabling, and managing all extensions. It maintains a registry of loaded extensions and handles their lifecycle events.\n\n```mermaid\ngraph TD\n    A[User Request] --> B[ExtensionManager]\n    B --> C[Find Extension by Name]\n    C --> D{Extension Found?}\n    D -->|Yes| E[Enable/Disable Extension]\n    D -->|No| F[Raise Error]\n    E --> G[Refresh Tools]\n    G --> H[Update Available Skills]\n```\n\n### Extension Lifecycle\n\nExtensions follow a defined lifecycle managed by the ExtensionManager:\n\n| State | Description |\n|-------|-------------|\n| `loaded` | Extension binary is loaded into memory |\n| `active` | Extension is enabled and functional |\n| `inactive` | Extension is disabled but remains loaded |\n\nThe manager provides methods to control this lifecycle:\n\n- `enableExtension(name, scope, cwd?)` - Activates an extension\n- `disableExtension(name, scope, cwd?)` - Deactivates an extension\n- `getLoadedExtensions()` - Returns all currently loaded extensions\n- `refreshTools()` - Updates the tool registry after extension changes\n\n资料来源：[packages/core/src/extension/extensionManager.ts:1-50]()\n\n## Extension Configuration\n\n### Settings Scopes\n\nExtensions support configuration at multiple scopes, following Qwen Code's hierarchical configuration model:\n\n| Scope | Path | Priority |\n|-------|------|----------|\n| User | `~/.qwen/settings.json` | Lower |\n| Workspace | `<project>/.qwen/settings.json` | Higher |\n\nSettings for extensions are stored with the extension ID as the namespace key, allowing multiple extensions to maintain independent configurations.\n\n资料来源：[packages/cli/src/commands/extensions/settings.ts:1-30]()\n\n### Accessing Extension Settings\n\nExtension settings can be retrieved at runtime using scoped environment contents:\n\n```typescript\nconst userSettings = await getScopedEnvContents(\n  extension.config,\n  extension.id,\n  ExtensionSettingScope.USER,\n);\nconst workspaceSettings = await getScopedEnvContents(\n  extension.config,\n  extension.id,\n  ExtensionSettingScope.WORKSPACE,\n);\nconst mergedSettings = { ...userSettings, ...workspaceSettings };\n```\n\nSettings merge with workspace settings taking precedence over user settings.\n\n资料来源：[packages/cli/src/commands/extensions/settings.ts:40-55]()\n\n## Extension Metadata\n\nEach extension carries metadata that describes its identity and capabilities:\n\n| Property | Description |\n|----------|-------------|\n| `name` | Unique identifier for the extension |\n| `version` | Semantic version string |\n| `path` | Filesystem path to the extension |\n| `isActive` | Boolean indicating current activation state |\n| `installMetadata` | Source information (e.g., marketplace) |\n| `mcpServers` | Map of MCP server configurations |\n| `commands` | List of provided commands |\n| `skills` | List of provided skills |\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-50]()\n\n## MCP Server Integration\n\nExtensions can provide MCP (Model Context Protocol) servers that expose additional tools and capabilities to the AI model:\n\n```mermaid\ngraph LR\n    A[Extension] --> B[MCP Servers Config]\n    B --> C[Server: tool1]\n    B --> D[Server: tool2]\n    C --> E[Available Tools]\n    D --> E\n```\n\nWhen an extension provides MCP servers, they are listed in the extension detail view:\n\n```typescript\n{ext.mcpServers && Object.keys(ext.mcpServers).length > 0 && (\n  <Box>\n    <Text color={theme.text.primary}>{t('MCP Servers:')}</Text>\n    <Text>{Object.keys(ext.mcpServers).join(', ')}</Text>\n  </Box>\n)}\n```\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:50-65]()\n\n## Skills and Commands\n\nExtensions can contribute skills that appear in the available skills list presented to the AI model. This integration uses XML-based skill descriptors:\n\n```xml\n<skill>\n<name>\n{skill.name}\n</name>\n<description>\n{descText}\n</description>\n<location>\n{skill.level}\n</location>\n</skill>\n```\n\nThe skill system includes security measures to prevent injection attacks. Extension skill names and descriptions are properly escaped when generating the available skills block:\n\n```typescript\n// Extension skills bypass the standard validator,\n// so they must be escaped explicitly\nallSkillEntries.push(`<skill>\n<name>\n${escapeXml(skill.name)}\n</name>\n<description>\n${descText}\n</description>\n<location>\n${skill.level}\n</location>\n</skill>`);\n```\n\n资料来源：[packages/core/src/tools/skill.ts:1-50]()\n\n### Command Sources\n\nExtension-provided commands are labeled with their source for clarity in the UI:\n\n| Source Type | Label Format | Description |\n|-------------|--------------|-------------|\n| `plugin-command` | `Extension: {name}` | Commands from extensions |\n| `skill-dir-command` | `Project` or `User` | Commands from local skill directories |\n\n资料来源：[packages/cli/src/services/SkillCommandLoader.ts:1-60]()\n\n## Extension UI Components\n\n### Extension List View\n\nThe CLI provides an interactive list view for browsing installed extensions:\n\n```typescript\n<Text color={theme.text.secondary}>\n  {t('{{count}} extensions installed', {\n    count: extensions.length.toString(),\n  })}\n</Text>\n```\n\nEach extension displays:\n- Name\n- Version\n- Active status (with color coding)\n- State indicator\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionListStep.tsx:1-50]()\n\n### Extension Detail View\n\nThe detail view shows comprehensive information about a selected extension:\n\n| Field | Display |\n|-------|---------|\n| Version | `{ext.version}` |\n| Status | Active string with color |\n| Path | Filesystem location |\n| Source | Installation source |\n| MCP Servers | Comma-separated list |\n| Commands | When available |\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-70]()\n\n## Extension Settings Commands\n\nUsers can view and configure extension settings through the CLI:\n\n### Viewing Settings\n\n```bash\n/extensions settings <name>\n```\n\nThe command displays:\n- Current setting values\n- Scope where each setting is defined (user/workspace)\n- Sensitive value indicators for secure settings\n\n```typescript\nfor (const setting of extension.settings) {\n  const value = mergedSettings[setting.envVar];\n  let displayValue: string;\n  let scopeInfo = '';\n\n  if (workspaceSettings[setting.envVar] !== undefined) {\n    scopeInfo = ' ' + t('(workspace)');\n  } else if (userSettings[setting.envVar] !== undefined) {\n    scopeInfo = ' ' + t('(user)');\n  }\n\n  if (value === undefined) {\n    displayValue = t('[not set]');\n  } else if (setting.sensitive) {\n    displayValue = t('[value stored in keychain]');\n  }\n  // ...\n}\n```\n\n资料来源：[packages/cli/src/commands/extensions/settings.ts:60-100]()\n\n### Setting Storage\n\nExtension settings support sensitive data storage via keychain integration:\n\n| Setting Type | Storage Location |\n|--------------|------------------|\n| Sensitive | System keychain |\n| Non-sensitive | JSON config files |\n\n## Extension Documentation\n\nThe bundled `qc-helper` skill provides documentation references for extension development:\n\n| Topic | Documentation Path |\n|-------|-------------------|\n| Extension introduction | `docs/extension/introduction.md` |\n| Getting started | `docs/extension/getting-started-extensions.md` |\n| Releasing extensions | `docs/extension/extension-releasing.md` |\n\n资料来源：[packages/core/src/skills/bundled/qc-helper/SKILL.md:1-100]()\n\n## Security Considerations\n\nThe extension system implements several security measures:\n\n1. **XML Escaping**: Skill names and descriptions from extensions are escaped to prevent injection attacks in the model-facing XML blocks.\n\n2. **Scope Restrictions**: System and SystemDefaults scopes are not supported for extension management to prevent privilege escalation.\n\n3. **Keychain Storage**: Sensitive extension settings are stored in the system keychain rather than plaintext config files.\n\n4. **Validation Bypass Awareness**: The codebase notes that extension skills bypass the standard validator, requiring explicit escaping in the skill generation code.\n\n资料来源：[packages/core/src/extension/extensionManager.ts:10-30]()\n\n## Extension Workflow Summary\n\n```mermaid\ngraph TD\n    A[Install Extension] --> B[Load Extension Binary]\n    B --> C[Register MCP Servers]\n    C --> D[Register Skills]\n    D --> E[Enable Extension]\n    E --> F[Refresh Tools]\n    F --> G[Available to AI Model]\n    \n    H[User Configures] --> I[Write to Scope]\n    I --> J[Merge Settings]\n    J --> K[Apply to Extension]\n    \n    L[Disable Extension] --> M[Mark Inactive]\n    M --> N[Tools Unavailable]\n```\n\n## See Also\n\n- [Getting Started with Extensions](docs/extension/getting-started-extensions.md)\n- [Extension Releasing Guide](docs/extension/extension-releasing.md)\n- [Configuration System](../configuration/settings.md)\n- [MCP Server Integration](../mcp/index.md)\n- [Skills System](../skills/index.md)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：QwenLM/qwen-code\n\n摘要：发现 8 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | host_targets=claude, claude_code, chatgpt\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 6. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n\n## 7. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | issue_or_pr_quality=unknown\n\n## 8. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | release_recency=unknown\n\n<!-- canonical_name: QwenLM/qwen-code; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "qwen-code",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "art_875e03abe4cc4cb58b4a8ef8603b8a0b",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/QwenLM/qwen-code#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "qwen-code 说明书",
      "toc": [
        "https://github.com/QwenLM/qwen-code 项目说明书",
        "目录",
        "Project Overview",
        "What is Qwen Code",
        "Architecture Overview",
        "Core Components",
        "Key Features",
        "Configuration",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "435f711e33dc7926fec2af62bbf3c2ec8a5464d2",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "Dockerfile",
      "package.json",
      "README.md",
      "docs/_meta.ts",
      "docs/index.md",
      "docs/e2e-tests/worktree.md",
      "docs/design/openrouter-auth-and-models.md",
      "docs/design/markdown-syntax-extension.md",
      "docs/design/custom-api-key-auth-wizard-prd.md",
      "docs/design/worktree.md",
      "docs/plans/2026-03-22-agent-tool-display-design.md",
      "docs/developers/qwen-serve-protocol.md",
      "docs/developers/_meta.ts",
      "docs/developers/architecture.md",
      "docs/developers/sdk-typescript.md",
      "docs/developers/contributing.md",
      "docs/developers/roadmap.md",
      "docs/developers/sdk-java.md",
      "docs/developers/sdk-python.md",
      "docs/developers/channel-plugins.md",
      "docs/users/_meta.ts",
      "docs/users/overview.md",
      "docs/users/integration-vscode.md",
      "docs/users/quickstart.md",
      "docs/users/common-workflow.md",
      "docs/users/qwen-serve.md",
      "docs/users/integration-jetbrains.md",
      "docs/users/integration-github-action.md",
      "docs/users/integration-zed.md",
      "docs/design/auto-memory/memory-system.md",
      "docs/design/customize-banner-area/customize-banner-area.zh-CN.md",
      "docs/design/customize-banner-area/customize-banner-area.md",
      "docs/design/compaction-image-stripping/compaction-image-stripping-design.md",
      "docs/design/channels/channels-design.md",
      "docs/design/fork-subagent/fork-subagent-design.md",
      "docs/design/adaptive-output-token-escalation/adaptive-output-token-escalation-design.md",
      "docs/design/prompt-suggestion/speculation-design.md",
      "docs/design/prompt-suggestion/prompt-suggestion-design.md",
      "docs/design/prompt-suggestion/prompt-suggestion-implementation.md",
      "docs/design/session-recap/session-recap-design.md"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @qwen-code/qwen-code - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @qwen-code/qwen-code 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`.qwen/skills/bugfix/SKILL.md`, `.qwen/skills/codegraph/SKILL.md`, `.qwen/skills/docs-audit-and-refresh/SKILL.md`, `.qwen/skills/docs-update-from-diff/SKILL.md` 等 Claim：`clm_0004` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`.qwen/skills/bugfix/SKILL.md`, `.qwen/skills/codegraph/SKILL.md`, `.qwen/skills/docs-audit-and-refresh/SKILL.md`, `.qwen/skills/docs-update-from-diff/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`AGENTS.md`, `README.md`, `docs/users/quickstart.md`, `packages/channels/base/README.md` 等 Claim：`clm_0002` supported 0.86\n\n## 怎么开始\n\n- `npm install -g @qwen-code/qwen-code@latest` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `npm install @qwen-code/channel-base` 证据：`packages/channels/base/README.md` Claim：`clm_0006` supported 0.86\n- `npm install @qwen-code/channel-plugin-example` 证据：`packages/channels/plugin-example/README.md` Claim：`clm_0007` supported 0.86\n- `npx qwen-channel-plugin-example-server` 证据：`packages/channels/plugin-example/README.md` Claim：`clm_0008` supported 0.86\n- `curl -sX POST http://localhost:9200/message \\` 证据：`packages/channels/plugin-example/README.md` Claim：`clm_0009` supported 0.86\n- `pip install qwen-code-sdk` 证据：`packages/sdk-python/README.md` Claim：`clm_0010` supported 0.86\n- `pip install --pre qwen-code-sdk` 证据：`packages/sdk-python/README.md` Claim：`clm_0011` supported 0.86\n- `npm install @qwen-code/sdk` 证据：`packages/sdk-typescript/README.md` Claim：`clm_0012` supported 0.86\n- `npm install -g qwen-code@^0.4.0` 证据：`packages/sdk-typescript/README.md` Claim：`clm_0013` supported 0.86\n- `npm install @qwen-code/webui` 证据：`packages/webui/README.md` Claim：`clm_0014` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`.qwen/skills/bugfix/SKILL.md`, `.qwen/skills/codegraph/SKILL.md`, `.qwen/skills/docs-audit-and-refresh/SKILL.md`, `.qwen/skills/docs-update-from-diff/SKILL.md` 等 Claim：`clm_0004` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.qwen/skills/bugfix/SKILL.md`, `.qwen/skills/codegraph/SKILL.md`, `.qwen/skills/docs-audit-and-refresh/SKILL.md`, `.qwen/skills/docs-update-from-diff/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`AGENTS.md`, `README.md`, `docs/users/quickstart.md`, `packages/channels/base/README.md` 等 Claim：`clm_0002` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0005` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`.qwen/skills/bugfix/SKILL.md`, `.qwen/skills/codegraph/SKILL.md`, `.qwen/skills/docs-audit-and-refresh/SKILL.md`, `.qwen/skills/docs-update-from-diff/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`AGENTS.md`, `README.md`, `docs/users/quickstart.md`, `packages/channels/base/README.md` 等\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`.qwen/skills/bugfix/SKILL.md`, `.qwen/skills/codegraph/SKILL.md`, `.qwen/skills/docs-audit-and-refresh/SKILL.md`, `.qwen/skills/docs-update-from-diff/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`AGENTS.md`, `README.md`, `docs/users/quickstart.md`, `packages/channels/base/README.md` 等\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`.qwen/skills/qwen-code-claw/SKILL.md`, `README.md`, `docs/users/configuration/auth.md`, `docs/users/configuration/model-providers.md` 等\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0017` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`AGENTS.md`, `README.md`, `docs/users/quickstart.md`, `packages/channels/base/README.md` 等 Claim：`clm_0018` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`.qwen/skills/bugfix/SKILL.md`, `.qwen/skills/codegraph/SKILL.md`, `.qwen/skills/docs-audit-and-refresh/SKILL.md`, `.qwen/skills/docs-update-from-diff/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`AGENTS.md`, `README.md`, `docs/users/quickstart.md`, `packages/channels/base/README.md` 等 Claim：`clm_0002` supported 0.86\n\n### 上下文规模\n\n- 文件总数：2483\n- 重要文件覆盖：40/2483\n- 证据索引条目：80\n- 角色 / Skill 条目：15\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 @qwen-code/qwen-code 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @qwen-code/qwen-code 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 @qwen-code/qwen-code 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 15 个角色 / Skill / 项目文档条目。\n\n- **bugfix**（skill）：Fix a bug from a GitHub issue, following the reproduce-first 激活提示：当用户任务与“bugfix”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/bugfix/SKILL.md`\n- **codegraph**（skill）：Analyze indexed codebases via graph database neug and vector index zvec . Covers call graphs, dependencies, dead code, hotspots, module coupling, architecture reports, semantic search, impact analysis, bug root cause from GitHub issues, class diagrams UML , and PR review risk scoring, conflict detection, auto-merge candidates, labeling . Also covers creating, inspecting, and repairing a CodeScope index. Use for: cod… 激活提示：当用户任务与“codegraph”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/codegraph/SKILL.md`\n- **docs-audit-and-refresh**（skill）：Audit the repository's docs/ content against the current codebase, 激活提示：当用户任务与“docs-audit-and-refresh”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/docs-audit-and-refresh/SKILL.md`\n- **docs-update-from-diff**（skill）：Review local code changes with git diff and update the official 激活提示：当用户任务与“docs-update-from-diff”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/docs-update-from-diff/SKILL.md`\n- **e2e-testing**（skill）：Guide for running end-to-end tests of the Qwen Code CLI, including 激活提示：当用户任务与“e2e-testing”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/e2e-testing/SKILL.md`\n- **feat-dev**（skill）：End-to-end workflow for implementing a non-trivial qwen-code 激活提示：当用户任务与“feat-dev”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/feat-dev/SKILL.md`\n- **qwen-code-claw**（skill）：Use Qwen Code as a Code Agent for code understanding, project 激活提示：当用户任务与“qwen-code-claw”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/qwen-code-claw/SKILL.md`\n- **structured-debugging**（skill）：Hypothesis-driven debugging methodology for hard bugs. Use this 激活提示：当用户任务与“structured-debugging”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/structured-debugging/SKILL.md`\n- **terminal-capture**（skill）：Automates terminal UI screenshot testing for CLI commands. Applies 激活提示：当用户任务与“terminal-capture”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/terminal-capture/SKILL.md`\n- **tmux-real-user-testing**（skill）：This skill should be used when the user asks to \"用 tmux 做真实测试\", \"保存 tmux 日志\", \"像真实用户一样测试 Qwen\", \"生成可复查的 TUI 测试报告\", \"测试 slash command 交互\", or requests a tmux-based real user E2E run with complete readable logs. It guides real TUI usage with step-by-step capture-pane snapshots rather than ANSI raw pipe logs. 激活提示：当用户任务与“tmux-real-user-testing”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.qwen/skills/tmux-real-user-testing/SKILL.md`\n- **synonyms**（skill）：Generate synonyms for words or phrases. Use this skill when the user needs alternative words with similar meanings, wants to expand vocabulary, or seeks varied expressions for writing. 激活提示：当用户任务与“synonyms”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/cli/src/commands/extensions/examples/skills/skills/synonyms/SKILL.md`\n- **batch**（skill）：Execute batch operations on multiple files in parallel. Automatically discovers files, splits into chunks, and processes with parallel worker agents. Use /batch followed by operation and file pattern. 激活提示：当用户任务与“batch”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/core/src/skills/bundled/batch/SKILL.md`\n- **loop**（skill）：Create a recurring loop that runs a prompt on a schedule. Usage - /loop 5m check the build, /loop check the PR every 30m, /loop run tests defaults to 10m . /loop list to show jobs, /loop clear to cancel all. 激活提示：当用户任务与“loop”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/core/src/skills/bundled/loop/SKILL.md`\n- **qc-helper**（skill）：Answer any question about Qwen Code usage, features, configuration, and troubleshooting by referencing the official user documentation. Also helps users view or modify their settings.json. Invoke with /qc-helper followed by a question, e.g. /qc-helper how do I configure MCP servers? or /qc-helper change approval mode to yolo . 激活提示：当用户任务与“qc-helper”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/core/src/skills/bundled/qc-helper/SKILL.md`\n- **review**（skill）：Review changed code for correctness, security, code quality, and performance. Use when the user asks to review code changes, a PR, or specific files. Invoke with /review , /review , /review , or /review --comment to post inline comments on the PR. 激活提示：当用户任务与“review”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/core/src/skills/bundled/review/SKILL.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **How to Contribute**（documentation）：We would love to accept your patches and contributions to this project. 证据：`docs/developers/contributing.md`\n- **AGENTS.md**（documentation）：This file provides guidance to Qwen Code when working with code in this repository. 证据：`AGENTS.md`\n- **🎉 News**（documentation）：! npm version https://img.shields.io/npm/v/@qwen-code/qwen-code.svg https://www.npmjs.com/package/@qwen-code/qwen-code ! License https://img.shields.io/github/license/QwenLM/qwen-code.svg ./LICENSE ! Node.js Version https://img.shields.io/badge/node-%3E%3D22.0.0-brightgreen.svg https://nodejs.org/ ! Downloads https://img.shields.io/npm/dm/@qwen-code/qwen-code.svg https://www.npmjs.com/package/@qwen-code/qwen-code 证据：`README.md`\n- **Qwen Code Docs Site**（documentation）：A documentation website for Qwen Code built with Next.js https://nextjs.org/ and Nextra https://nextra.site/ . 证据：`docs-site/README.md`\n- **Qwen Concurrent Runner**（documentation）：A Python tool for executing multiple Qwen CLI tasks across different models concurrently using isolated git worktrees. 证据：`integration-tests/concurrent-runner/README.md`\n- **@qwen-code/channel-base**（documentation）：Base infrastructure for building Qwen Code channel adapters. Provides the abstract base class, access control, session routing, and the ACP bridge that communicates with the agent. 证据：`packages/channels/base/README.md`\n- **@qwen-code/channel-plugin-example**（documentation）：A reference channel plugin for Qwen Code. It connects to a WebSocket server and routes messages through the full channel pipeline access control, session routing, agent bridge . 证据：`packages/channels/plugin-example/README.md`\n- **Message Rewrite Middleware**（documentation）：⚠️ Temporary Solution — subject to change or removal at any time. This is a stopgap implementation. We are considering a hook-based approach that would be more decoupled and extensible. Ideas and suggestions for a better design are very welcome. 证据：`packages/cli/src/acp-integration/session/rewrite/README.md`\n- **Provider Structure**（documentation）：This folder contains the different provider implementations for the Qwen Code refactor system. 证据：`packages/core/src/core/openaiContentGenerator/provider/README.md`\n- **qwen-code-sdk**（documentation）：Experimental Python SDK for programmatic access to Qwen Code through the stream-json protocol. 证据：`packages/sdk-python/README.md`\n- **@qwen-code/sdk**（documentation）：A minimum experimental TypeScript SDK for programmatic access to Qwen Code. 证据：`packages/sdk-typescript/README.md`\n- **Qwen Code Companion**（documentation）：! Version https://img.shields.io/visual-studio-marketplace/v/qwenlm.qwen-code-vscode-ide-companion https://marketplace.visualstudio.com/items?itemName=qwenlm.qwen-code-vscode-ide-companion ! VS Code Installs https://img.shields.io/visual-studio-marketplace/i/qwenlm.qwen-code-vscode-ide-companion https://marketplace.visualstudio.com/items?itemName=qwenlm.qwen-code-vscode-ide-companion ! Open VSX Downloads https://img.shields.io/open-vsx/dt/qwenlm/qwen-code-vscode-ide-companion https://open-vsx.org/extension/qwenlm/qwen-code-vscode-ide-companion ! Rating https://img.shields.io/visual-studio-marketplace/r/qwenlm.qwen-code-vscode-ide-companion https://marketplace.visualstudio.com/items?itemName… 证据：`packages/vscode-ide-companion/README.md`\n- **@qwen-code/webui**（documentation）：A shared React component library for Qwen Code applications, providing cross-platform UI components with consistent styling and behavior. 证据：`packages/webui/README.md`\n- **Examples**（documentation）：This directory contains example implementations demonstrating various ways to use the @qwen-code/webui library. 证据：`packages/webui/examples/README.md`\n- **Qwen Code Agent Server Extension for Zed**（documentation）：Qwen Code Agent Server Extension for Zed 证据：`packages/zed-extension/README.md`\n- **Package**（package_manifest）：{ \"name\": \"docs-site\", \"version\": \"1.0.0\", \"description\": \"\", \"license\": \"ISC\", \"author\": \"\", \"type\": \"module\", \"main\": \"index.js\", \"scripts\": { \"link\": \"ln -s ../docs content\", \"clean\": \"rm -rf .next\", \"dev\": \"npm run clean && next --turbopack\", \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"dependencies\": { \"next\": \"^16.0.8\", \"nextra\": \"^4.6.1\", \"nextra-theme-docs\": \"^4.6.1\", \"react\": \"^19.2.1\", \"react-dom\": \"^19.2.1\" } } 证据：`docs-site/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/qwen-code\", \"version\": \"0.15.11\", \"engines\": { \"node\": \" =22.0.0\" }, \"type\": \"module\", \"workspaces\": \"packages/ \", \"packages/channels/base\", \"packages/channels/telegram\", \"packages/channels/weixin\", \"packages/channels/dingtalk\", \"packages/channels/plugin-example\" , \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/QwenLM/qwen-code.git\" }, \"config\": { \"sandboxImageUri\": \"ghcr.io/qwenlm/qwen-code:0.15.11\" }, \"scripts\": { \"start\": \"cross-env node scripts/start.js\", \"dev\": \"node scripts/dev.js\", \"debug\": \"cross-env DEBUG=1 node --inspect-brk scripts/start.js\", \"generate\": \"node scripts/generate-git-commit-info.js\", \"generate:settings-schema\": \"node --import tsx… 证据：`package.json`\n- **How to Contribute**（documentation）：We would love to accept your patches and contributions to this project. 证据：`CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"name\": \"toy-project\", \"version\": \"1.0.0\", \"description\": \"Minimal toy project for testing\", \"scripts\": { \"build\": \"echo 'Build complete!'\" }, \"keywords\": , \"author\": \"\", \"license\": \"MIT\" } 证据：`integration-tests/concurrent-runner/examples/toy-project/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/terminal-capture\", \"version\": \"0.1.0\", \"private\": true, \"description\": \"Terminal UI screenshot automation for CLI visual testing\", \"type\": \"module\", \"scripts\": { \"capture\": \"npx tsx run.ts scenarios/\", \"capture:about\": \"npx tsx run.ts scenarios/about.ts\", \"capture:all\": \"npx tsx run.ts scenarios/all.ts\", \"capture:markdown-rendering\": \"npx tsx run.ts scenarios/markdown-rendering.ts\" }, \"dependencies\": { \"@lydell/node-pty\": \"1.2.0-beta.10\", \"@xterm/xterm\": \"^5.5.0\", \"playwright\": \"^1.50.0\", \"strip-ansi\": \"^7.1.2\" } } 证据：`integration-tests/terminal-capture/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/channel-base\", \"version\": \"0.15.11\", \"description\": \"Base channel infrastructure for Qwen Code\", \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.js\" } }, \"files\": \"dist\" , \"scripts\": { \"build\": \"tsc --build\" }, \"dependencies\": { \"@agentclientprotocol/sdk\": \"^0.14.1\" }, \"devDependencies\": { \"typescript\": \"^5.0.0\" } } 证据：`packages/channels/base/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/channel-dingtalk\", \"version\": \"0.15.11\", \"description\": \"DingTalk channel adapter for Qwen Code\", \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.js\" } }, \"files\": \"dist\" , \"scripts\": { \"build\": \"tsc --build\" }, \"dependencies\": { \"@qwen-code/channel-base\": \"file:../base\", \"dingtalk-stream-sdk-nodejs\": \"^2.0.4\" }, \"devDependencies\": { \"typescript\": \"^5.0.0\" } } 证据：`packages/channels/dingtalk/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/channel-plugin-example\", \"version\": \"0.15.11\", \"private\": true, \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.js\" } }, \"files\": \"dist\", \"src\", \"qwen-extension.json\" , \"bin\": { \"qwen-channel-plugin-example-server\": \"dist/start-server.js\" }, \"scripts\": { \"build\": \"tsc --build\", \"prepublishOnly\": \"npm run build\" }, \"dependencies\": { \"@qwen-code/channel-base\": \"file:../base\", \"ws\": \"^8.18.0\" }, \"devDependencies\": { \"@types/ws\": \"^8.5.0\" } } 证据：`packages/channels/plugin-example/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/channel-telegram\", \"version\": \"0.15.11\", \"description\": \"Telegram channel adapter for Qwen Code\", \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.js\" } }, \"files\": \"dist\" , \"scripts\": { \"build\": \"tsc --build\" }, \"dependencies\": { \"@qwen-code/channel-base\": \"file:../base\", \"grammy\": \"^1.41.1\", \"https-proxy-agent\": \"^7.0.6\", \"telegram-markdown-formatter\": \"^0.1.2\" }, \"devDependencies\": { \"typescript\": \"^5.0.0\" } } 证据：`packages/channels/telegram/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/channel-weixin\", \"version\": \"0.15.11\", \"description\": \"WeChat Weixin channel adapter for Qwen Code\", \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.js\" }, \"./accounts\": { \"types\": \"./dist/accounts.d.ts\", \"default\": \"./dist/accounts.js\" }, \"./login\": { \"types\": \"./dist/login.d.ts\", \"default\": \"./dist/login.js\" } }, \"files\": \"dist\" , \"scripts\": { \"build\": \"tsc --build\" }, \"dependencies\": { \"@qwen-code/channel-base\": \"file:../base\" }, \"devDependencies\": { \"typescript\": \"^5.0.0\" } } 证据：`packages/channels/weixin/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/qwen-code\", \"version\": \"0.15.11\", \"description\": \"Qwen Code\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/QwenLM/qwen-code.git\" }, \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"bin\": { \"qwen\": \"dist/index.js\" }, \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"import\": \"./dist/index.js\" }, \"./export\": { \"types\": \"./dist/src/export/index.d.ts\", \"import\": \"./dist/src/export/index.js\" } }, \"scripts\": { \"build\": \"node ../../scripts/build package.js\", \"start\": \"node dist/index.js\", \"debug\": \"node --inspect-brk dist/index.js\", \"lint\": \"eslint . --ext .ts,.tsx\", \"format\": \"prettier --write .\", \"test\": \"vitest run\", \"test:ci\": \"vit… 证据：`packages/cli/package.json`\n- **Package**（package_manifest）：{ \"name\": \"mcp-server-example\", \"version\": \"1.0.0\", \"description\": \"Example MCP Server for Qwen Code Extension\", \"type\": \"module\", \"main\": \"example.js\", \"scripts\": { \"build\": \"tsc\" }, \"devDependencies\": { \"typescript\": \"~5.4.5\", \"@types/node\": \"^20.11.25\" }, \"dependencies\": { \"@modelcontextprotocol/sdk\": \"^1.11.0\", \"zod\": \"^3.22.4\" } } 证据：`packages/cli/src/commands/extensions/examples/mcp-server/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/qwen-code-core\", \"version\": \"0.15.11\", \"description\": \"Qwen Code Core\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/QwenLM/qwen-code.git\" }, \"type\": \"module\", \"main\": \"dist/index.js\", \"scripts\": { \"build\": \"node ../../scripts/build package.js\", \"lint\": \"eslint . --ext .ts,.tsx\", \"format\": \"prettier --write .\", \"test\": \"vitest run\", \"test:ci\": \"vitest run\", \"typecheck\": \"tsc --noEmit\", \"postinstall\": \"node scripts/postinstall.js\" }, \"files\": \"dist\", \"vendor\", \"scripts/postinstall.js\" , \"dependencies\": { \"@anthropic-ai/sdk\": \"^0.36.1\", \"@google/genai\": \"1.30.0\", \"@iarna/toml\": \"^2.2.5\", \"@modelcontextprotocol/sdk\": \"^1.25.1\", \"@opentelemetry/api\": \"^1.9… 证据：`packages/core/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/sdk\", \"version\": \"0.1.7\", \"description\": \"TypeScript SDK for programmatic access to qwen-code CLI\", \"main\": \"./dist/index.cjs\", \"module\": \"./dist/index.mjs\", \"types\": \"./dist/index.d.ts\", \"type\": \"module\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"import\": \"./dist/index.mjs\", \"require\": \"./dist/index.cjs\" }, \"./package.json\": \"./package.json\" }, \"files\": \"dist\", \"README.md\" , \"scripts\": { \"build\": \"node scripts/build.js\", \"bundle:cli\": \"node scripts/bundle-cli.js\", \"test\": \"vitest run\", \"test:ci\": \"vitest run\", \"test:watch\": \"vitest\", \"test:coverage\": \"vitest run --coverage\", \"lint\": \"eslint src test\", \"lint:fix\": \"eslint src test --fix\", \"typecheck\": \"tsc --n… 证据：`packages/sdk-typescript/package.json`\n- **Package**（package_manifest）：{ \"name\": \"qwen-code-vscode-ide-companion\", \"displayName\": \"Qwen Code Companion\", \"description\": \"Enable Qwen Code with direct access to your VS Code workspace.\", \"version\": \"0.15.11\", \"publisher\": \"qwenlm\", \"icon\": \"assets/icon.png\", \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/QwenLM/qwen-code.git\", \"directory\": \"packages/vscode-ide-companion\" }, \"engines\": { \"vscode\": \"^1.85.0\" }, \"license\": \"LICENSE\", \"preview\": true, \"categories\": \"AI\" , \"keywords\": \"qwen-code\", \"qwen code\", \"qwen\", \"qwen code\", \"cli\", \"ide integration\", \"ide companion\" , \"activationEvents\": \"onStartupFinished\", \"onView:qwen-code.chatView.sidebar\", \"onView:qwen-code.chatView.secondary\", \"onCommand:qwen-cod… 证据：`packages/vscode-ide-companion/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/web-templates\", \"version\": \"0.15.11\", \"description\": \"Web templates bundled as embeddable JS/CSS strings\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/QwenLM/qwen-code.git\" }, \"type\": \"module\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"import\": \"./dist/index.js\" } }, \"scripts\": { \"build\": \"node build.mjs && tsc --build --clean && tsc\", \"build:templates\": \"node build.mjs\" }, \"files\": \"dist\" , \"dependencies\": {}, \"devDependencies\": { \"@types/react\": \"^18.2.0\", \"@types/react-dom\": \"^18.2.0\", \"@vitejs/plugin-react\": \"^4.2.0\", \"autoprefixer\": \"^10.4.22\", \"postcss\": \"^8.5.6\", \"tailwindcss\": \"^3.4… 证据：`packages/web-templates/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/cli-export-html\", \"private\": true, \"type\": \"module\", \"scripts\": { \"build\": \"node build.mjs\" }, \"dependencies\": { \"@qwen-code/webui\": \"latest\" }, \"devDependencies\": { \"esbuild\": \"^0.25.0\" } } 证据：`packages/web-templates/src/export-html/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/cli-insight\", \"private\": true, \"type\": \"module\", \"scripts\": { \"dev\": \"vite\", \"build\": \"node build.mjs\" } } 证据：`packages/web-templates/src/insight/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@qwen-code/webui\", \"version\": \"0.15.11\", \"description\": \"Shared UI components for Qwen Code packages\", \"type\": \"module\", \"main\": \"./dist/index.cjs\", \"module\": \"./dist/index.js\", \"types\": \"./dist/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"import\": \"./dist/index.js\", \"require\": \"./dist/index.cjs\" }, \"./icons\": { \"types\": \"./dist/components/icons/index.d.ts\", \"import\": \"./dist/components/icons/index.js\", \"require\": \"./dist/components/icons/index.cjs\" }, \"./tailwind.preset\": \"./tailwind.preset.cjs\", \"./styles.css\": \"./dist/styles.css\" }, \"files\": \"dist\", \"tailwind.preset.cjs\" , \"sideEffects\": \" / .css\" , \"publishConfig\": { \"access\": \"public\" }, \"scripts\": { \"dev\"… 证据：`packages/webui/package.json`\n- **Bugfix Workflow**（skill_instruction）：Follow this workflow for GitHub issue bugfixes. Do not skip reproduction; fixing without first reproducing the bug tends to produce incomplete fixes and regressions. 证据：`.qwen/skills/bugfix/SKILL.md`\n- **CodeScope Q&A**（skill_instruction）：CodeScope indexes source code into a two-layer knowledge graph — structure functions, calls, imports, classes, modules and evolution commits, file changes, function modifications — plus semantic embeddings for every function. Supports Python, JavaScript/TypeScript, C, and Java including Hadoop-scale repositories with 8K+ files . This combination enables analyses that grep, LSP, or pure vector search cannot do alone. It can also fetch GitHub issues and trace bugs to code , and review open PRs — scoring per-PR risk, detecting cross-PR conflicts, identifying auto-merge candidates, and applying GitHub labels. 证据：`.qwen/skills/codegraph/SKILL.md`\n- **Docs Audit And Refresh**（skill_instruction）：Audit docs/ from the repository outward: inspect the current implementation, identify documentation gaps or inaccuracies, and update the relevant pages. Keep the work inside docs/ and treat code, tests, and current configuration surfaces as the authoritative source. 证据：`.qwen/skills/docs-audit-and-refresh/SKILL.md`\n- **Docs Update From Diff**（skill_instruction）：Inspect local diffs, derive the documentation impact, and update only the repository's docs/ pages. Treat the current code as the source of truth and keep changes scoped, specific, and navigable. 证据：`.qwen/skills/docs-update-from-diff/SKILL.md`\n- **E2E Testing Guide**（skill_instruction）：How to run the Qwen Code CLI end-to-end, from building the bundle to inspecting raw API traffic. Use when unit tests are not enough and you need to verify behavior through the full pipeline model API → tool validation → tool execution . 证据：`.qwen/skills/e2e-testing/SKILL.md`\n- **Feature Development Workflow**（skill_instruction）：Use this workflow when implementing a feature in qwen-code that needs design, behavioral validation, or coordinated changes across multiple files. Each phase produces a concrete artifact. Do not combine phases; the output of each phase feeds the next. 证据：`.qwen/skills/feat-dev/SKILL.md`\n- **Qwen Code Claw**（skill_instruction）：- Understand codebases or ask questions about source code - Generate new projects or add new features - Review pull requests in the codebase - Fix bugs or refactor existing code - Execute various programming tasks such as code review, testing, documentation generation, etc. - Collaborate with other tools and agents to complete complex development tasks 证据：`.qwen/skills/qwen-code-claw/SKILL.md`\n- **Structured Debugging**（skill_instruction）：When debugging hard issues, the natural instinct is to form a theory and immediately apply a fix. This fails more often than it works. The fix addresses the wrong cause, adds complexity, creates false confidence, and obscures the real issue. Worse, after several failed attempts you lose track of what's been tried and start guessing randomly. 证据：`.qwen/skills/structured-debugging/SKILL.md`\n- **Terminal Capture — CLI Terminal Screenshot Automation**（skill_instruction）：Terminal Capture — CLI Terminal Screenshot Automation 证据：`.qwen/skills/terminal-capture/SKILL.md`\n- **tmux Real User Testing**（skill_instruction）：Run Qwen Code in a real tmux TUI session as a user would: navigate dialogs, trigger slash commands, exercise workflows, and save a readable log that maintainers can review. Prefer this workflow when the goal is not just a pass/fail assertion, but a narrative artifact showing what happened on screen. 证据：`.qwen/skills/tmux-real-user-testing/SKILL.md`\n- **Synonym Generation Guidelines**（skill_instruction）：This skill helps generate synonyms and alternative expressions for given words or phrases. It provides contextually appropriate alternatives to enhance vocabulary and improve writing variety. 证据：`packages/cli/src/commands/extensions/examples/skills/skills/synonyms/SKILL.md`\n- **/batch - Parallel Batch Operations**（skill_instruction）：You are orchestrating a batch operation across multiple files. Your job is to: 证据：`packages/core/src/skills/bundled/batch/SKILL.md`\n- **/loop — schedule a recurring prompt**（skill_instruction）：/loop — schedule a recurring prompt 证据：`packages/core/src/skills/bundled/loop/SKILL.md`\n- **Qwen Code Helper**（skill_instruction）：You are a helpful assistant for Qwen Code — an AI coding agent for the terminal. Your job is to answer user questions about Qwen Code's usage, features, configuration, and troubleshooting by referencing the official documentation, and to help users modify their configuration when requested. 证据：`packages/core/src/skills/bundled/qc-helper/SKILL.md`\n- **Code Review**（skill_instruction）：You are an expert code reviewer. Your job is to review code changes and provide actionable feedback. 证据：`packages/core/src/skills/bundled/review/SKILL.md`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`packages/vscode-ide-companion/LICENSE`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`packages/zed-extension/LICENSE`\n- **Qwen Code Documentation**（documentation）：Welcome to the Qwen Code documentation. Qwen Code is an agentic coding tool that lives in your terminal and helps you turn ideas into code faster than ever before. 证据：`docs/index.md`\n- **Adaptive Output Token Escalation Design**（documentation）：Adaptive Output Token Escalation Design 证据：`docs/design/adaptive-output-token-escalation/adaptive-output-token-escalation-design.md`\n- **Auth Provider Registry Motivation**（documentation）：The auth module used to model each setup path as a separate flow: API key, OAuth, subscription plans, and custom providers. In practice, all of these paths produce the same kind of output: updates to the user's provider configuration in ~/.qwen/settings.json . 证据：`docs/design/auth/motivation.md`\n- **Memory 记忆管理系统**（documentation）：本文介绍 Qwen Code 中 Managed Auto-Memory （托管自动记忆）的记忆管理机制、触发时机和实现细节。 证据：`docs/design/auto-memory/memory-system.md`\n- **Channels Design**（documentation）：External messaging integrations for Qwen Code — interact with an agent from Telegram, WeChat, and more. User documentation: Channels Overview ../../users/features/channels/overview.md . 证据：`docs/design/channels/channels-design.md`\n- **Compact Mode Design: Competitive Analysis & Optimization**（documentation）：Compact Mode Design: Competitive Analysis & Optimization 证据：`docs/design/compact-mode/compact-mode-design.md`\n- **Compaction Image Stripping + Token Estimation Fix**（documentation）：Compaction Image Stripping + Token Estimation Fix 证据：`docs/design/compaction-image-stripping/compaction-image-stripping-design.md`\n- **Custom API Key Auth Wizard PRD**（documentation）：Improve the /auth - API Key - Custom API Key experience by replacing the current documentation-only screen with an in-terminal setup wizard for custom API providers. 证据：`docs/design/custom-api-key-auth-wizard-prd.md`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`docs/developers/contributing.md`, `AGENTS.md`, `README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`docs/developers/contributing.md`, `AGENTS.md`, `README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Project Overview**：importance `high`\n  - source_paths: README.md, package.json, packages/cli/package.json, packages/core/package.json\n- **System Architecture**：importance `high`\n  - source_paths: docs/developers/architecture.md, packages/core/src/index.ts, packages/cli/src/index.ts, packages/channels/base/src/ChannelBase.ts\n- **Core Agent Runtime**：importance `high`\n  - source_paths: packages/core/src/agents/runtime/agent-core.ts, packages/core/src/agents/runtime/agent-context.ts, packages/core/src/agents/runtime/agent-types.ts, packages/core/src/agents/background-tasks.ts\n- **Turn Processing and LLM Communication**：importance `high`\n  - source_paths: packages/core/src/core/turn.ts, packages/core/src/core/client.ts, packages/core/src/core/contentGenerator.ts, packages/core/src/core/baseLlmClient.ts\n- **Tools System**：importance `high`\n  - source_paths: packages/core/src/tools/tools.ts, packages/core/src/tools/tool-registry.ts, packages/core/src/tools/shell.ts, packages/core/src/tools/edit.ts, packages/core/src/tools/read-file.ts\n- **Authentication and Model Providers**：importance `high`\n  - source_paths: packages/cli/src/auth/providerConfig.ts, packages/cli/src/auth/allProviders.ts, packages/cli/src/config/settingsSchema.ts, packages/core/src/core/openaiContentGenerator/provider/index.ts\n- **Memory System**：importance `medium`\n  - source_paths: packages/core/src/memory/manager.ts, packages/core/src/memory/entries.ts, packages/core/src/memory/recall.ts, packages/core/src/memory/extract.ts, packages/core/src/memory/prompt.ts\n- **Session Management**：importance `medium`\n  - source_paths: packages/core/src/services/sessionService.ts, packages/core/src/services/sessionRecap.ts, packages/core/src/services/sessionTitle.ts, packages/core/src/config/storage.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `435f711e33dc7926fec2af62bbf3c2ec8a5464d2`\n- inspected_files: `Dockerfile`, `package.json`, `README.md`, `docs/_meta.ts`, `docs/index.md`, `docs/e2e-tests/worktree.md`, `docs/design/openrouter-auth-and-models.md`, `docs/design/markdown-syntax-extension.md`, `docs/design/custom-api-key-auth-wizard-prd.md`, `docs/design/worktree.md`, `docs/plans/2026-03-22-agent-tool-display-design.md`, `docs/developers/qwen-serve-protocol.md`, `docs/developers/_meta.ts`, `docs/developers/architecture.md`, `docs/developers/sdk-typescript.md`, `docs/developers/contributing.md`, `docs/developers/roadmap.md`, `docs/developers/sdk-java.md`, `docs/developers/sdk-python.md`, `docs/developers/channel-plugins.md`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 可能修改宿主 AI 配置\n\n- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Evidence: capability.host_targets | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | host_targets=claude, claude_code, chatgpt\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 存在安全注意事项\n\n- Trigger: No sandbox install has been executed yet; downstream must verify before user use.\n- Host AI rule: 转成明确权限清单和安全审查提示。\n- Why it matters: 用户安装前需要知道权限边界和敏感操作。\n- Evidence: risks.safety_notes | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | No sandbox install has been executed yet; downstream must verify before user use.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- Evidence: evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | issue_or_pr_quality=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Evidence: evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | release_recency=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：QwenLM/qwen-code\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：claude, claude_code, chatgpt\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 可能修改宿主 AI 配置（medium）：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 能力判断依赖假设（medium）：假设不成立时，用户拿不到承诺的能力。 建议检查：将假设转成下游验证清单。\n- 维护活跃度未知（medium）：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 下游验证发现风险项（medium）：下游已经要求复核，不能在页面中弱化。 建议检查：进入安全/权限治理复核队列。\n- 存在安全注意事项（medium）：用户安装前需要知道权限边界和敏感操作。 建议检查：转成明确权限清单和安全审查提示。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/QwenLM/qwen-code 项目说明书\n\n生成时间：2026-05-16 00:58:51 UTC\n\n## 目录\n\n- [Project Overview](#project-overview)\n- [System Architecture](#architecture)\n- [Core Agent Runtime](#agent-runtime)\n- [Turn Processing and LLM Communication](#turn-processing)\n- [Tools System](#tools-system)\n- [Authentication and Model Providers](#authentication)\n- [Memory System](#memory-system)\n- [Session Management](#session-management)\n- [Skills System](#skills-system)\n- [Extensions System](#extensions)\n\n<a id='project-overview'></a>\n\n## Project Overview\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [Authentication and Model Providers](#authentication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/QwenLM/qwen-code/blob/main/README.md)\n- [packages/cli/package.json](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/package.json)\n- [packages/core/package.json](https://github.com/QwenLM/qwen-code/blob/main/packages/core/package.json)\n- [packages/webui/README.md](https://github.com/QwenLM/qwen-code/blob/main/packages/webui/README.md)\n- [packages/webui/package.json](https://github.com/QwenLM/qwen-code/blob/main/packages/webui/package.json)\n- [packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n- [packages/core/src/memory/extractionAgentPlanner.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/extractionAgentPlanner.ts)\n</details>\n\n# Project Overview\n\nQwen Code is an AI-powered coding assistant developed by the Qwen team. It provides an intelligent CLI (Command-Line Interface) tool that leverages large language models to assist developers with coding tasks, code review, refactoring, and automated programming workflows.\n\n## What is Qwen Code\n\nQwen Code is a multi-agent coding system that combines AI language model capabilities with traditional development tools. It enables developers to:\n\n- **Execute coding tasks** through natural language commands\n- **Manage complex development workflows** with multiple sub-agents\n- **Access external tools** via MCP (Model Context Protocol) servers\n- **Compare AI models** using an Arena feature for side-by-side evaluation\n\n资料来源：[README.md:1-50]()\n\n## Architecture Overview\n\nThe project follows a **monorepo structure** with three main packages:\n\n```mermaid\ngraph TD\n    subgraph \"Qwen Code Repository\"\n        CLI[\"packages/cli<br/>CLI Application\"]\n        CORE[\"packages/core<br/>Core Engine\"]\n        WEBUI[\"packages/webui<br/>Web UI Components\"]\n    end\n    \n    CLI --> CORE\n    CLI --> WEBUI\n```\n\n### Package Breakdown\n\n| Package | Purpose | Technology |\n|---------|---------|------------|\n| `packages/cli` | Command-line interface and terminal UI | TypeScript, React-like rendering (blessed) |\n| `packages/core` | Core AI logic, memory management, agent planning | TypeScript |\n| `packages/webui` | Reusable web components for React applications | React, Tailwind CSS |\n\n资料来源：[README.md:30-45]()\n资料来源：[packages/cli/package.json]()\n资料来源：[packages/core/package.json]()\n\n## Core Components\n\n### CLI Application (`packages/cli`)\n\nThe CLI package provides the terminal-based user interface for interacting with Qwen Code. It includes:\n\n- **Interactive terminal UI** built with `blessed` and `react-blessed`\n- **Arena functionality** for comparing multiple AI agents side-by-side\n- **Background task management** for long-running operations\n- **Sub-agent creation and management** system\n- **MCP server integration** for external tool access\n\n```mermaid\ngraph TD\n    UI[\"UI Layer<br/>React-Blessed Components\"]\n    CB[\"Context & State<br/>Management\"]\n    CORE[\"Core Engine<br/>packages/core\"]\n    IO[\"Non-Interactive<br/>CLI Mode\"]\n    \n    UI --> CB\n    CB --> CORE\n    IO --> CORE\n```\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx:1-50]()\n资料来源：[packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx:1-30]()\n\n### Core Engine (`packages/core`)\n\nThe core package contains the fundamental AI capabilities:\n\n- **Memory Management** - Handles persistent memory with topic-based organization\n- **Agent Planning** - Extraction and planning agents for task decomposition\n- **Managed Memory System** - Durable storage for project-specific information\n\n#### Memory System Architecture\n\n```mermaid\ngraph TD\n    Input[\"User Input / Conversation\"]\n    TopicScan[\"Topic Scanner\"]\n    MemoryBlock[\"Memory Block<br/>Builder\"]\n    PromptGen[\"Task Prompt<br/>Generator\"]\n    Output[\"AI Context\"]\n    \n    Input --> TopicScan\n    TopicScan --> MemoryBlock\n    MemoryBlock --> PromptGen\n    PromptGen --> Output\n    \n    subgraph \"Managed Memory\"\n        TopicDocs[\"Topic Documents<br/>scanAutoMemoryTopicDocuments\"]\n    end\n    TopicScan --> TopicDocs\n```\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-60]()\n资料来源：[packages/core/src/memory/prompt.ts:1-50]()\n\n### Web UI Components (`packages/webui`)\n\nThe webui package provides a React component library for building web-based interfaces:\n\n#### Available Component Categories\n\n| Category | Components |\n|----------|------------|\n| **Icons** | FileIcon, FolderIcon, CheckIcon, ErrorIcon, WarningIcon, SendIcon, etc. |\n| **Layout** | Container, Header, Footer, Sidebar, Main |\n| **Messages** | Message, MessageList, MessageInput, WaitingMessage, InterruptedMessage |\n| **UI Primitives** | Button, Input, Tooltip, Select, etc. |\n\n#### ToolCall Components\n\nSpecialized components for displaying tool interactions:\n\n```tsx\n// ToolCallCard with status indicators\n<ToolCallCard icon=\"💭\">\n  <ToolCallRow label=\"SaveMemory\">\n    <div>The user wants to refactor...</div>\n  </ToolCallRow>\n</ToolCallCard>\n```\n\n资料来源：[packages/webui/README.md:1-80]()\n资料来源：[packages/webui/src/components/toolcalls/shared/ToolCallCard.stories.tsx:1-50]()\n\n## Key Features\n\n### Arena Mode\n\nThe Arena feature enables side-by-side comparison of different AI agents:\n\n- Multiple agent selection with status indicators\n- Token and file count tracking\n- Diff visualization with additions/deletions\n- Duration and performance metrics\n\n```mermaid\ngraph LR\n    Agent1[\"Agent A<br/>qwen3.6-plus\"]\n    Agent2[\"Agent B<br///>glm-4.7\"]\n    Arena[\"Arena Dialog\"]\n    Results[\"Side-by-side<br/>Results\"]\n    \n    Agent1 --> Arena\n    Agent2 --> Arena\n    Arena --> Results\n```\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx:20-40]()\n资料来源：[packages/cli/src/ui/components/arena/ArenaStopDialog.tsx:1-30]()\n\n### Sub-agents System\n\nDevelopers can create custom sub-agents with:\n\n- Custom system prompts\n- Tool configurations\n- Model selection\n- Color coding for visual distinction\n- Project-level or user-level scope\n\n资料来源：[packages/cli/src/ui/components/subagents/create/CreationSummary.tsx:1-50]()\n资料来源：[packages/cli/src/ui/components/subagents/manage/AgentViewerStep.tsx:1-40]()\n\n### Extension System\n\nQwen Code supports extensions through:\n\n- MCP server integration\n- Version tracking\n- Status monitoring\n- Command registration\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-40]()\n\n## Configuration\n\n### Model Provider Configuration\n\nQwen Code supports multiple AI model providers configured via JSON:\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3.6-plus\",\n        \"name\": \"qwen3.6-plus (Coding Plan)\",\n        \"baseUrl\": \"https://coding.dashscope.aliyuncs.com/v1\",\n        \"envKey\": \"BAILIAN_CODING_PLAN_API_KEY\"\n      }\n    ]\n  }\n}\n```\n\n### Environment Variables\n\n| Variable | Purpose |\n|----------|---------|\n| `BAILIAN_CODING_PLAN_API_KEY` | API key for ModelStudio Coding Plan |\n| `QWEN_MODEL` | Default model selection |\n\n资料来源：[README.md:50-80]()\n\n## Project Structure\n\n```\nqwen-code/\n├── packages/\n│   ├── cli/\n│   │   ├── src/\n│   │   │   ├── ui/           # Terminal UI components\n│   │   │   │   ├── components/\n│   │   │   │   └── contexts/\n│   │   │   └── nonInteractiveCli.ts\n│   │   └── package.json\n│   ├── core/\n│   │   ├── src/\n│   │   │   └── memory/       # Memory management\n│   │   └── package.json\n│   └── webui/\n│       ├── src/\n│       │   ├── components/\n│       │   ├── context/\n│       │   └── hooks/\n│       └── package.json\n├── docs-site/               # Documentation website\n└── README.md\n```\n\n## Technology Stack\n\n| Layer | Technology |\n|-------|------------|\n| **Runtime** | Node.js |\n| **Language** | TypeScript |\n| **CLI UI** | blessed, react-blessed |\n| **Web UI** | React, Tailwind CSS, Vite |\n| **Docs** | Next.js, Nextra |\n| **Testing** | Vitest, React Testing Library |\n\n## Installation & Usage\n\n### Quick Start\n\n```bash\n# Install globally\nnpm install -g qwen-code\n\n# Configure (optional, can use defaults)\nqwen config set openai.apiKey your-key\n\n# Start Qwen Code\nqwen\n```\n\n### Development Setup\n\n```bash\n# Clone repository\ngit clone https://github.com/QwenLM/qwen-code.git\ncd qwen-code\n\n# Install dependencies\nnpm install\n\n# Start development\nnpm run dev\n```\n\n资料来源：[README.md:1-60]()\n\n## Statistics & Performance\n\nThe CLI provides detailed performance metrics including:\n\n- **Wall Time** - Total execution duration\n- **Agent Active Time** - Time spent actively processing\n- **API Time** - Time waiting for model responses\n- **Tool Time** - Time executing tools\n- **Cache Efficiency** - Token cache utilization\n\n资料来源：[packages/cli/src/ui/components/StatsDisplay.tsx:1-50]()\n\n## Summary\n\nQwen Code is a comprehensive AI coding assistant that combines:\n\n1. **CLI-first design** for terminal-based workflows\n2. **Modular architecture** with separate core, CLI, and UI packages\n3. **Multi-agent support** via Arena and sub-agent systems\n4. **Extensible tooling** through MCP integration\n5. **Web component library** for building custom interfaces\n\nThe project is well-suited for developers who prefer command-line workflows while wanting access to powerful AI-assisted coding capabilities.\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Core Agent Runtime](#agent-runtime), [Tools System](#tools-system), [Memory System](#memory-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n- [packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx)\n- [packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx)\n- [packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx)\n- [packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx)\n- [packages/cli/src/ui/components/arena/ArenaStopDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaStopDialog.tsx)\n- [packages/cli/src/ui/components/arena/ArenaCards.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaCards.tsx)\n- [packages/cli/src/ui/components/StatsDisplay.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/StatsDisplay.tsx)\n</details>\n\n# System Architecture\n\n## Overview\n\nQwen Code is a multi-package monorepo designed as an AI-powered coding assistant. The system architecture follows a modular design pattern with clear separation between core logic, CLI interface, UI components, and channel integrations.\n\n## Package Structure\n\nThe repository is organized as a monorepo under the `packages/` directory:\n\n| Package | Purpose |\n|---------|---------|\n| `cli` | Command-line interface with terminal-based UI |\n| `core` | Core functionality and business logic |\n| `webui` | Web-based user interface components |\n| `channels` | Abstraction layer for platform-specific capabilities |\n\n资料来源：[packages/webui/README.md](packages/webui/README.md)\n\n## Core Architectural Patterns\n\n### Agent Session Model\n\nThe system operates on an agent-based session model where agents perform coding tasks within isolated sessions.\n\n```mermaid\ngraph TD\n    A[User Query] --> B[Session Manager]\n    B --> C[Agent Executor]\n    C --> D[Tool Registry]\n    D --> E[File System]\n    D --> F[MCP Servers]\n    C --> G[Token Tracker]\n    G --> H[Stats Aggregator]\n```\n\nThe `BackgroundTasksDialog.tsx` component manages agent sessions with support for:\n- Session counting and tracking\n- Progress reporting\n- Topic metadata\n- Lock-release mechanisms for session management\n- Metadata write operations\n\n资料来源：[packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx](packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx)\n\n### Task and Monitor System\n\nTasks flow through the system with monitoring capabilities:\n\n```mermaid\ngraph LR\n    A[Task Created] --> B[Monitor Registry]\n    B --> C[Task Notification XML]\n    C --> D[Status: running|completed|failed|cancelled]\n```\n\nThe monitor system emits notifications via XML format:\n```xml\n<task-notification>\n  <task-id>mon_1</task-id>\n  <kind>monitor</kind>\n  <status>running</status>\n  <summary>Monitor emitted event #1.</summary>\n  <result>ready</result>\n</task-notification>\n```\n\n资料来源：[packages/cli/src/nonInteractiveCli.test.ts](packages/cli/src/nonInteractiveCli.test.ts)\n\n## CLI Architecture\n\n### UI Component Hierarchy\n\nThe CLI package (`packages/cli/src/ui/components/`) organizes UI components by functional domain:\n\n| Directory | Function |\n|-----------|----------|\n| `arena/` | Arena comparison sessions and dialogs |\n| `background-view/` | Background task management |\n| `extensions/` | Extension management steps |\n| `mcp/steps/` | MCP server and tool listing |\n| `views/` | General view components |\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n\n### Arena System\n\nThe Arena system enables comparative evaluation of multiple agents:\n\n```mermaid\ngraph TD\n    A[Arena Session] --> B[Agent Selection]\n    A --> C[Result Comparison]\n    A --> D[Diff Analysis]\n    B --> E{Stop Action}\n    E --> F[Cleanup]\n    E --> G[Preserve Artifacts]\n```\n\n**Arena Components:**\n\n1. **ArenaSelectDialog** - Agent selection interface with status indicators\n2. **ArenaStopDialog** - Session termination with cleanup/preserve options\n3. **ArenaCards** - Visual comparison of agent outputs\n\nThe `ArenaSelectDialog.tsx` displays agent status with the following metadata:\n- Status (success/error/running)\n- Duration\n- Token count\n- File count\n- Diff statistics (additions/deletions)\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n\n**Stop Actions:**\n\n| Action | Behavior |\n|--------|----------|\n| `cleanup` | Remove all worktrees and session files |\n| `preserve` | Keep worktrees and session files for later inspection |\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaStopDialog.tsx](packages/cli/src/ui/components/arena/ArenaStopDialog.tsx)\n\n### Stats and Performance Tracking\n\nThe `StatsDisplay.tsx` component aggregates performance metrics:\n\n| Metric Category | Tracked Data |\n|-----------------|--------------|\n| **Performance** | Wall time, agent active time, API time, tool time |\n| **Tokens** | Total cached tokens, cache efficiency |\n| **Models** | Per-model usage statistics |\n\nThe system calculates percentages for API and tool time relative to total execution time.\n\n资料来源：[packages/cli/src/ui/components/StatsDisplay.tsx](packages/cli/src/ui/components/StatsDisplay.tsx)\n\n## MCP (Model Context Protocol) Integration\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[CLI] --> B[MCP Registry]\n    B --> C[Server List]\n    B --> D[Tool List]\n    C --> E[ServerListStep]\n    D --> F[ToolListStep]\n    E --> G[Status: connected/disconnected]\n    F --> H[Validation]\n```\n\n### Server Management\n\nThe `ServerListStep.tsx` component displays MCP server status:\n\n```typescript\ninterface MCPServer {\n  status: 'connected' | 'disconnected';\n  isDisabled?: boolean;\n}\n```\n\nDisconnected servers display a debug hint:\n> \"Run qwen --debug to see error logs\"\n\n资料来源：[packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx](packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx)\n\n### Tool Listing\n\nThe `ToolListStep.tsx` provides:\n- Scrollable tool list with fixed-width name column\n- Validation status indicators\n- Tool annotations display\n- Pagination for large tool sets (VISIBLE_TOOLS_COUNT)\n\nTool validation feedback:\n```typescript\ninterface Tool {\n  name: string;\n  isValid: boolean;\n  invalidReason?: string;\n}\n```\n\n资料来源：[packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx](packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx)\n\n## Extension System\n\n### Extension Metadata\n\nThe `ExtensionDetailStep.tsx` displays extension information:\n\n| Field | Description |\n|-------|-------------|\n| `name` | Extension name |\n| `version` | Semantic version |\n| `status` | Active/inactive state |\n| `path` | Installation path |\n| `source` | Install metadata source |\n| `mcpServers` | Associated MCP server list |\n| `commands` | Available CLI commands |\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx](packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx)\n\n## Platform Abstraction\n\nThe webui package provides a `PlatformProvider` context for platform-specific capabilities:\n\n```tsx\nimport { PlatformProvider, usePlatform } from '@qwen-code/webui/context';\n```\n\nThis abstraction allows the same codebase to run in different environments while exposing platform-specific APIs through a unified interface.\n\n资料来源：[packages/webui/README.md](packages/webui/README.md)\n\n## WebUI Components\n\n### Layout Components\n- `Container` - Main layout wrapper\n- `Header` - Application header\n- `Footer` - Application footer\n- `Sidebar` - Side navigation\n- `Main` - Main content area\n\n### Message Components\n- `Message` - Chat message display\n- `MessageList` - List of messages\n- `MessageInput` - Message input field\n- `WaitingMessage` - Loading/waiting state\n- `InterruptedMessage` - Interrupted state display\n\n### UI Primitives\n- **Buttons**: `size`, `error`, `errorMessage`, `label`, `helperText`, `leftElement`, `rightElement`\n- **Tooltip**: Content wrapper for hover hints\n- **Icons**: File, Folder, Check, Error, Warning, Loading, Navigation, Edit, and Special icons\n\n资料来源：[packages/webui/README.md](packages/webui/README.md)\n\n## Key Command Processing\n\nThe `atCommandProcessor` handles special commands prefixed with `@`:\n\n```mermaid\ngraph TD\n    A[User Query] --> B{Contains @?}\n    B -->|No| C[Pass Through]\n    B -->|Yes| D[At Command Parser]\n    D --> E[Command Registry]\n    E --> F[Processed Query]\n```\n\nConfiguration options:\n- `getTruncateToolOutputThreshold` (default: 2500)\n- `getTruncateToolOutputLines` (default: 500)\n- `getUsageStatisticsEnabled`\n- `getFileExclusions` with ignore patterns\n\n资料来源：[packages/cli/src/ui/hooks/atCommandProcessor.test.ts](packages/cli/src/ui/hooks/atCommandProcessor.test.ts)\n\n## Keyboard Navigation\n\nThe `keyMatchers.ts` defines command-to-key bindings:\n\n| Command | Key Binding |\n|---------|-------------|\n| `KILL_LINE_RIGHT` | `Ctrl+k` |\n| `KILL_LINE_LEFT` | `Ctrl+u` |\n| `CLEAR_INPUT` | `Ctrl+c` |\n| `DELETE_WORD_BACKWARD` | `Ctrl+Backspace` or `Meta+Backspace` |\n| `CLEAR_SCREEN` | `Ctrl+l` |\n| `HISTORY_UP/DOWN` | `Ctrl+p` / `Ctrl+n` |\n| `NAVIGATION_UP/DOWN` | Arrow keys |\n| `COMPLETION_UP/DOWN` | Arrow keys only |\n| `ACCEPT_SUGGESTION` | `Tab` or `Enter` |\n| `ESCAPE` | `Escape` |\n\nNote: Completion navigation uses only arrow keys to preserve `Ctrl+P/N` for history navigation.\n\n资料来源：[packages/cli/src/ui/keyMatchers.test.ts](packages/cli/src/ui/keyMatchers.test.ts)\n\n## Error Handling Architecture\n\n### Status Types\n\n| Status | Color | Usage |\n|--------|-------|-------|\n| `success` | Green | Completed tasks |\n| `error` | Red | Failed operations |\n| `warning` | Yellow | Lock-release and metadata write warnings |\n| `running` | Accent | Active sessions |\n\n### Lock-Release Warnings\n\nWhen lock-release errors occur, the system displays:\n> \"Subsequent dreams may be skipped as locked until the next session's staleness sweep cleans the file.\"\n\n### Metadata Write Warnings\n\nFor metadata write failures:\n> \"The scheduler gate did not see this dream's timestamp; the next dream cycle may re-fire sooner than usual.\"\n\n资料来源：[packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx](packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx)\n\n## Token Efficiency Tracking\n\nThe `ArenaCards.tsx` component tracks token efficiency per agent:\n\n```typescript\ninterface AgentMetrics {\n  label: string;\n  totalTokens: number;\n  durationMs: number;\n  toolCalls: number;\n  diffStats: {\n    additions: number;\n    deletions: number;\n  };\n}\n```\n\nMetrics display with tree-style formatting for easy comparison.\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaCards.tsx](packages/cli/src/ui/components/arena/ArenaCards.tsx)\n\n---\n\n<a id='agent-runtime'></a>\n\n## Core Agent Runtime\n\n### 相关页面\n\n相关主题：[Turn Processing and LLM Communication](#turn-processing), [Tools System](#tools-system), [Session Management](#session-management)\n\n# Core Agent Runtime\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/subagents/subagent-manager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/subagents/subagent-manager.ts)\n- [packages/core/src/core/coreToolScheduler.test.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/coreToolScheduler.test.ts)\n- [packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx)\n- [packages/cli/src/ui/components/StatsDisplay.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/StatsDisplay.tsx)\n- [packages/cli/src/ui/components/messages/ToolGroupMessage.test.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/messages/ToolGroupMessage.test.tsx)\n</details>\n\n## Overview\n\nThe Core Agent Runtime system in qwen-code provides the foundational infrastructure for executing AI agent tasks, managing subagents, handling tool scheduling, and coordinating background operations. This runtime architecture enables the CLI to execute complex multi-step coding tasks with support for tool calls, model routing, and persistent state management.\n\n## Architecture Components\n\n### Subagent Manager\n\nThe `SubagentManager` is the central coordinator for agent-level operations, handling registration, discovery, and lifecycle management of subagents across different storage levels.\n\n```mermaid\ngraph TD\n    A[SubagentManager] --> B[BuiltinAgentRegistry]\n    A --> C[Project Level Agents]\n    A --> D[User Level Agents]\n    A --> E[Extension Agents]\n    C --> F[~/.qwen/agents/]\n    D --> G[~/.qwen/agents/]\n```\n\n**Key Responsibilities:**\n\n| Function | Description |\n|----------|-------------|\n| `getSubagentConfig()` | Retrieves subagent configuration by name and level |\n| `listSubagentsAtLevel()` | Lists all subagents at a specific storage level |\n| `getSubagentPath()` | Resolves the file path for a subagent configuration |\n| `loadAllSubagents()` | Loads all available subagents across all levels |\n\n**Storage Levels:**\n\nThe system supports four distinct subagent levels:\n\n| Level | Path | Description |\n|-------|------|-------------|\n| `builtin` | Built-in registry | Agents bundled with the application |\n| `project` | `<project>/.qwen/agents/` | Project-scoped agents |\n| `session` | In-memory only | Session-specific agents |\n| `extension` | Extension-provided | Agents from loaded extensions |\n\n资料来源：[packages/core/src/subagents/subagent-manager.ts:1-100]()\n\n### Agent Resolution Logic\n\nThe subagent path resolution follows a hierarchical pattern:\n\n```typescript\ngetSubagentPath(name: string, level: SubagentLevel): string {\n  if (level === 'builtin') return `<builtin:${name}>`;\n  if (level === 'session') return `<session:${name}>`;\n  \n  const baseDir = level === 'project'\n    ? path.join(this.config.getProjectRoot(), QWEN_DIR, AGENT_CONFIG_DIR)\n    : path.join(Storage.getGlobalQwenDir(), AGENT_CONFIG_DIR);\n    \n  return path.join(baseDir, `${name}.md`);\n}\n```\n\n资料来源：[packages/core/src/subagents/subagent-manager.ts:40-52]()\n\n### Project vs Home Directory Handling\n\nA critical safety check prevents conflicts when the project root equals the home directory:\n\n```typescript\nconst homeDir = os.homedir();\nconst isHomeDirectory = path.resolve(projectRoot) === path.resolve(homeDir);\n\nif (level === 'project' && isHomeDirectory) {\n  return [];\n}\n```\n\n资料来源：[packages/core/src/subagents/subagent-manager.ts:77-82]()\n\n## Agent Result Display\n\nAgent execution results are represented through the `AgentResultDisplay` interface, supporting various execution states and task types:\n\n### Result Types\n\n| Type | Description |\n|------|-------------|\n| `task_execution` | Subagent task execution result |\n| `tool_execution` | Individual tool call result |\n\n### Execution Status States\n\n| Status | Description |\n|--------|-------------|\n| `running` | Agent is actively executing |\n| `completed` | Agent completed successfully |\n| `failed` | Agent encountered an error |\n| `cancelled` | Agent was cancelled |\n\n### Agent Result Structure\n\n```typescript\ninterface AgentResultDisplay {\n  type: 'task_execution';\n  subagentName: string;\n  taskDescription: string;\n  taskPrompt: string;\n  status: 'running' | 'completed' | 'failed' | 'cancelled';\n  toolCalls: ToolCall[];\n}\n```\n\n资料来源：[packages/cli/src/ui/components/messages/ToolGroupMessage.test.tsx:10-35]()\n\n## Tool Call Integration\n\n### Tool Call Status\n\nTool calls within agent execution follow a status model:\n\n| Status | Description |\n|--------|-------------|\n| `Executing` | Tool is currently running |\n| `success` | Tool completed successfully |\n| `error` | Tool failed with an error |\n\n### Tool Call Display\n\n```typescript\nconst createToolCall = ({\n  callId: string,\n  name: string,\n  status: ToolCallStatus,\n  resultDisplay?: AgentResultDisplay,\n}) => ({\n  callId,\n  name,\n  status,\n  description: '...',\n  resultDisplay,\n});\n```\n\n## Performance Metrics\n\nThe runtime tracks comprehensive performance metrics for agent execution:\n\n### Computed Statistics\n\n| Metric | Description |\n|--------|-------------|\n| `agentActiveTime` | Total time agent was actively processing |\n| `totalApiTime` | Time spent in API calls |\n| `totalToolTime` | Time spent executing tools |\n| `apiTimePercent` | Percentage of time in API calls |\n| `toolTimePercent` | Percentage of time in tool execution |\n| `totalCachedTokens` | Token usage from cache |\n| `cacheEfficiency` | Cache hit ratio |\n\n### Stats Display Component\n\nThe `StatsDisplay` component renders performance metrics with theme-aware coloring:\n\n- **Wall Time**: Total elapsed time\n- **Agent Active**: Time agent was processing\n- **API Time**: Model interaction time with percentage\n- **Tool Time**: Tool execution time with percentage\n- **Token Usage**: Lines added/removed, token counts\n\n资料来源：[packages/cli/src/ui/components/StatsDisplay.tsx:1-80]()\n\n## Arena Selection System\n\nThe arena system enables comparison of multiple agent implementations:\n\n### Agent Selection Dialog\n\nThe `ArenaSelectDialog` provides an interactive selection interface with keyboard navigation:\n\n| Key | Action |\n|-----|--------|\n| `Escape` | Close arena dialog |\n| `P` | Toggle preview |\n| `D` | Toggle detailed diff view |\n\n### Agent Display Metrics\n\nEach agent candidate displays:\n\n- Status (with color coding)\n- Duration\n- Token count\n- File count (if applicable)\n- Diff additions/deletions\n\n```typescript\nconst getAgentDisplay = (agent) => ({\n  key: agent.agentId,\n  value: agent.agentId,\n  title: agent.name,\n  description: `${statusInfo.text} · ${duration} · ${tokens} tokens`,\n  disabled: !isSuccessStatus(agent.status),\n});\n```\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx:1-60]()\n\n## Configuration Integration\n\nThe agent runtime integrates with the configuration system through the `Config` interface:\n\n### Required Configuration Methods\n\n| Method | Purpose |\n|--------|---------|\n| `getSessionId()` | Session identifier for state management |\n| `getUsageStatisticsEnabled()` | Enable/disable stats collection |\n| `getDebugMode()` | Enable verbose debugging |\n| `getToolRegistry()` | Access tool registry |\n| `getApprovalMode()` | Tool execution approval level |\n| `getTruncateToolOutputThreshold()` | Output truncation limit |\n| `getTruncateToolOutputLines()` | Line count truncation limit |\n\n### Default Test Configuration\n\n```typescript\nconst mockConfig = {\n  getSessionId: () => 'test-session-id',\n  getUsageStatisticsEnabled: () => true,\n  getDebugMode: () => false,\n  getApprovalMode: () => ApprovalMode.YOLO,\n  getToolRegistry: () => mockToolRegistry,\n  getTruncateToolOutputThreshold: () => 100,\n  getTruncateToolOutputLines: () => 10,\n};\n```\n\n资料来源：[packages/core/src/core/coreToolScheduler.test.ts:1-80]()\n\n## Extension Agent Integration\n\nAgents can also be provided by extensions through the extension registry:\n\n```typescript\nif (level === 'extension') {\n  const extensions = this.config.getActiveExtensions();\n  return extensions.flatMap((extension) => extension.agents || []);\n}\n```\n\nExtensions contribute agents via their `agents` property, which are merged with built-in and file-based agents.\n\n## Summary\n\nThe Core Agent Runtime provides a layered architecture for agent execution:\n\n1. **SubagentManager** - Coordinates agent discovery and lifecycle across storage levels\n2. **ToolRegistry** - Manages available tools and their execution\n3. **Config System** - Provides runtime configuration and state\n4. **Extension System** - Allows external contributions of agents\n5. **UI Components** - Renders agent status, results, and performance metrics\n\nThis architecture enables flexible agent composition while maintaining clear separation of concerns between agent definition, execution, and presentation layers.\n\n---\n\n<a id='turn-processing'></a>\n\n## Turn Processing and LLM Communication\n\n### 相关页面\n\n相关主题：[Core Agent Runtime](#agent-runtime), [Authentication and Model Providers](#authentication), [Tools System](#tools-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/core/turn.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/turn.ts)\n- [packages/core/src/core/client.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/client.ts)\n- [packages/core/src/core/contentGenerator.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/contentGenerator.ts)\n- [packages/core/src/core/baseLlmClient.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/baseLlmClient.ts)\n- [packages/core/src/core/coreToolScheduler.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/coreToolScheduler.ts)\n- [packages/core/src/telemetry/metrics.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/telemetry/metrics.ts)\n</details>\n\n# Turn Processing and LLM Communication\n\n## Overview\n\nTurn Processing and LLM Communication is the core message flow system that orchestrates the interaction between the Qwen Code CLI and Large Language Models. This system manages the complete lifecycle of a user interaction \"turn\" — from query processing through tool execution to final response delivery.\n\n## Architecture Components\n\nThe turn processing system consists of several interconnected components:\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| Turn Manager | `turn.ts` | Orchestrates turn lifecycle and state management |\n| Client | `client.ts` | Handles session management and configuration |\n| Content Generator | `contentGenerator.ts` | Generates prompts and processes responses |\n| Base LLM Client | `baseLlmClient.ts` | Abstract base for LLM API communication |\n| Tool Scheduler | `coreToolScheduler.ts` | Manages tool execution during turns |\n\n## Turn State Machine\n\nA turn progresses through distinct states during its lifecycle. The system tracks both the overall turn state and individual tool call states.\n\n```mermaid\ngraph TD\n    A[Turn Started] --> B[User Query Received]\n    B --> C[Content Generation]\n    C --> D{Awaiting Tool Calls?}\n    D -->|Yes| E[Tool Call Scheduled]\n    E --> F[Tool Execution]\n    F --> G[Tool Success?]\n    G -->|Yes| C\n    G -->|No| H[Tool Failure]\n    H --> I[Error Response]\n    D -->|No| J[Final Response]\n    I --> J\n    J --> K[Turn Complete]\n```\n\n## Message Flow\n\n### Input Processing\n\nWhen a user submits a query, the system processes it through several stages:\n\n1. **Query Reception** — The CLI receives the user's input\n2. **At-Command Processing** — Any `@` commands referencing subagents are parsed\n3. **Context Enrichment** — Project context and memory are retrieved\n4. **Prompt Construction** — System prompts and context are assembled\n\n### LLM Communication\n\nThe communication with the LLM API follows a structured pattern:\n\n```mermaid\ngraph LR\n    A[User Query] --> B[Content Generator]\n    B --> C[Base LLM Client]\n    C --> D[API Request]\n    D --> E[Streaming Response]\n    E --> F[Response Parser]\n    F --> G[Tool Call Detection]\n    G --> H[Tool Execution]\n    H --> B\n    F --> I[Final Response]\n```\n\n### Tool Call Lifecycle\n\nTool calls are processed through the Core Tool Scheduler. Each tool call transitions through these states:\n\n| State | Description |\n|-------|-------------|\n| `pending` | Tool call queued for execution |\n| `executing` | Tool currently running |\n| `success` | Tool completed successfully |\n| `failure` | Tool encountered an error |\n| `interrupted` | Tool execution was cancelled |\n\nThe scheduler handles both native tools and MCP (Model Context Protocol) tools through a unified interface.\n\n## Response Handling\n\n### Streaming Architecture\n\nThe system supports real-time streaming responses with several message types:\n\n- **Stream chunks** — Partial response text\n- **Thinking segments** — Model reasoning (when enabled)\n- **Tool call updates** — Progress on executing tools\n- **Waiting indicators** — User feedback during processing\n\n### Result Display\n\nTool execution results are formatted into display objects that include:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `type` | string | Result category (task_execution, error, etc.) |\n| `status` | string | Execution status |\n| `toolCalls` | array | Individual tool call results |\n| `subagentName` | string | Name of subagent (if applicable) |\n\n## Configuration\n\n### Model Configuration\n\nThe system supports multiple model providers with configurable parameters:\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3.6-plus\",\n        \"name\": \"qwen3.6-plus (Coding Plan)\",\n        \"baseUrl\": \"https://coding.dashscope.aliyuncs.com/v1\",\n        \"envKey\": \"BAILIAN_CODING_PODING_PLAN_API_KEY\"\n      }\n    ]\n  }\n}\n```\n\n### Generation Config\n\nResponse generation can be customized per request:\n\n| Parameter | Description |\n|-----------|-------------|\n| `temperature` | Sampling temperature |\n| `maxTokens` | Maximum response length |\n| `thinkingConfig.includeThoughts` | Enable model thinking |\n| `abortSignal` | Cancellation token |\n\n## Telemetry and Metrics\n\nThe turn processing system records comprehensive metrics:\n\n| Metric | Description | Tags |\n|--------|-------------|------|\n| `TOOL_CALL_COUNT` | Tool invocations | function_name, success, decision |\n| `API_REQUEST_COUNT` | LLM API calls | model, status_code |\n| `TOKEN_USAGE` | Token consumption | model, type (input/output/thought) |\n\nThese metrics enable monitoring of system performance and usage patterns.\n\n## Error Handling\n\n### Tool Execution Failures\n\nWhen a tool fails, the scheduler:\n\n1. Records the error with type classification\n2. Fires post-tool-use failure hooks\n3. Optionally appends additional context from hooks\n4. Returns formatted error response to the LLM\n\n### Graceful Degradation\n\nThe system handles various error scenarios:\n\n- **Config errors** — Individual config methods may throw; caught internally\n- **Network failures** — Retry logic with timeout handling\n- **Tool unavailability** — Tools excluded from execution but handled gracefully\n\n## Subagent Integration\n\nSubagents can be invoked during turn processing. The system supports:\n\n- **Focused execution** — Running subagent keeps focus for Ctrl+E expansion\n- **Task tracking** — Subagent tasks displayed with status indicators\n- **Nested execution** — Subagents can call other tools recursively\n\n## Data Flow Diagram\n\n```mermaid\ngraph TD\n    subgraph Input\n        A[User Input] --> B[At-Command Processor]\n        B --> C[Query Parser]\n    end\n    \n    subgraph Context\n        C --> D[Memory System]\n        C --> E[Project Context]\n        C --> F[Subagent Registry]\n    end\n    \n    subgraph LLM\n        D --> G[Content Generator]\n        E --> G\n        F --> G\n        G --> H[Base LLM Client]\n        H --> I[Model API]\n    end\n    \n    subgraph Execution\n        I --> J[Response Parser]\n        J --> K{Tool Calls?}\n        K -->|Yes| L[Core Tool Scheduler]\n        L --> M[Tool Registry]\n        M --> L\n        L --> N[Result Formatter]\n        N --> G\n        K -->|No| O[Final Response]\n    end\n```\n\n## Key Source Files\n\nThe following files implement the turn processing and LLM communication system:\n\n| File | Purpose |\n|------|---------|\n| `packages/core/src/core/turn.ts` | Core turn state management |\n| `packages/core/src/core/client.ts` | Client session handling |\n| `packages/core/src/core/contentGenerator.ts` | Prompt and response handling |\n| `packages/core/src/core/baseLlmClient.ts` | Abstract LLM communication |\n| `packages/core/src/core/coreToolScheduler.ts` | Tool execution orchestration |\n| `packages/core/src/telemetry/metrics.ts` | Usage telemetry |\n\n## Summary\n\nThe Turn Processing and LLM Communication system provides the foundation for Qwen Code's interaction with language models. It coordinates query processing, manages tool execution through the scheduler, handles streaming responses, and maintains comprehensive telemetry. The modular architecture allows flexible configuration of model providers while maintaining consistent behavior across different LLM backends.\n\n---\n\n<a id='tools-system'></a>\n\n## Tools System\n\n### 相关页面\n\n相关主题：[Core Agent Runtime](#agent-runtime), [Turn Processing and LLM Communication](#turn-processing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/tools/tools.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/tools.ts)\n- [packages/core/src/tools/tool-registry.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/tool-registry.ts)\n- [packages/core/src/tools/shell.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/shell.ts)\n- [packages/core/src/tools/edit.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/edit.ts)\n- [packages/core/src/tools/read-file.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/read-file.ts)\n- [packages/core/src/tools/write-file.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/write-file.ts)\n- [packages/core/src/tools/mcp-client.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/mcp-client.ts)\n- [packages/core/src/tools/lsp.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/lsp.ts)\n</details>\n\n# Tools System\n\n## Overview\n\nThe Tools System is a core architectural component of Qwen Code that enables the AI assistant to interact with the user's development environment. It provides a unified interface for executing code-related operations such as reading files, writing files, executing shell commands, editing code, and integrating with external services via the Model Context Protocol (MCP).\n\nTools extend the LLM's capabilities beyond text generation by allowing it to perform actions in the real world. When the model decides to use a tool, it generates a tool call that the system executes, returning results back to the model for further processing.\n\n## Architecture\n\nThe Tools System follows a plugin-based architecture with three main layers:\n\n```mermaid\ngraph TD\n    subgraph \"Presentation Layer\"\n        UI[UI Components]\n        TL[ToolListStep]\n        MS[McpStatus]\n    end\n    \n    subgraph \"Core Layer\"\n        TR[ToolRegistry]\n        TS[ToolScheduler]\n        TE[ToolExecutor]\n    end\n    \n    subgraph \"Integration Layer\"\n        MCP[MCP Client]\n        LSP[LSP Client]\n        SH[Shell Tools]\n        FS[File System Tools]\n    end\n    \n    UI --> TR\n    TL --> TR\n    MS --> TR\n    TR --> TS\n    TR --> TE\n    TE --> MCP\n    TE --> LSP\n    TE --> SH\n    TE --> FS\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| ToolRegistry | `tool-registry.ts` | Central registry for all available tools |\n| ToolScheduler | `coreToolScheduler.test.ts` | Schedules and manages tool execution |\n| BaseTool | `tools.ts` | Abstract base class for all tools |\n| MCPToolClient | `mcp-client.ts` | Handles MCP server communication |\n| LSPClient | `lsp.ts` | Language Server Protocol integration |\n\n## Built-in Tools\n\nQwen Code includes several built-in tools that provide fundamental file system and execution capabilities.\n\n### File Operations\n\n#### ReadFileTool\n\nReads the contents of files from the file system.\n\n```typescript\n// From packages/core/src/tools/read-file.ts\nclass ReadFileTool extends BaseTool {\n  readonly name = 'Bash';\n  readonly description = '...';\n}\n```\n\n#### WriteFileTool\n\nCreates or overwrites files with specified content.\n\n```typescript\n// From packages/core/src/tools/write-file.ts\nclass WriteFileTool extends BaseTool {\n  readonly name = 'Write';\n  readonly description = '...';\n}\n```\n\n#### EditTool\n\nModifies existing files by applying targeted changes, supporting search-and-replace operations.\n\n```typescript\n// From packages/core/src/tools/edit.ts\nclass EditTool extends BaseTool {\n  readonly name = 'Edit';\n  readonly description = '...';\n}\n```\n\n### Shell Execution\n\n#### ShellTool\n\nExecutes bash commands in the user's terminal environment.\n\n```typescript\n// From packages/core/src/tools/shell.ts\nclass ShellTool extends BaseTool {\n  readonly name = 'Bash';\n  readonly description = 'Executes bash commands in the user\\'s terminal';\n}\n```\n\nThe shell execution configuration includes terminal dimensions for proper output formatting:\n\n```typescript\ngetShellExecutionConfig: () => ({\n  terminalWidth: 90,\n  terminalHeight: 30,\n}),\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:45-47]()*\n\n## Tool Registry\n\nThe ToolRegistry serves as the central knowledge base for all available tools in the system.\n\n### Registry Interface\n\n```typescript\ninterface ToolRegistry {\n  getToolByName(name: string): Tool | undefined;\n  getToolByDisplayName(displayName: string): Tool | undefined;\n  getTools(): Tool[];\n  getAllTools(): Tool[];\n  getAllToolNames(): string[];\n  getToolsByServer(serverName: string): Tool[];\n  discoverTools(): Promise<void>;\n  registerTool(tool: Tool): void;\n}\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:18-27]()*\n\n### Registry Operations\n\nTools can be retrieved by various identifiers:\n\n```typescript\ngetToolByName: (name: string) =>\n  name === StrictStringTool.Name\n    ? toolA\n    : name === StrictToolAlt.Name\n      ? toolB\n      : undefined,\ngetToolByDisplayName: () => undefined,\ngetAllToolNames: () => [StrictStringTool.Name, StrictToolAlt.Name],\ngetToolsByServer: () => [],\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:28-35]()*\n\n## MCP Integration\n\nThe Model Context Protocol (MCP) allows Qwen Code to connect with external tools and services.\n\n### MCP Client Architecture\n\n```mermaid\ngraph LR\n    LLM[LLM] -->|Tool Call| QC[Qwen Code]\n    QC -->|MCP Request| MS[MCP Server]\n    MS -->|Response| QC\n    QC -->|Result| LLM\n    \n    subgraph \"MCP Servers\"\n        FS[File System]\n        DB[Database]\n        API[External APIs]\n    end\n    \n    MS --> FS\n    MS --> DB\n    MS --> API\n```\n\n### MCP Tool Display\n\nMCP tools are displayed in the UI with their server information and validation status:\n\n```tsx\n// From packages/cli/src/ui/components/views/McpStatus.tsx\n{tools.map((tool) => {\n  const schemaContent =\n    showSchema &&\n    tool.schema &&\n    (tool.schema.parametersJsonSchema || tool.schema.parameters)\n      ? JSON.stringify(tool.schema.parametersJsonSchema ?? tool.schema.parameters, null, 2)\n      : null;\n  \n  return (\n    <Box key={tool.name} flexDirection=\"column\">\n      <Text>- <Text color={theme.text.primary}>{tool.name}</Text></Text>\n      {showDescriptions && tool.description && (\n        <Box marginLeft={2}>\n          <Text color={theme.text.secondary}>{tool.description.trim()}</Text>\n        </Box>\n      )}\n    </Box>\n  );\n})}\n```\n*资料来源：[packages/cli/src/ui/components/views/McpStatus.tsx:1-20]()*\n\n### MCP Servers Configuration\n\nMCP servers can expose multiple components:\n\n| Component | Description |\n|-----------|-------------|\n| Tools | Executable operations exposed by the server |\n| Resources | Data sources that can be read |\n| Prompts | Predefined prompt templates |\n| MCP Servers | Named server connections |\n\n```tsx\n// Displaying MCP servers in UI\n{ext.mcpServers && Object.keys(ext.mcpServers).length > 0 && (\n  <Box>\n    <Box width={LABEL_WIDTH} flexShrink={0}>\n      <Text color={theme.text.primary}>{t('MCP Servers:')}</Text>\n    </Box>\n    <Text>{Object.keys(ext.mcpServers).join(', ')}</Text>\n  </Box>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-15]()*\n\n## LSP Integration\n\nThe Language Server Protocol (LSP) integration provides advanced code intelligence features including:\n\n- Symbol navigation\n- Hover information\n- Go-to-definition\n- Code completion\n- Diagnostics\n\n```typescript\n// From packages/core/src/tools/lsp.ts\nclass LSPTool extends BaseTool {\n  readonly name = 'LSP';\n  readonly description = 'Language Server Protocol integration';\n}\n```\n\n## Tool Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant LLM as LLM Model\n    participant TS as Tool Scheduler\n    participant TR as Tool Registry\n    participant EX as Tool Executor\n    participant TOOL as Specific Tool\n    \n    LLM->>TS: Request tool execution\n    TS->>TR: Lookup tool by name\n    TR-->>TS: Return tool instance\n    TS->>EX: Execute tool with parameters\n    EX->>TOOL: Call tool.run()\n    TOOL-->>EX: Return result\n    EX-->>TS: Return execution result\n    TS-->>LLM: Return result to model\n```\n\n### Execution Configuration\n\nThe tool execution system supports various configuration options:\n\n```typescript\nconst mockConfig = {\n  getTruncateToolOutputThreshold: () => 100,\n  getTruncateToolOutputLines: () => 10,\n  getToolRegistry: () => mockToolRegistry,\n  getUseModelRouter: () => false,\n  getGeminiClient: () => null,\n  isInteractive: () => true,\n};\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:40-48]()*\n\n## UI Components\n\n### Tool List Display\n\nThe ToolListStep component provides an interactive list of available tools:\n\n```tsx\n// From packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx\n<Box width={toolNameWidth}>\n  <Text\n    color={isSelected ? theme.text.accent : theme.text.primary}\n    wrap=\"truncate\"\n  >\n    {tool.name}\n  </Text>\n</Box>\n{!tool.isValid && (\n  <Text color={theme.status.warning}>\n    {t('invalid: {{reason}}', {\n      reason: tool.invalidReason || t('unknown'),\n    })}\n  </Text>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx:1-15]()*\n\n### Context Usage Display\n\nTools contribute to the overall context window usage:\n\n```tsx\n// From packages/cli/src/ui/components/views/ContextUsage.tsx\n{/* Built-in tools detail */}\n{sortedBuiltinTools.length > 0 && (\n  <Box flexDirection=\"column\" marginTop={1}>\n    <Text bold color={theme.text.primary}>{t('Built-in tools')}</Text>\n    {sortedBuiltinTools.map((tool) => (\n      <DetailRow key={tool.name} name={tool.name} tokens={tool.tokens} />\n    ))}\n  </Box>\n)}\n\n{/* MCP Tools detail */}\n{sortedMcpTools.length > 0 && (\n  <Box flexDirection=\"column\" marginTop={1}>\n    <Text bold color={theme.text.primary}>{t('MCP tools')}</Text>\n    {sortedMcpTools.map((tool) => (\n      <DetailRow key={tool.name} name={tool.name} tokens={tool.tokens} />\n    ))}\n  </Box>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/views/ContextUsage.tsx:1-25]()*\n\n## Keyboard Shortcuts\n\nThe tool system integrates with keyboard shortcuts for quick access:\n\n```typescript\n// From packages/cli/src/ui/keyMatchers.test.ts\n[Command.TOGGLE_TOOL_DESCRIPTIONS]: (key: Key) => key.ctrl && key.name === 't',\n[Command.TOGGLE_IDE_CONTEXT_DETAIL]: (key: Key) => key.ctrl && key.name === 'g',\n```\n*资料来源：[packages/cli/src/ui/keyMatchers.test.ts:1-5]()*\n\n## Tool Validation\n\nTools undergo validation before execution:\n\n| Validation | Description |\n|------------|-------------|\n| isValid | Boolean flag indicating if tool is valid |\n| invalidReason | String explaining why tool is invalid |\n| schema | JSON schema for parameters |\n| parameters | Tool input parameters |\n\n```tsx\n// Tool validation display\n{annotations && tool.isValid && (\n  <Text color={theme.text.secondary}>{annotations}</Text>\n)}\n```\n*资料来源：[packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx:16-18]()*\n\n## Memory and Reference Tools\n\nThe system maintains reference memory for tools that interact with external systems:\n\n```typescript\n// From packages/core/src/memory/prompt.ts\n'<when_to_save>When you learn about resources in external systems and their purpose.</when_to_save>',\n'<how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>',\n```\n\nExamples of external system references:\n- Bug tracking systems (e.g., Linear)\n- Monitoring dashboards (e.g., Grafana)\n- Communication channels (e.g., Slack)\n\n## Configuration\n\n### Tool Registry Configuration\n\nThe tool registry is configured through the main config interface:\n\n```typescript\ngetToolRegistry: () => mockToolRegistry,\ngetTruncateToolOutputThreshold: () => 100,\ngetTruncateToolOutputLines: () => 10,\n```\n*资料来源：[packages/core/src/core/coreToolScheduler.test.ts:40-42]()*\n\n### Display Configuration\n\nTools can be configured for display with various options:\n\n```typescript\ninterface ToolDisplayConfig {\n  showDescriptions: boolean;\n  showSchema: boolean;\n  visibleCount: number;\n  scrollOffset: number;\n}\n```\n\n## Summary\n\nThe Tools System is a comprehensive framework that enables Qwen Code to interact with the development environment through:\n\n1. **Built-in Tools**: File operations, shell execution, and code editing\n2. **MCP Integration**: Connection to external tools and services via Model Context Protocol\n3. **LSP Integration**: Language server features for code intelligence\n4. **Central Registry**: Unified management of all available tools\n5. **UI Integration**: User-friendly display and interaction with tools\n6. **Validation System**: Ensuring tool validity before execution\n\nThe architecture supports extensibility through the plugin-based design, allowing new tools to be registered and discovered dynamically at runtime.\n\n---\n\n<a id='authentication'></a>\n\n## Authentication and Model Providers\n\n### 相关页面\n\n相关主题：[Turn Processing and LLM Communication](#turn-processing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/cli/src/auth/providerConfig.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/auth/providerConfig.ts)\n- [packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts)\n- [packages/cli/src/ui/auth/AuthDialog.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/auth/AuthDialog.tsx)\n- [packages/cli/src/ui/components/mcp/steps/AuthenticateStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/mcp/steps/AuthenticateStep.tsx)\n- [packages/cli/src/ui/components/QwenOAuthProgress.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/QwenOAuthProgress.tsx)\n- [README.md](https://github.com/QwenLM/qwen-code/blob/main/README.md)\n</details>\n\n# Authentication and Model Providers\n\n## Overview\n\nThe authentication and model provider system in Qwen Code provides a flexible, pluggable architecture for connecting to various LLM providers. It handles credential management, provider configuration, authentication flows (including OAuth), and model selection across multiple backends including Alibaba ModelStudio, OpenAI-compatible APIs, Ollama, and vLLM.\n\nThe system is designed around a provider configuration model that abstracts authentication details (API keys, OAuth tokens, base URLs) from the core content generation logic, allowing users to seamlessly switch between different providers and models. 资料来源：[packages/cli/src/auth/providerConfig.ts:1-50]()\n\n## Architecture\n\n### Core Components\n\n```mermaid\ngraph TD\n    subgraph \"User Interface Layer\"\n        AD[AuthDialog]\n        AS[AuthenticateStep]\n        QP[QwenOAuthProgress]\n    end\n    \n    subgraph \"Configuration Layer\"\n        PC[ProviderConfig]\n        MC[ModelConfig]\n        SS[Settings Schema]\n    end\n    \n    subgraph \"Provider Registry\"\n        AP[All Providers]\n        PM[Provider Matching]\n    end\n    \n    subgraph \"Authentication Services\"\n        OAuth[OAuth Flow]\n        APIKey[API Key Auth]\n        BaseURL[Base URL Resolution]\n    end\n    \n    AD --> AS\n    AS --> QP\n    PC --> PM\n    PM --> AP\n    AP --> OAuth\n    AP --> APIKey\n    AP --> BaseURL\n```\n\n### Provider Configuration Model\n\nThe `ProviderConfig` interface defines the structure for all provider configurations:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | `string` | Unique provider identifier |\n| `name` | `string` | Display name for the provider |\n| `baseUrl` | `string \\| Array<BaseUrlOption>` | API endpoint base URL |\n| `envKey` | `string` | Environment variable name for API key |\n| `modelsEditable` | `boolean` | Whether users can modify model list |\n| `showAdvancedConfig` | `boolean` | Show advanced configuration options |\n| `uiLabels` | `UILabelsConfig` | UI text labels and titles |\n| `modelNamePrefix` | `string` | Prefix for model names (e.g., provider tag) |\n\n资料来源：[packages/cli/src/auth/providerConfig.ts:20-40]()\n\n## Provider Matching Logic\n\n### Credential-Based Matching\n\nThe system uses a matching algorithm to identify the correct provider based on user credentials:\n\n```mermaid\ngraph TD\n    A[Input: baseUrl, envKey] --> B{envKey match?}\n    B -->|No| C[Return false]\n    B -->|Yes| D{baseUrl type?}\n    D -->|String| E{baseUrl matches?}\n    E -->|Yes| F[Return true]\n    E -->|No| C\n    D -->|Array| G{Any option matches?}\n    G -->|Yes| F\n    G -->|No| C\n```\n\nThe `providerMatchesCredentials` function implements this logic:\n\n```typescript\nexport function providerMatchesCredentials(\n  config: ProviderConfig,\n  baseUrl: string | undefined,\n  envKey: string | undefined,\n): boolean {\n  if (typeof config.envKey !== 'string' || config.envKey !== envKey) {\n    return false;\n  }\n  if (typeof config.baseUrl === 'string') {\n    return config.baseUrl === baseUrl;\n  }\n  if (Array.isArray(config.baseUrl)) {\n    return config.baseUrl.some((opt) => opt.url === baseUrl);\n  }\n  return false;\n}\n```\n\n资料来源：[packages/cli/src/auth/providerConfig.ts:47-63]()\n\n## Model Configuration\n\n### Building Model Configurations\n\nThe `buildModelConfigs` function transforms provider specifications into usable model configurations:\n\n```typescript\nfunction buildGenerationConfig(\n  spec: Pick<ModelSpec, 'enableThinking' | 'contextWindowSize' | 'modalities'>,\n): ProviderModelConfig['generationConfig'] | undefined {\n  const parts: ProviderModelConfig['generationConfig'] = {};\n  let hasAny = false;\n  if (spec.enableThinking) {\n    parts.extra_body = { enable_thinking: true };\n    hasAny = true;\n  }\n  if (spec.contextWindowSize) {\n    parts.contextWindowSize = spec.contextWindowSize;\n    hasAny = true;\n  }\n  if (spec.modalities && Object.values(spec.modalities).some(Boolean)) {\n    parts.modalities = spec.modalities;\n    hasAny = true;\n  }\n  return hasAny ? parts : undefined;\n}\n```\n\n资料来源：[packages/cli/src/auth/providerConfig.ts:90-107]()\n\n### Generation Configuration Options\n\n| Option | Structure | Purpose |\n|--------|-----------|---------|\n| `enableThinking` | `extra_body: { enable_thinking: true }` | Enable chain-of-thought reasoning |\n| `contextWindowSize` | `contextWindowSize: number` | Set maximum context length |\n| `modalities` | `{ text?: boolean, image?: boolean }` | Enable multimodal capabilities |\n\n## Authentication Methods\n\n### Supported Authentication Types\n\n| Method | Description | Status |\n|--------|-------------|--------|\n| **Qwen OAuth** | Alibaba Cloud OAuth flow | Discontinued (2026-04-15) |\n| **Coding Plan** | Alibaba ModelStudio fixed subscription | Active |\n| **API Key** | Direct OpenAI-compatible API access | Active |\n| **OAuth** | Third-party OAuth providers | Active |\n\n资料来源：[packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts:15-20]()\n\n### OAuth Authentication Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as AuthDialog\n    participant AuthStep as AuthenticateStep\n    participant OAuth as OAuthProvider\n    participant Browser\n\n    User->>CLI: Select OAuth provider\n    CLI->>AuthStep: Initialize OAuth flow\n    AuthStep->>OAuth: Request authorization URL\n    OAuth-->>AuthStep: Return verification URL\n    AuthStep->>User: Display URL + copy option\n    User->>Browser: Open verification URL\n    Browser->>OAuth: Complete authorization\n    OAuth-->>Browser: Authorization granted\n    Browser-->>User: Success confirmation\n    AuthStep->>OAuth: Poll for token\n    OAuth-->>AuthStep: Return access token\n    AuthStep-->>CLI: Authentication complete\n```\n\n### OAuth Progress UI\n\nThe `QwenOAuthProgress` component displays the device authorization flow:\n\n```typescript\nexport function QwenOAuthProgress({\n  deviceAuth,\n  timeRemaining,\n}: QwenOAuthProgressProps): React.JSX.Element {\n  return (\n    <Box flexDirection=\"column\" padding={1} width=\"100%\">\n      <Text bold>{t('Qwen OAuth Authentication')}</Text>\n      <Link url={deviceAuth.verification_uri_complete || ''}>\n        {deviceAuth.verification_uri_complete}\n      </Link>\n      <Text>\n        {t('Waiting for authorization')}\n        {dots}\n      </Text>\n      <Text>{t('Time remaining:')} {formatTime(timeRemaining)}</Text>\n    </Box>\n  );\n}\n```\n\n资料来源：[packages/cli/src/ui/components/QwenOAuthProgress.tsx:1-30]()\n\n## Discontinued Model Detection\n\n### ACP Model ID Parsing\n\nThe ACP (Agent Communication Protocol) server emits model IDs in a wrapped format for tracking discontinued models:\n\n| Format | Example |\n|--------|---------|\n| Standard | `qwen3-coder-plus(qwen-oauth)` |\n| Runtime | `$runtime\\|qwen-oauth\\|qwen3-coder-plus(qwen-oauth)` |\n\nThe `ParsedAcpModelId` interface extracts the base model ID and auth type:\n\n```typescript\nexport interface ParsedAcpModelId {\n  /** Model id with the trailing `(authType)` marker stripped. */\n  baseModelId: string;\n  /** Auth type extracted from the trailing `(authType)` marker. */\n  authType: string;\n}\n\nexport const DISCONTINUED_MESSAGES = {\n  badge: '(Discontinued)',\n  description: 'Discontinued — switch to Coding Plan or API Key',\n  blockedError:\n    'Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.',\n} as const;\n```\n\n资料来源：[packages/vscode-ide-companion/src/webview/utils/discontinuedModel.ts:20-35]()\n\n## Configuration Settings\n\n### Settings Schema Structure\n\nThe system uses a hierarchical settings structure defined in `settingsSchema.ts`:\n\n```mermaid\ngraph TD\n    SS[settings.json] --> MP[modelProviders]\n    MP --> OP[openai Array]\n    OP --> PMC[ProviderModelConfig]\n    PMC --> id\n    PMC --> name\n    PMC --> baseUrl\n    PMC --> description\n    PMC --> envKey\n    PMC --> generationConfig\n    SS --> S[security]\n    S --> auth\n    auth --> selectedType\n    SS --> M[model]\n    M --> name\n```\n\n### Provider Setup Inputs\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `baseUrl` | `string` | Yes | API endpoint base URL |\n| `apiKey` | `string` | Yes | API key value (or empty for template) |\n| `modelIds` | `string[]` | No | Specific model IDs to include |\n\n## Supported Providers\n\n### Provider Configuration Examples\n\n#### Alibaba ModelStudio (Coding Plan)\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3.6-plus\",\n        \"name\": \"qwen3.6-plus (Coding Plan)\",\n        \"baseUrl\": \"https://coding.dashscope.aliyuncs.com/v1\",\n        \"description\": \"qwen3.6-plus from ModelStudio Coding Plan\",\n        \"envKey\": \"BAILIAN_CODING_PLAN_API_KEY\"\n      }\n    ]\n  }\n}\n```\n\n资料来源：[README.md:50-65]()\n\n#### Ollama (Local)\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"qwen3:32b\",\n        \"name\": \"Qwen3 32B (Ollama)\",\n        \"baseUrl\": \"http://localhost:11434/v1\",\n        \"description\": \"Qwen3 32B running locally via Ollama\",\n        \"generationConfig\": {\n          \"contextWindowSize\": 131072\n        }\n      }\n    ]\n  }\n}\n```\n\n资料来源：[README.md:150-165]()\n\n#### vLLM (Local)\n\n```json\n{\n  \"modelProviders\": {\n    \"openai\": [\n      {\n        \"id\": \"Qwen/Qwen3-32B\",\n        \"name\": \"Qwen3 32B (vLLM)\",\n        \"baseUrl\": \"http://localhost:8000/v1\",\n        \"description\": \"Qwen3 32B running locally via vLLM\",\n        \"generationConfig\": {\n          \"contextWindowSize\": 131072\n        }\n      }\n    ]\n  }\n}\n```\n\n## Auth Dialog Workflow\n\n### View State Machine\n\n```mermaid\ngraph TD\n    M[main] --> AS[alibaba-select]\n    M --> TS[thirdparty-select]\n    M --> OS[oauth-select]\n    AS --> BR[baseUrl Step]\n    TS --> BR\n    OS --> BR\n    BR --> PK[apiKey Step]\n    PK --> MD[models Step]\n    MD --> AC[advancedConfig Step]\n    AC --> RV[review Step]\n    RV --> M\n```\n\nThe `AuthDialog` component manages this state:\n\n```typescript\nexport function AuthDialog(): React.JSX.Element {\n  const {\n    auth: { pendingAuthType, authError },\n  } = useUIState();\n  const {\n    auth: {\n      handleAuthSelect: onAuthSelect,\n      handleProviderSubmit,\n      handleOpenRouterSubmit,\n      onAuthError,\n    },\n  } = useUIActions();\n  const config = useConfig();\n  const settings = useSettings();\n\n  const [errorMessage, setErrorMessage] = useState<string | null>(null);\n  const [viewLevel, setViewLevel] = useState<ViewLevel>('main');\n  const [_viewStack, setViewStack] = useState<ViewStack>([]);\n```\n\n资料来源：[packages/cli/src/ui/auth/AuthDialog.tsx:60-85]()\n\n### Step Labels\n\n| Step Key | Label | Description |\n|----------|-------|-------------|\n| `protocol` | Protocol | Select communication protocol |\n| `baseUrl` | Base URL / Endpoint | Configure API endpoint |\n| `apiKey` | API Key | Enter credentials |\n| `models` | Model IDs | Select available models |\n| `advancedConfig` | Advanced Config | Show/hide advanced options |\n| `review` | Review | Confirm configuration |\n\n## Environment Variables\n\n### API Key Environment Variables\n\n| Provider | Environment Variable | Description |\n|----------|---------------------|-------------|\n| Alibaba ModelStudio | `DASHSCOPE_API_KEY` | Standard API key |\n| Alibaba Coding Plan | `BAILIAN_CODING_PLAN_API_KEY` | Subscription API key |\n| OpenAI | `OPENAI_API_KEY` | OpenAI API key |\n| Custom Providers | Variable defined in `envKey` field | Provider-specific |\n\n资料来源：[README.md:80-85]()\n\n## Security Considerations\n\n- **Never commit API keys** to version control — the `~/.qwen/settings.json` file should remain private\n- API keys via `export` or `.env` files take higher priority than `settings.json` → `env` configuration\n- The authentication system supports both key-based and OAuth-based authentication for different trust levels\n\n## Related Commands\n\n| Command | Description |\n|---------|-------------|\n| `/auth` | Launch interactive authentication setup |\n| `/model` | Switch between configured models |\n| `/mcp auth <server-name>` | Authenticate with OAuth-enabled MCP servers |\n\n资料来源：[packages/cli/src/ui/components/views/McpStatus.tsx:15-20]()\n\n---\n\n<a id='memory-system'></a>\n\n## Memory System\n\n### 相关页面\n\n相关主题：[Session Management](#session-management), [Core Agent Runtime](#agent-runtime)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/memory/manager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/manager.ts)\n- [packages/core/src/memory/entries.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/entries.ts)\n- [packages/core/src/memory/recall.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/recall.ts)\n- [packages/core/src/memory/extract.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/extract.ts)\n- [packages/core/src/memory/prompt.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/prompt.ts)\n- [packages/core/src/memory/dreamAgentPlanner.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/dreamAgentPlanner.ts)\n- [packages/core/src/memory/extractionAgentPlanner.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/memory/extractionAgentPlanner.ts)\n</details>\n\n# Memory System\n\n## Overview\n\nThe Memory System is a persistent, file-based knowledge management component in Qwen Code that enables the AI assistant to maintain context across conversations. It allows the system to remember information about users, projects, feedback, and external references, providing personalized and context-aware assistance over time.\n\nThe memory system is built around a directory structure at a configurable root location (`~/.qwen/memory/` by default) and uses Markdown files with structured frontmatter for storing persistent information. 资料来源：[packages/core/src/memory/prompt.ts:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[User Conversation] --> B[Memory Extraction Agent]\n    B --> C[Memory Files]\n    C --> D[Index File]\n    D --> E[Memory Recall]\n    E --> A\n    \n    F[Dream Agent] -->|Periodic Consolidation| C\n    F --> D\n    \n    G[CLI Remember Command] -->|Manual Save| C\n    G --> D\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| Memory Manager | `manager.ts` | Core memory operations and configuration |\n| Memory Entries | `entries.ts` | Data structures for memory items |\n| Memory Recall | `recall.ts` | Retrieval and context injection |\n| Memory Extraction | `extract.ts` | Automatic memory extraction from conversations |\n| Prompt Builder | `prompt.ts` | Prompt templates for memory operations |\n| Dream Agent | `dreamAgentPlanner.ts` | Periodic memory consolidation |\n| Extraction Agent | `extractionAgentPlanner.ts` | Extraction prompt generation |\n\n## Memory Types\n\nThe system supports four primary memory types, each stored in its own subdirectory:\n\n### Memory Type Structure\n\n```mermaid\ngraph LR\n    A[Memory Root] --> B[user/]\n    A --> C[feedback/]\n    A --> D[project/]\n    A --> E[reference/]\n```\n\n### Type Definitions\n\n| Type | Directory | Purpose | When to Save |\n|------|-----------|---------|--------------|\n| **User** | `user/` | User preferences, working style, collaboration patterns | When learning about user preferences, habits, or personal context |\n| **Feedback** | `feedback/` | Feedback on AI outputs, corrections, style preferences | When user corrects or provides feedback on AI responses |\n| **Project** | `project/` | Project-specific context, architecture, conventions | When learning about project structure, requirements, or technical decisions |\n| **Reference** | `reference/` | External systems, resources, documentation links | When learning about external systems (e.g., bug trackers, dashboards) |\n\n资料来源：[packages/core/src/memory/prompt.ts:50-120]()\n\n### What NOT to Save\n\nPer the system guidelines, the following should not be stored in memory:\n\n- Code patterns, conventions, architecture, file paths, or project structure\n- Git history, recent changes, or who-changed-what\n- Debugging solutions or fix recipes\n- Date-based information outside of the project directory\n\n资料来源：[packages/core/src/memory/prompt.ts:100-115]()\n\n## Memory File Format\n\nMemory files use structured Markdown with YAML frontmatter:\n\n```yaml\n---\ntitle: <Title>\ntype: <user | feedback | project | reference>\ncreated: <ISO timestamp>\nupdated: <ISO timestamp>\n---\n# Memory Content\n\n<Detailed memory information>\n```\n\n### Index File\n\nThe `index.md` file serves as a catalog of all memories:\n\n```markdown\n# index\n\n- [Title](relative/path.md) — one-line hook\n- [Another Memory](another/file.md) — brief description\n```\n\nEach index entry must be a single line with the format: `- [Title](relative/path.md) — one-line hook`\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-50]()\n\n## Memory Operations\n\n### Memory Extraction\n\nMemory extraction is an automated process that identifies valuable information during conversations. The extraction agent uses a limited tool set:\n\n**Available Tools:**\n- `grep_search`\n- `glob`\n- `list_directory`\n- `read_file` / `write_file` / `edit` (memory directory only)\n\n**Extraction Workflow:**\n\n```mermaid\nsequenceDiagram\n    participant User as User Message\n    participant Extract as Extraction Agent\n    participant FS as Memory Files\n    \n    User->>Extract: Conversation with new information\n    Extract->>FS: Read existing memory files\n    Extract->>FS: Check for duplicates\n    Extract->>FS: Write/Update memory file\n    Extract->>FS: Update index.md\n```\n\n**Efficient Strategy:**\n1. Issue all reads in parallel for files that might be updated\n2. Issue all writes/edits in parallel\n3. Never interleave reads and writes across multiple turns\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-30]()\n\n### Memory Recall\n\nMemory recall retrieves relevant memories based on context. The system:\n\n1. Maintains a rolling context of recent memories\n2. Dynamically loads memories based on conversation relevance\n3. Limits loaded memories to prevent context overflow\n\n**Memory Truncation:**\n\nThe system warns when `MEMORY.md` exceeds size limits:\n- Maximum managed auto memory index lines: 512\n- Warning message format: `> WARNING: MEMORY.md is [reason]. Only part of it was loaded.`\n\n资料来源：[packages/core/src/memory/prompt.ts:1-30]()\n\n### Memory Consolidation (Dream Agent)\n\nThe Dream Agent runs periodically to consolidate and clean up memories:\n\n**Consolidation Phases:**\n\n```mermaid\ngraph TD\n    A[Phase 1: Orient] --> B[Phase 2: Gather Signal]\n    B --> C[Phase 3: Consolidate]\n    C --> D[Phase 4: Prune]\n```\n\n#### Phase 1 — Orient\n- List the memory directory to see existing files\n- Read `memoryRoot/index.md` to understand current state\n- Skim topic subdirectories (`user/`, `project/`, `feedback/`, `reference/`)\n- Review recent entries in `logs/` or `sessions/` subdirectories\n\n#### Phase 2 — Gather Recent Signal\n- Look for new information worth persisting\n- Check for existing memories that have drifted\n- Grep session transcripts for narrow terms if context is needed\n\n#### Phase 3 — Consolidate\nFor each topic directory:\n- Identify duplicate or near-duplicate `.md` files\n- Merge duplicates into canonical versions\n- Fix stale or contradicted facts\n- Convert relative dates to absolute dates\n\n资料来源：[packages/core/src/memory/dreamAgentPlanner.ts:1-60]()\n\n## Manual Memory Operations\n\n### CLI Remember Command\n\nUsers can manually save information using the `/remember` command:\n\n```bash\n/remember <fact-to-remember>\n```\n\n**Behavior:**\n- When managed auto-memory is enabled: The system asks the agent to save to the appropriate memory type directory\n- When disabled: The system asks the agent to append to `QWEN.md` in the project root\n\n**Implementation Flow:**\n\n```mermaid\ngraph LR\n    A[/remember command] --> B{Memory Enabled?}\n    B -->|Yes| C[Submit to Agent]\n    C --> D[Prompt Agent to Save]\n    D --> E[Choose memory type]\n    E --> F[Save to appropriate directory]\n    \n    B -->|No| G[Submit to Agent]\n    G --> H[Append to QWEN.md]\n```\n\n资料来源：[packages/cli/src/ui/commands/rememberCommand.ts:1-60]()\n\n## UI Integration\n\n### Memory Statistics Display\n\nThe UI displays memory operation statistics in tool call summaries:\n\n```typescript\n// Memory statistics shown in ToolGroupMessage\nif (memoryRecallCount > 0) {\n    parts.push(`Recalled ${n} ${n === 1 ? 'memory' : 'memories'}`);\n}\nif (memoryWriteCount > 0) {\n    parts.push(`Wrote ${n} ${n === 1 ? 'memory' : 'memories'}`);\n}\n```\n\n**Display Format:**\n- Shows count of recalled memories\n- Shows count of written memories\n- Rendered as inline summary after tool execution\n\n资料来源：[packages/cli/src/ui/components/messages/ToolGroupMessage.tsx:1-50]()\n\n### Memory Usage Metrics\n\nThe telemetry system tracks memory operations:\n\n| Metric | Type | Description |\n|--------|------|-------------|\n| `memory.dream.count` | Counter | Number of memory consolidation runs |\n| `memory.dream.duration` | Histogram | Duration of consolidation operations |\n| `memory.recall.count` | Counter | Number of memory recall operations |\n| `memory.recall.duration` | Histogram | Duration of recall operations |\n| `memory.extract.duration` | Histogram | Duration of extraction operations |\n| `memory.usage` | Histogram | Memory usage in bytes |\n\n资料来源：[packages/core/src/telemetry/metrics.ts:1-50]()\n\n## Configuration\n\n### Memory Root Path\n\nThe memory system is configured at:\n\n```\n~/.qwen/memory/  (default)\n```\n\n### Directory Structure\n\n```\nmemoryRoot/\n├── index.md           # Master index of all memories\n├── user/              # User preference memories\n│   └── *.md\n├── feedback/          # Feedback memories\n│   └── *.md\n├── project/           # Project-specific memories\n│   └── *.md\n├── reference/         # External reference memories\n│   └── *.md\n├── logs/              # Session logs (optional)\n└── sessions/          # Session transcripts (optional)\n```\n\n## Best Practices\n\n### Index Entry Guidelines\n\n- Keep index entries to one line under ~200 characters\n- Move detailed content into topic files\n- Each entry format: `- [Title](relative/path.md) — one-line hook`\n\n### Memory File Guidelines\n\n- One durable memory per file\n- Use frontmatter with title, type, created, and updated fields\n- Avoid duplicate or near-duplicate content\n- Convert relative dates to absolute dates\n\n### When to Update vs. Create\n\n- Prefer updating an existing memory file over creating duplicates\n- Check for existing entries before creating new ones\n- Consolidate related information into single files\n\n资料来源：[packages/core/src/memory/extractionAgentPlanner.ts:1-40]()\n\n## Related Documentation\n\n- [Managed Auto Memory Prompt Template](packages/core/src/memory/prompt.ts) — Complete prompt for memory system\n- [Dream Agent Planner](packages/core/src/memory/dreamAgentPlanner.ts) — Consolidation workflow\n- [Extraction Agent Planner](packages/core/src/memory/extractionAgentPlanner.ts) — Extraction guidelines\n- [Remember Command](packages/cli/src/ui/commands/rememberCommand.ts) — Manual memory saving\n\n---\n\n<a id='session-management'></a>\n\n## Session Management\n\n### 相关页面\n\n相关主题：[Memory System](#memory-system), [Core Agent Runtime](#agent-runtime)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/services/sessionService.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/services/sessionService.ts)\n- [packages/core/src/services/sessionRecap.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/services/sessionRecap.ts)\n- [packages/core/src/services/sessionTitle.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/services/sessionTitle.ts)\n- [packages/core/src/config/storage.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/config/storage.ts)\n- [packages/vscode-ide-companion/src/services/qwenAgentManager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/vscode-ide-companion/src/services/qwenAgentManager.ts)\n- [packages/cli/src/ui/contexts/UIActionsContext.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/contexts/UIActionsContext.tsx)\n- [packages/cli/src/ui/hooks/useBranchCommand.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/hooks/useBranchCommand.ts)\n</details>\n\n# Session Management\n\n## Overview\n\nSession Management is a core system in Qwen Code that orchestrates the lifecycle of agent conversations. It handles creating new sessions, persisting conversation history, enabling session branching (forking), resuming previous sessions, and managing session metadata. The system ensures continuity across interactions and supports features like session recap generation, title derivation, and artifact preservation.\n\nSession management operates across multiple packages including `packages/core`, `packages/cli`, and `packages/vscode-ide-companion`, with data persisted to the file system in JSONL format.\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"CLI Layer\"\n        UI[UI Components]\n        Actions[UIActionsContext]\n        BranchCmd[useBranchCommand]\n    end\n    \n    subgraph \"Core Services\"\n        SessionService[SessionService]\n        SessionRecap[SessionRecap]\n        SessionTitle[SessionTitle]\n    end\n    \n    subgraph \"Storage Layer\"\n        Storage[Storage Config]\n        FileSystem[File System]\n        ACP[ACP Protocol]\n    end\n    \n    UI --> Actions\n    Actions --> BranchCmd\n    BranchCmd --> SessionService\n    SessionService --> Storage\n    SessionService --> SessionTitle\n    SessionService --> SessionRecap\n    Storage --> FileSystem\n    ACP --> SessionService\n    \n    QwenAgent[QwenAgentManager] --> ACP\n    QwenAgent --> Storage\n```\n\n## Core Services\n\n### SessionService\n\nThe `SessionService` is the central orchestrator for all session operations. It provides APIs for:\n\n| Method | Description |\n|--------|-------------|\n| `createSession()` | Creates a new session with unique ID |\n| `forkSession()` | Creates a branch (fork) of an existing session |\n| `getSession()` | Retrieves a session by ID |\n| `listSessions()` | Lists all sessions, optionally filtered by project |\n| `deleteSession()` | Removes a session and its artifacts |\n| `saveSession()` | Persists session state to disk |\n| `loadSession()` | Loads session from storage |\n\n资料来源：[packages/core/src/services/sessionService.ts]()\n\n#### Session Data Model\n\n```typescript\ninterface QwenSession {\n  sessionId: string;\n  title: string;\n  name: string;\n  startTime: number;\n  lastUpdated: number;\n  messageCount: number;\n  projectHash?: string;\n  filePath?: string;\n  cwd?: string;\n}\n```\n\n资料来源：[packages/vscode-ide-companion/src/services/qwenAgentManager.ts:24-33]()\n\n### SessionTitle Service\n\nThe `SessionTitle` service automatically derives session titles from conversation content. It analyzes the first user prompt and generates a human-readable title that identifies the session's purpose.\n\n| Feature | Description |\n|---------|-------------|\n| Title Derivation | Extracts meaningful title from initial prompt |\n| Auto-naming | Provides default names like \"Untitled Session\" when no title is available |\n| Persistence | Titles are saved with session metadata |\n\n资料来源：[packages/core/src/services/sessionTitle.ts]()\n\n### SessionRecap Service\n\nThe `SessionRecap` service generates summary information about sessions, providing context for:\n\n- Session status display\n- Background task tracking\n- Conversation metadata\n\n资料来源：[packages/core/src/services/sessionRecap.ts]()\n\n## Storage Architecture\n\n### File System Storage\n\nSessions are persisted to the file system using a structured directory layout:\n\n```mermaid\ngraph TD\n    Root[Project/Root Directory]\n    QwenDir[.qwen/]\n    SessionsDir[sessions/]\n    Session1[session-id-1.jsonl]\n    Session2[session-id-2.jsonl]\n    \n    Root --> QwenDir\n    QwenDir --> SessionsDir\n    SessionsDir --> Session1\n    SessionsDir --> Session2\n```\n\nThe `Storage` config provides methods for:\n\n| Method | Purpose |\n|--------|---------|\n| `getProjectTempDir()` | Get temporary directory for session artifacts |\n| `getSessionDir()` | Get the sessions directory path |\n| `getSessionFile()` | Get path for a specific session file |\n\n资料来源：[packages/core/src/config/storage.ts]()\n\n### Session File Format\n\nSession data is stored in JSONL (JSON Lines) format, with each line representing a single message or event in the conversation. This format allows for:\n\n- Efficient streaming writes\n- Incremental reading\n- Easy append operations\n\n### ACP Protocol Fallback\n\nWhen the Agent Communication Protocol (ACP) session list fails, the system automatically falls back to reading sessions directly from the file system:\n\n```typescript\n// From qwenAgentManager.ts\ntry {\n  const items = await acpClient.listSessions();\n  if (items.length > 0) {\n    return items.map(/* transform to session format */);\n  }\n} catch (error) {\n  console.warn('[QwenAgentManager] ACP session list failed, falling back...');\n}\n\n// Fallback to file system\nconst sessions = await this.sessionReader.getAllSessions(undefined, true);\n```\n\n资料来源：[packages/vscode-ide-companion/src/services/qwenAgentManager.ts:55-71]()\n\n## Session Lifecycle Operations\n\n### Creating a New Session\n\n```mermaid\ngraph LR\n    A[Start] --> B[Generate Session ID]\n    B --> C[Create Session Object]\n    C --> D[Initialize Message Queue]\n    D --> E[Save to File System]\n    E --> F[Update UI State]\n```\n\n### Session Branching (Forking)\n\nThe branch command allows creating a fork of an existing session, enabling parallel exploration of different approaches:\n\n```mermaid\ngraph TD\n    A[Original Session] --> B[Invoke /branch Command]\n    B --> C[Capture Parent Session ID]\n    B --> D[Finalize Current Recording]\n    C --> E[forkSession Service Call]\n    D --> E\n    E --> F[Write New JSONL File]\n    F --> G[Load Forked Session]\n    G --> H[Update UI Context]\n    H --> I[Fire SessionStart Hook]\n```\n\nThe branching process:\n\n1. Captures the current session ID for resume hint\n2. Finalizes the ChatRecordingService to persist last metadata\n3. Calls `SessionService.forkSession()` to create a new JSONL file\n4. Loads the fork back via `loadSession`\n5. Computes custom title with \"(Branch)\" suffix\n6. Announces the fork with Claude-style info\n\n资料来源：[packages/cli/src/ui/hooks/useBranchCommand.ts]()\n\n### Session Resumption\n\nResuming a session allows returning to a previous conversation:\n\n| Step | Action |\n|------|--------|\n| 1 | User invokes `/resume` command |\n| 2 | System loads session from storage |\n| 3 | Chat history is restored |\n| 4 | Context and configuration are restored |\n\n### Session Deletion\n\nSessions can be deleted individually or in bulk:\n\n```typescript\n// From UIActionsContext.tsx\nhandleDelete: (sessionId: string) => void;\nhandleDeleteMany: (sessionIds: string[]) => void;\n```\n\n资料来源：[packages/cli/src/ui/contexts/UIActionsContext.tsx:89-90]()\n\n## UI Integration\n\n### UIActionsContext\n\nThe `UIActionsContext` provides a comprehensive interface for session-related UI operations:\n\n| Action | Description |\n|--------|-------------|\n| `openResumeDialog()` | Opens dialog to resume a previous session |\n| `closeResumeDialog()` | Closes resume dialog |\n| `handleResume(sessionId)` | Resumes specific session |\n| `handleBranch(name?)` | Creates a branch/fork |\n| `openDeleteDialog()` | Opens delete confirmation dialog |\n| `handleDelete(sessionId)` | Deletes a single session |\n| `handleDeleteMany(sessionIds)` | Bulk deletes sessions |\n\n资料来源：[packages/cli/src/ui/contexts/UIActionsContext.tsx:76-92]()\n\n### Background Tasks Dialog\n\nSession information is displayed in the background tasks dialog, showing:\n\n- Session review status\n- Session count\n- Topics touched in the conversation\n- Error states and lock-release warnings\n\n```typescript\n// From BackgroundTasksDialog.tsx\n{entry.sessionCount !== undefined && (\n  <Fragment>\n    <Text bold dimColor>{t('Sessions reviewing')}</Text>\n    <Text>{String(entry.sessionCount)}</Text>\n  </Fragment>\n)}\n```\n\n## Arena Session Management\n\nArena sessions have specialized management options for handling artifacts:\n\n```typescript\ntype StopAction = 'cleanup' | 'preserve';\n```\n\n| Action | Behavior |\n|--------|----------|\n| `cleanup` | Remove all worktrees and session files |\n| `preserve` | Keep worktrees and session files for later inspection |\n\n资料来源：[packages/cli/src/ui/components/arena/ArenaStopDialog.tsx]()\n\n## Configuration\n\n### Session-Related Configuration\n\n```typescript\ninterface SessionConfig {\n  getSessionId: () => string;\n  getUsageStatisticsEnabled: () => boolean;\n  getDebugMode: () => boolean;\n  getApprovalMode: () => ApprovalMode;\n  storage: {\n    getProjectTempDir: () => string;\n  };\n}\n```\n\n## Related Commands\n\n| Command | Description |\n|---------|-------------|\n| `/branch` | Fork current session |\n| `/resume` | Resume a previous session |\n| `/delete` | Delete session(s) |\n| `/sessions` | List all sessions |\n\n## Summary\n\nThe Session Management system in Qwen Code provides a robust framework for:\n\n1. **Lifecycle Management** - Creating, forking, resuming, and deleting sessions\n2. **Persistence** - Storing sessions in JSONL format on the file system\n3. **Metadata** - Managing titles, timestamps, and conversation statistics\n4. **UI Integration** - Rich dialogs and context providers for session operations\n5. **Cross-Platform** - Unified session management across CLI and VS Code IDE companion\n\nAll session operations are designed to be atomic and reliable, with automatic fallbacks (e.g., ACP → file system) to ensure data accessibility.\n\n---\n\n<a id='skills-system'></a>\n\n## Skills System\n\n### 相关页面\n\n相关主题：[Extensions System](#extensions), [Core Agent Runtime](#agent-runtime)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/skills/skill-manager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/skill-manager.ts)\n- [packages/core/src/skills/skill-load.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/skill-load.ts)\n- [packages/core/src/skills/skill-activation.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/skill-activation.ts)\n- [packages/core/src/skills/types.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/types.ts)\n- [packages/core/src/skills/bundled/review/SKILL.md](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/bundled/review/SKILL.md)\n- [packages/cli/src/ui/components/views/ContextUsage.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/views/ContextUsage.tsx)\n- [packages/cli/src/ui/components/HistoryItemDisplay.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/HistoryItemDisplay.tsx)\n- [packages/core/src/core/coreToolScheduler.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/core/coreToolScheduler.ts)\n</details>\n\n# Skills System\n\n## Overview\n\nThe Skills System is a modular extension framework within qwen-code that enables dynamic loading and activation of predefined capabilities. Skills are specialized modules that extend the agent's functionality beyond built-in tools, allowing users to configure and utilize domain-specific capabilities through a standardized interface.\n\nSkills serve as a composition layer between the core agent and specialized functionality, providing:\n- **Modular capability packaging** - Skills bundle related functionality into self-contained units\n- **Dynamic loading** - Skills can be loaded on-demand without restarting the application\n- **Token-based resource tracking** - Each skill reports its token consumption for context management\n- **Model override support** - Skills can influence which model handles specific requests\n\n资料来源：[packages/core/src/skills/types.ts]()\n\n## Architecture\n\nThe Skills System follows a layered architecture with clear separation of concerns:\n\n```mermaid\ngraph TD\n    A[Agent Request] --> B[Skill Manager]\n    B --> C[Skill Loader]\n    C --> D[Skill Activation]\n    D --> E[Skill Execution]\n    \n    F[Skill Manifest<br/>SKILL.md] --> C\n    G[User Config] --> B\n    H[Token Budget] --> E\n    \n    E --> I[Response with<br/>Model Override]\n    E --> J[Tool Results]\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| Skill Manager | `skill-manager.ts` | Orchestrates skill lifecycle, registration, and retrieval |\n| Skill Loader | `skill-load.ts` | Parses skill manifests, validates, and instantiates skills |\n| Skill Activation | `skill-activation.ts` | Manages skill activation state and context injection |\n| Skill Types | `types.ts` | Defines interfaces, enums, and type contracts |\n\n资料来源：[packages/core/src/skills/skill-manager.ts]()\n\n## Skill Structure\n\n### Skill Manifest (SKILL.md)\n\nEach skill is defined by a `SKILL.md` manifest file that describes its metadata and behavior:\n\n```markdown\n# Skill: Review\n\n## Description\nPerforms code review analysis with configurable rules.\n\n## Triggers\n- Command: `/review`\n- Auto-suggest: On file save\n\n## Actions\n- analyze(code): ReviewResult\n- suggest_fixes(issues): Fix[]\n```\n\n资料来源：[packages/core/src/skills/bundled/review/SKILL.md]()\n\n### Skill Data Model\n\n```typescript\ninterface Skill {\n  name: string;           // Unique identifier\n  loaded: boolean;        // Current activation state\n  tokens: number;         // Token consumption for context\n  bodyTokens?: number;    // Additional body tokens if loaded\n  description?: string;   // Human-readable description\n}\n```\n\n资料来源：[packages/cli/src/ui/components/views/ContextUsage.tsx:55-61]()\n\n## Skill Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Unregistered\n    Unregistered --> Registered: Register Skill\n    Registered --> Loading: Activate Skill\n    Loading --> Active: Load Complete\n    Active --> Loading: Re-activate\n    Active --> Inactive: Deactivate\n    Inactive --> Active: Reactivate\n    Inactive --> Unregistered: Unregister\n    Registered --> Unregistered: Unregister\n```\n\n### States\n\n| State | Description |\n|-------|-------------|\n| `Unregistered` | Skill not known to the system |\n| `Registered` | Skill manifest parsed and indexed |\n| `Loading` | Skill resources being prepared |\n| `Active` | Skill ready for execution |\n| `Inactive` | Skill loaded but temporarily disabled |\n\n## Skill Loading Process\n\nThe skill loading process involves multiple stages:\n\n```mermaid\nsequenceDiagram\n    participant SM as Skill Manager\n    participant SL as Skill Loader\n    participant SA as Skill Activator\n    participant FS as File System\n    \n    SM->>FS: Read SKILL.md manifest\n    FS-->>SL: Manifest content\n    SL->>SL: Parse YAML frontmatter\n    SL->>SL: Validate schema\n    SL->>SA: Validated manifest\n    SA->>SA: Allocate token budget\n    SA-->>SM: Skill activated\n    SM->>SM: Update skill registry\n```\n\n资料来源：[packages/core/src/skills/skill-load.ts]()\n\n## Integration with Tool System\n\nSkills integrate with the core tool scheduler through a unified execution model:\n\n```mermaid\ngraph LR\n    A[Agent Request] --> B{Request Type}\n    B -->|Tool Call| C[Tool Scheduler]\n    B -->|Skill Action| D[Skill Activation]\n    \n    C --> E[Tool Executor]\n    D --> E\n    \n    E --> F[Function Response]\n    F --> G[Response with Metadata]\n    \n    H[Model Override] --> G\n    D --> H\n```\n\n### Model Override Propagation\n\nSkills can return a `modelOverride` field that influences which model handles subsequent requests:\n\n```typescript\nconst successResponse: ToolCallResponseInfo = {\n  callId,\n  responseParts: response,\n  resultDisplay: toolResult.returnDisplay,\n  error: undefined,\n  errorType: undefined,\n  contentLength,\n  // Propagate modelOverride from skill tools\n  ...('modelOverride' in toolResult\n    ? { modelOverride: toolResult.modelOverride }\n    : {}),\n};\n```\n\n资料来源：[packages/core/src/core/coreToolScheduler.ts:248-258]()\n\n## Context Usage Tracking\n\nThe system tracks skill resource consumption for context management:\n\n```typescript\ninterface ContextUsage {\n  modelName: string;\n  totalTokens: number;\n  contextWindowSize: number;\n  breakdown: TokenBreakdown;\n  skills: Skill[];\n  builtinTools: Tool[];\n  mcpTools: Tool[];\n  memoryFiles: FileInfo[];\n  isEstimated: boolean;\n  showDetails: boolean;\n}\n```\n\n资料来源：[packages/cli/src/ui/components/HistoryItemDisplay.tsx:89-98]()\n\n### Skill Display in Context Usage\n\nSkills are rendered with the following information hierarchy:\n\n| Field | Display | Description |\n|-------|---------|-------------|\n| `name` | Link text | Skill identifier |\n| `loaded` | Badge \"active\" | Green indicator when active |\n| `tokens` | Numeric count | Total tokens consumed |\n| `bodyTokens` | Italic secondary | Body content token count |\n\n```typescript\n{sortedSkills.map((skill) => (\n  <Box key={skill.name} flexDirection=\"column\">\n    <Box width={CONTENT_WIDTH} paddingLeft={2}>\n      <Text>{'\\u2514'} </Text>\n      <Box width={32}>\n        <Text color={theme.text.link}>\n          {truncateName(skill.name, DETAIL_NAME_MAX_LEN)}\n        </Text>\n        {skill.loaded && (\n          <Text color={theme.status.success}> {t('active')}</Text>\n        )}\n      </Box>\n      <Box flexGrow={1} justifyContent=\"flex-end\">\n        <Text color={theme.text.secondary}>\n          {formatTokens(skill.tokens)} {t('tokens')}\n        </Text>\n      </Box>\n    </Box>\n  </Box>\n))}\n```\n\n资料来源：[packages/cli/src/ui/components/views/ContextUsage.tsx:55-73]()\n\n## User Interface Components\n\n### Skills List Component\n\nThe `SkillsList` component renders available skills in the history view:\n\n```typescript\n{itemForDisplay.type === 'skills_list' && (\n  <SkillsList skills={itemForDisplay.skills} />\n)}\n```\n\n资料来源：[packages/cli/src/ui/components/HistoryItemDisplay.tsx:54-56]()\n\n### Skill Registration Flow\n\n```mermaid\ngraph TD\n    A[Start CLI] --> B[Load User Config]\n    B --> C[Scan Skill Directories]\n    C --> D{skill found?}\n    D -->|Yes| E[Parse SKILL.md]\n    D -->|No| F[Skip]\n    E --> G{Valid manifest?}\n    G -->|Yes| H[Register in Manager]\n    G -->|No| I[Log warning]\n    H --> J[Add to active list]\n    J --> K[Ready for use]\n```\n\n## Configuration\n\nSkills can be configured through the main configuration system:\n\n| Config Option | Type | Default | Description |\n|---------------|------|---------|-------------|\n| `skills.enabled` | boolean | `true` | Enable/disable skills system |\n| `skills.maxTokens` | number | `8000` | Maximum tokens for all skills |\n| `skills.autoLoad` | boolean | `true` | Load skills on startup |\n\nConfiguration is accessed through the central `Config` interface which provides access to skill-related settings.\n\n## Bundled Skills\n\nThe repository includes bundled skills that provide out-of-the-box functionality:\n\n| Skill | Path | Purpose |\n|-------|------|---------|\n| Review | `bundled/review/` | Code review and analysis |\n\n资料来源：[packages/core/src/skills/bundled/review/SKILL.md]()\n\n## Error Handling\n\nThe skill system integrates with the tool scheduler's error handling mechanism:\n\n```typescript\n// Failure handling in skill execution\nif (hooksEnabled && messageBus) {\n  const failureHookResult = await safelyFirePostToolUseFailureHook(\n    messageBus,\n    toolUseId,\n    toolName,\n    toolInput,\n    toolResult.error.message,\n    false,\n    this.config.getApprovalMode(),\n  );\n\n  // Append additional context from hook if provided\n  if (failureHookResult.additionalContext) {\n    errorMessage += `\\n\\n${failureHookResult.additionalContext}`;\n  }\n}\n```\n\n资料来源：[packages/core/src/core/coreToolScheduler.ts:263-274]()\n\n## Best Practices\n\n1. **Manifest Validation** - Always validate SKILL.md against the schema before distribution\n2. **Token Budgeting** - Monitor skill token usage to stay within context limits\n3. **Lazy Loading** - Prefer loading skills on-demand rather than at startup\n4. **Model Override** - Use sparingly and document the override behavior clearly\n5. **Error Boundaries** - Wrap skill execution in try-catch to prevent cascading failures\n\n## Summary\n\nThe Skills System provides a flexible, extensible framework for adding capabilities to the qwen-code agent. By standardizing skill definition through manifests, tracking resource consumption, and integrating with the tool execution pipeline, skills enable users to customize and expand the agent's functionality without modifying core code.\n\n---\n\n<a id='extensions'></a>\n\n## Extensions System\n\n### 相关页面\n\n相关主题：[Skills System](#skills-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/extension/extensionManager.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/extension/extensionManager.ts)\n- [packages/cli/src/ui/components/extensions/steps/ExtensionListStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/extensions/steps/ExtensionListStep.tsx)\n- [packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx)\n- [packages/cli/src/commands/extensions/settings.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/cli/src/commands/extensions/settings.ts)\n- [packages/core/src/tools/skill.ts](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/tools/skill.ts)\n- [packages/core/src/skills/bundled/qc-helper/SKILL.md](https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/skills/bundled/qc-helper/SKILL.md)\n</details>\n\n# Extensions System\n\n## Overview\n\nThe Extensions System is a modular plugin architecture that allows Qwen Code to extend its core functionality through dynamically loadable extensions. Extensions can provide MCP servers, skills, tools, commands, and configuration options that integrate seamlessly with the main application.\n\nExtensions enable third-party developers to extend Qwen Code without modifying the core codebase, while providing users with additional capabilities through a standardized interface.\n\n## Architecture\n\n### Extension Manager\n\nThe `ExtensionManager` is the central orchestrator responsible for loading, enabling, disabling, and managing all extensions. It maintains a registry of loaded extensions and handles their lifecycle events.\n\n```mermaid\ngraph TD\n    A[User Request] --> B[ExtensionManager]\n    B --> C[Find Extension by Name]\n    C --> D{Extension Found?}\n    D -->|Yes| E[Enable/Disable Extension]\n    D -->|No| F[Raise Error]\n    E --> G[Refresh Tools]\n    G --> H[Update Available Skills]\n```\n\n### Extension Lifecycle\n\nExtensions follow a defined lifecycle managed by the ExtensionManager:\n\n| State | Description |\n|-------|-------------|\n| `loaded` | Extension binary is loaded into memory |\n| `active` | Extension is enabled and functional |\n| `inactive` | Extension is disabled but remains loaded |\n\nThe manager provides methods to control this lifecycle:\n\n- `enableExtension(name, scope, cwd?)` - Activates an extension\n- `disableExtension(name, scope, cwd?)` - Deactivates an extension\n- `getLoadedExtensions()` - Returns all currently loaded extensions\n- `refreshTools()` - Updates the tool registry after extension changes\n\n资料来源：[packages/core/src/extension/extensionManager.ts:1-50]()\n\n## Extension Configuration\n\n### Settings Scopes\n\nExtensions support configuration at multiple scopes, following Qwen Code's hierarchical configuration model:\n\n| Scope | Path | Priority |\n|-------|------|----------|\n| User | `~/.qwen/settings.json` | Lower |\n| Workspace | `<project>/.qwen/settings.json` | Higher |\n\nSettings for extensions are stored with the extension ID as the namespace key, allowing multiple extensions to maintain independent configurations.\n\n资料来源：[packages/cli/src/commands/extensions/settings.ts:1-30]()\n\n### Accessing Extension Settings\n\nExtension settings can be retrieved at runtime using scoped environment contents:\n\n```typescript\nconst userSettings = await getScopedEnvContents(\n  extension.config,\n  extension.id,\n  ExtensionSettingScope.USER,\n);\nconst workspaceSettings = await getScopedEnvContents(\n  extension.config,\n  extension.id,\n  ExtensionSettingScope.WORKSPACE,\n);\nconst mergedSettings = { ...userSettings, ...workspaceSettings };\n```\n\nSettings merge with workspace settings taking precedence over user settings.\n\n资料来源：[packages/cli/src/commands/extensions/settings.ts:40-55]()\n\n## Extension Metadata\n\nEach extension carries metadata that describes its identity and capabilities:\n\n| Property | Description |\n|----------|-------------|\n| `name` | Unique identifier for the extension |\n| `version` | Semantic version string |\n| `path` | Filesystem path to the extension |\n| `isActive` | Boolean indicating current activation state |\n| `installMetadata` | Source information (e.g., marketplace) |\n| `mcpServers` | Map of MCP server configurations |\n| `commands` | List of provided commands |\n| `skills` | List of provided skills |\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-50]()\n\n## MCP Server Integration\n\nExtensions can provide MCP (Model Context Protocol) servers that expose additional tools and capabilities to the AI model:\n\n```mermaid\ngraph LR\n    A[Extension] --> B[MCP Servers Config]\n    B --> C[Server: tool1]\n    B --> D[Server: tool2]\n    C --> E[Available Tools]\n    D --> E\n```\n\nWhen an extension provides MCP servers, they are listed in the extension detail view:\n\n```typescript\n{ext.mcpServers && Object.keys(ext.mcpServers).length > 0 && (\n  <Box>\n    <Text color={theme.text.primary}>{t('MCP Servers:')}</Text>\n    <Text>{Object.keys(ext.mcpServers).join(', ')}</Text>\n  </Box>\n)}\n```\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:50-65]()\n\n## Skills and Commands\n\nExtensions can contribute skills that appear in the available skills list presented to the AI model. This integration uses XML-based skill descriptors:\n\n```xml\n<skill>\n<name>\n{skill.name}\n</name>\n<description>\n{descText}\n</description>\n<location>\n{skill.level}\n</location>\n</skill>\n```\n\nThe skill system includes security measures to prevent injection attacks. Extension skill names and descriptions are properly escaped when generating the available skills block:\n\n```typescript\n// Extension skills bypass the standard validator,\n// so they must be escaped explicitly\nallSkillEntries.push(`<skill>\n<name>\n${escapeXml(skill.name)}\n</name>\n<description>\n${descText}\n</description>\n<location>\n${skill.level}\n</location>\n</skill>`);\n```\n\n资料来源：[packages/core/src/tools/skill.ts:1-50]()\n\n### Command Sources\n\nExtension-provided commands are labeled with their source for clarity in the UI:\n\n| Source Type | Label Format | Description |\n|-------------|--------------|-------------|\n| `plugin-command` | `Extension: {name}` | Commands from extensions |\n| `skill-dir-command` | `Project` or `User` | Commands from local skill directories |\n\n资料来源：[packages/cli/src/services/SkillCommandLoader.ts:1-60]()\n\n## Extension UI Components\n\n### Extension List View\n\nThe CLI provides an interactive list view for browsing installed extensions:\n\n```typescript\n<Text color={theme.text.secondary}>\n  {t('{{count}} extensions installed', {\n    count: extensions.length.toString(),\n  })}\n</Text>\n```\n\nEach extension displays:\n- Name\n- Version\n- Active status (with color coding)\n- State indicator\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionListStep.tsx:1-50]()\n\n### Extension Detail View\n\nThe detail view shows comprehensive information about a selected extension:\n\n| Field | Display |\n|-------|---------|\n| Version | `{ext.version}` |\n| Status | Active string with color |\n| Path | Filesystem location |\n| Source | Installation source |\n| MCP Servers | Comma-separated list |\n| Commands | When available |\n\n资料来源：[packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx:1-70]()\n\n## Extension Settings Commands\n\nUsers can view and configure extension settings through the CLI:\n\n### Viewing Settings\n\n```bash\n/extensions settings <name>\n```\n\nThe command displays:\n- Current setting values\n- Scope where each setting is defined (user/workspace)\n- Sensitive value indicators for secure settings\n\n```typescript\nfor (const setting of extension.settings) {\n  const value = mergedSettings[setting.envVar];\n  let displayValue: string;\n  let scopeInfo = '';\n\n  if (workspaceSettings[setting.envVar] !== undefined) {\n    scopeInfo = ' ' + t('(workspace)');\n  } else if (userSettings[setting.envVar] !== undefined) {\n    scopeInfo = ' ' + t('(user)');\n  }\n\n  if (value === undefined) {\n    displayValue = t('[not set]');\n  } else if (setting.sensitive) {\n    displayValue = t('[value stored in keychain]');\n  }\n  // ...\n}\n```\n\n资料来源：[packages/cli/src/commands/extensions/settings.ts:60-100]()\n\n### Setting Storage\n\nExtension settings support sensitive data storage via keychain integration:\n\n| Setting Type | Storage Location |\n|--------------|------------------|\n| Sensitive | System keychain |\n| Non-sensitive | JSON config files |\n\n## Extension Documentation\n\nThe bundled `qc-helper` skill provides documentation references for extension development:\n\n| Topic | Documentation Path |\n|-------|-------------------|\n| Extension introduction | `docs/extension/introduction.md` |\n| Getting started | `docs/extension/getting-started-extensions.md` |\n| Releasing extensions | `docs/extension/extension-releasing.md` |\n\n资料来源：[packages/core/src/skills/bundled/qc-helper/SKILL.md:1-100]()\n\n## Security Considerations\n\nThe extension system implements several security measures:\n\n1. **XML Escaping**: Skill names and descriptions from extensions are escaped to prevent injection attacks in the model-facing XML blocks.\n\n2. **Scope Restrictions**: System and SystemDefaults scopes are not supported for extension management to prevent privilege escalation.\n\n3. **Keychain Storage**: Sensitive extension settings are stored in the system keychain rather than plaintext config files.\n\n4. **Validation Bypass Awareness**: The codebase notes that extension skills bypass the standard validator, requiring explicit escaping in the skill generation code.\n\n资料来源：[packages/core/src/extension/extensionManager.ts:10-30]()\n\n## Extension Workflow Summary\n\n```mermaid\ngraph TD\n    A[Install Extension] --> B[Load Extension Binary]\n    B --> C[Register MCP Servers]\n    C --> D[Register Skills]\n    D --> E[Enable Extension]\n    E --> F[Refresh Tools]\n    F --> G[Available to AI Model]\n    \n    H[User Configures] --> I[Write to Scope]\n    I --> J[Merge Settings]\n    J --> K[Apply to Extension]\n    \n    L[Disable Extension] --> M[Mark Inactive]\n    M --> N[Tools Unavailable]\n```\n\n## See Also\n\n- [Getting Started with Extensions](docs/extension/getting-started-extensions.md)\n- [Extension Releasing Guide](docs/extension/extension-releasing.md)\n- [Configuration System](../configuration/settings.md)\n- [MCP Server Integration](../mcp/index.md)\n- [Skills System](../skills/index.md)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：QwenLM/qwen-code\n\n摘要：发现 8 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | host_targets=claude, claude_code, chatgpt\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 6. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n\n## 7. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | issue_or_pr_quality=unknown\n\n## 8. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | release_recency=unknown\n\n<!-- canonical_name: QwenLM/qwen-code; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：QwenLM/qwen-code\n\n摘要：发现 8 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | host_targets=claude, claude_code, chatgpt\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 6. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | no_demo; severity=medium\n\n## 7. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | issue_or_pr_quality=unknown\n\n## 8. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | art_875e03abe4cc4cb58b4a8ef8603b8a0b | https://github.com/QwenLM/qwen-code#readme | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# qwen-code - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for QwenLM/qwen-code.\n\nProject:\n- Name: qwen-code\n- Repository: https://github.com/QwenLM/qwen-code\n- Summary: <div align=\"center\">\n- Host target: claude, claude_code, chatgpt\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: <div align=\"center\">\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. project-overview: Project Overview. Produce one small intermediate artifact and wait for confirmation.\n2. architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. agent-runtime: Core Agent Runtime. Produce one small intermediate artifact and wait for confirmation.\n4. turn-processing: Turn Processing and LLM Communication. Produce one small intermediate artifact and wait for confirmation.\n5. tools-system: Tools System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/QwenLM/qwen-code#readme\n- .qwen/skills/bugfix/SKILL.md\n- .qwen/skills/codegraph/SKILL.md\n- .qwen/skills/docs-audit-and-refresh/SKILL.md\n- .qwen/skills/docs-update-from-diff/SKILL.md\n- .qwen/skills/e2e-testing/SKILL.md\n- .qwen/skills/feat-dev/SKILL.md\n- .qwen/skills/qwen-code-claw/SKILL.md\n- .qwen/skills/structured-debugging/SKILL.md\n- .qwen/skills/terminal-capture/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：QwenLM/qwen-code\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm install -g @qwen-code/qwen-code@latest\n```\n\n来源：https://github.com/QwenLM/qwen-code#readme\n\n## 来源\n\n- docs: https://github.com/QwenLM/qwen-code#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_d750a4261ee247f2afff5933a37f8cf2"
}
