AI 与大模型 · 开源插件架构

Copilot Chat VS Code 插件架构

基于 2026-04-25 抓取的 microsoft/vscode-copilot-chat main 分支、VS Code AI Extension API 与官方开源说明,系统拆解 Copilot Chat 的 Chat Participant、Language Model Tool、ToolCallingLoop、Agent Mode、Subagent 与 MCP 扩展路径。

Repo: microsoft/vscode-copilot-chat License: MIT Snapshot: package 0.44.0 9 chat participants 37 languageModelTools

0. 真实边界

Copilot Chat 在 2025-06-30 的 VS Code 开源 AI 编辑器里程碑中被公开到 microsoft/vscode-copilot-chat。这次开源覆盖的是 VS Code 端扩展、prompt 渲染、工具注册、会话编排、UI 集成和大量测试代码;GitHub Copilot 的托管模型、账号鉴权、配额、服务端路由和推理基础设施仍是服务端能力,不在该仓库中。

本页把“源码可见的扩展客户端架构”和“服务端 Copilot/模型能力”分开讨论。凡是涉及具体类名、工具数量、participant 数量的地方,都来自本次抓取的仓库快照和 package.json;未来 main 分支更新后这些数字可能变化。

事实当前快照说明
扩展名copilot-chat / GitHub Copilot Chat由 GitHub 发布,仓库在 microsoft 组织下
运行环境VS Code ^1.115.0,Node >=22.14.0来自仓库 package.json
激活事件onStartupFinishedonLanguageModelChat:copilotonUriccreq/ccsettings 文件系统决定扩展何时进入 Extension Host
Chat Participants9 个默认 Copilot、编辑会话、agent、notebook、VS Code、terminal 等入口
Language Model Tools37 个代码搜索、文件读写、补丁、终端子代理、notebook、web、GitHub、memory 等

0.1 新增细化子页

如果需要逐项查看 9 个 Chat Participant、37 个 contributed Language Model Tools、内部 ToolName 映射、源码实现文件、prompt-tsx 装配和 ToolCallingLoop 状态机,请看子页:

Copilot Chat Agent / Tool / Prompt 源码细节 →

1. 源码目录到职责的映射

package.json

声明 activationEvents、enabledApiProposals、chatParticipants、languageModelTools、commands、settings。它是 VS Code 把扩展接进工作台的入口清单。

conversation/vscode-node/chatParticipants.ts

vscode.chat.createChatParticipant 注册各个 Chat Participant,并把 participant、slash command 和默认 intent 绑定起来。

prompt/node/chatParticipantRequestHandler.ts

处理一次 ChatRequest:清理 ignored 文件变量、恢复历史会话、推断 location、选择 intent,并交给默认请求处理器。

prompt/node/defaultIntentRequestHandler.ts

执行 intent、处理 confirmation、运行 start hooks 与 UserPromptSubmit hooks,创建 DefaultToolCallingLoop。

intents/node/toolCallingLoop.ts

核心 agent 循环:构建 prompt、发送模型请求、收集 tool call、记录 transcript、处理 Stop/SubagentStop hooks、autopilot 和 task_complete。

tools/vscode-node/tools*.ts

把内部工具注册到 VS Code LM Tool API,核心路径是 vscode.lm.registerToolvscode.lm.invokeTool

tools/node/*.ts(x)

具体工具实现:读文件、搜索、应用补丁、替换字符串、notebook、web page、memory、subagent、GitHub repo 等。

prompts/node/agent

基于 @vscode/prompt-tsx 拼装 agent prompt,并针对不同模型家族提供 prompt customizations。

mcp/vscode-node

MCP tool calling loop,把 MCP server 暴露的工具接入同一套工具调用与 prompt 编排体系。

2. 总体架构图

VS Code Workbench
  |
  | Chat UI / Inline Chat / Edit Session / Terminal Chat / Notebook Chat
  v
Extension Host: copilot-chat
  |
  +-- Contribution manifest
  |     +-- 9 chatParticipants
  |     +-- 37 languageModelTools
  |     +-- commands, settings, menus, proposed APIs
  |
  +-- Conversation layer
  |     +-- ChatAgentService
  |     +-- ChatParticipantRequestHandler
  |     +-- IntentDetector / IntentService
  |
  +-- Agent orchestration layer
  |     +-- DefaultIntentRequestHandler
  |     +-- DefaultToolCallingLoop
  |     +-- PromptRenderer / prompt-tsx
  |     +-- Hooks and transcript services
  |
  +-- Tool layer
  |     +-- ToolsContribution registers tools
  |     +-- ToolsService filters and invokes tools
  |     +-- file/search/edit/notebook/web/github/memory/subagent tools
  |
  +-- Endpoint and platform layer
        +-- Copilot auth, endpoint provider, quota handling, telemetry
        +-- VS Code APIs: chat, lm, workspace, terminal, notebook, scm
        +-- GitHub Copilot hosted model/service

这个架构和普通 VS Code 扩展的差别在于:它不是只注册命令或视图,而是把 VS Code Chat API、Language Model API、Language Model Tool API、文件系统、终端、notebook、GitHub 服务和 MCP 统一到一个 agent loop 里。

3. Chat Participant 到 Intent 的流程图

User selects chat surface
  |
  +-- default Copilot chat
  +-- edit session / inline chat
  +-- agent mode
  +-- notebook chat
  +-- @vscode participant
  +-- @terminal participant
  |
  v
vscode.chat.createChatParticipant handler
  |
  +-- switch model if quota/rate-limit policy requires it
  +-- start interaction telemetry
  +-- categorize first prompt
  +-- map participant and command to Intent
  |
  v
ChatParticipantRequestHandler
  |
  +-- sanitize ignored file references
  +-- rebuild Conversation from VS Code history
  +-- infer editor/notebook/panel/terminal location
  +-- choose command or detected intent
  |
  v
DefaultIntentRequestHandler
  |
  +-- intent.invoke builds an invocation object
  +-- confirmation handler may pause the flow
  +-- hooks may add context or block
  +-- DefaultToolCallingLoop starts

4. ToolCallingLoop 时序图

User          ChatParticipant        Intent Handler        ToolCallingLoop        Endpoint / Model        ToolsService
 |                  |                       |                     |                    |                   |
 | prompt           |                       |                     |                    |                   |
 |----------------->| create handler        |                     |                    |                   |
 |                  |---------------------->| select intent       |                    |                   |
 |                  |                       |-------------------->| runStartHooks      |                   |
 |                  |                       |                     | build prompt       |                   |
 |                  |                       |                     |------------------->| messages + tools  |
 |                  |                       |                     |<-------------------| stream response   |
 |                  |                       |                     | collect tool calls |                   |
 |                  |                       |                     |--------------------------------------->| invoke tool
 |                  |                       |                     |<---------------------------------------| result/error
 |                  |                       |                     | append result      |                   |
 |                  |                       |                     |------------------->| next model turn   |
 |<-----------------| stream markdown/edits/progress/confirmations |                    |                   |

源码里的 ToolCallingLoop 是一个抽象基类,真正的 prompt 构建由各 intent 或子循环实现。默认循环会反复执行 runOne:拿到可用工具、构建 prompt、计算 token、向 endpoint 发请求、处理流式输出、记录 tool call round,再决定继续还是停止。

5. 工具体系:37 个 Language Model Tools

本次快照中 package.json 贡献了 37 个 languageModelTools。这些工具不是随便暴露给模型的函数列表,而是同时包含显示名、用户说明、模型说明、输入 schema、when 条件和 tags。运行时还会通过工具选择器、配置、模型能力、MCP 来源和 endpoint override 再过滤一次。

类别工具用途
代码上下文copilot_searchCodebase, search_subagent, copilot_searchWorkspaceSymbols, copilot_findFiles, copilot_findTextInFiles语义搜索、快速探索、符号搜索、文件名和文本搜索
文件读取和诊断copilot_readFile, copilot_listDirectory, copilot_readProjectStructure, copilot_getErrors, copilot_getChangedFiles, copilot_testFailure, copilot_findTestFiles构建工作区视图、读取代码、收集错误和测试失败上下文
编辑copilot_applyPatch, copilot_insertEdit, copilot_createFile, copilot_createDirectory, copilot_replaceString, copilot_multiReplaceString, copilot_editFiles补丁、插入、创建文件/目录、字符串替换和多文件编辑
执行和环境execution_subagent, copilot_runVscodeCommand, copilot_installExtension, copilot_createNewWorkspace, copilot_getProjectSetupInfo运行命令、调用 VS Code 命令、安装扩展、创建新工程或获取项目搭建信息
Notebook / Web / GitHubcopilot_createNewJupyterNotebook, copilot_editNotebook, copilot_runNotebookCell, copilot_getNotebookSummary, copilot_readNotebookCellOutput, copilot_fetchWebPage, copilot_githubRepoJupyter 工作流、网页抓取和 GitHub 仓库上下文
Agent / Memory / Misccopilot_switchAgent, copilot_memory, copilot_resolveMemoryFileUri, copilot_viewImage, copilot_getVSCodeAPI, copilot_getSearchResults切换 agent、记忆读写、图像查看、VS Code API 文档和搜索面板结果

6. Tool 生命周期状态图

Declared in package.json or dynamic registry
  |
  v
Registered with vscode.lm.registerTool
  |
  v
Visible in vscode.lm.tools
  |
  +-- disabled by config / tool picker / model capability --> Hidden
  |
  v
Offered to model in request tool definitions
  |
  v
Model emits tool call
  |
  v
prepareInvocation builds user-visible message
  |
  +-- needs approval --> waiting for VS Code confirmation
  |
  v
ToolsService.invokeTool
  |
  +-- trace and telemetry span starts
  +-- arguments captured for debug panel
  +-- vscode.lm.invokeTool dispatches implementation
  |
  v
LanguageModelToolResult
  |
  +-- text / prompt-tsx / binary data parts
  +-- transcript and toolCallRounds updated
  |
  v
Next model turn receives tool result

Copilot Chat 的工具层有一个关键细节:扩展内部用 ToolName 管理工具名,但贡献给 VS Code 时会转换为带前缀的 contributed tool name;模型和 UI 看到的是“可调用工具”,实现仍由扩展自己的工具类承接。

7. Agent Mode、Autopilot 和 Subagent

Agent Mode

github.copilot.editsAgent 对应 agent 入口,默认 intent 是 Agent。它把编辑、搜索、诊断、终端和记忆工具放进一个长循环,让模型可以连续行动。

Autopilot

源码中 permissionLevel === 'autopilot' 会确保 task_complete 工具存在。如果模型停止但没有明确完成,内部 stop hook 会提示它继续;工具调用上限可被自动扩展,硬上限为 200。

Execution Subagent

execution_subagent 会创建独立 ExecutionSubagentToolCallingLoop、独立 invocation id 和过滤后的输出流;它的可用工具白名单只保留终端执行工具,用于运行测试、安装依赖或分析命令输出。

Search Subagent

search_subagent 是面向代码库探索的轻量工具,package 描述要求它快速查找文件、模式和相关片段,把结果作为上下文注入给主 agent。

Complex agent task
  |
  +-- Main agent loop plans and edits
  |
  +-- search_subagent
  |     +-- explore files and symbols
  |     +-- return focused snippets
  |
  +-- execution_subagent
  |     +-- run tests or setup commands
  |     +-- summarize relevant output
  |
  +-- main loop integrates observations
  |
  +-- task_complete signals done in autopilot mode

8. Hooks、Transcript、Telemetry 与可观测性

ToolCallingLoopDefaultIntentRequestHandler 显式接入了 Hook 服务。源码中可见的生命周期包括 SessionStartUserPromptSubmitStopSubagentStartSubagentStop。这些 Hook 可以添加上下文,也可以 block,让 agent 在真正停止前处理额外要求。

它还维护 transcript、toolCallRounds、token usage、debug file logger 与 OpenTelemetry span。每次 agent invoke、每一轮 model turn、每个 tool call 都会进入可观测链路,这也是 VS Code Copilot Chat 能显示工具进度、调试面板和上下文窗口使用情况的工程基础。

9. MCP 和 VS Code AI API 的关系

VS Code 官方 AI Extension API 把能力拆成三类:Chat Participant 用于创建专属聊天入口,Language Model API 用于访问聊天模型,Language Model Tool API 用于注册模型可调用工具。Copilot Chat 同时使用这三类能力,并把 MCP 工具也纳入同一套 tool calling loop。

External MCP Server
  |
  +-- tools / resources / prompts
  |
  v
VS Code MCP integration
  |
  v
copilot-chat McpToolCallingLoop
  |
  v
LanguageModelToolInformation
  |
  v
ToolCallingLoop offers selected tools to model
  |
  v
Model calls MCP-backed tool through the same invocation path

10. 一次复杂修改的端到端流转

用户:修复测试失败并解释原因
  |
  v
Chat participant receives request
  |
  v
Intent detects agent/edit workflow
  |
  v
PromptRenderer builds model-specific prompt
  |
  v
ToolCallingLoop turn 0
  |
  +-- search_subagent explores failing area
  +-- readFile/listDirectory/getErrors collect precise context
  |
  v
ToolCallingLoop turn 1
  |
  +-- applyPatch or replaceString edits source/test
  +-- transcript records edited files and tool calls
  |
  v
ToolCallingLoop turn 2
  |
  +-- execution_subagent runs test command
  +-- relevant output returns as tool result
  |
  +-- if failed: loop continues with new observation
  +-- if passed: final markdown plus changed-file summary
  |
  v
VS Code renders markdown, edits, references, confirmations and usage

11. 关键结论

Copilot Chat 的核心不是单个 prompt。 真正的架构核心是 VS Code Chat Participant 接入点、Intent 分发、PromptRenderer、ToolCallingLoop 和 ToolsService 组成的闭环。
工具是第一等公民。 37 个工具带 schema、tags、when 条件、用户展示文案和模型说明;运行时还会被权限、配置、模型能力和工具选择器过滤。
Agent Mode 是有状态编排。 它维护轮次、工具结果、transcript、hooks、token 统计、停止条件和 autopilot 完成信号,而不是把用户问题一次性发给模型。
开源边界清晰。 客户端扩展和编排代码可读;Copilot 服务端模型、路由、鉴权和配额仍是闭源服务。

资料来源