Cline Prompt 设计分析

最近一直在使用 Cline 辅助编程,确实效果不错,比 Github Copilot 要强不少。Cline 提供的功能也非常强大,今天重点分析下它的 prompt 设计。

什么是 Cline

按照官方的解释:

Cline 是一个运行在 VS Code 中的 AI 编程助手,不仅能够跨多个文件进行读写、执行命令,还功能深层次的理解项目,执行复杂的重构任务。

以使用体验来看,Cline 不仅仅是一个 AI 编程助手,更像是一个 AI Agent,只是内置了很多编程相关的功能。除此之外,Cline 提供了很高的扩展性,用户可以通过自定义 Rule 来扩展系统 Prompt;定义 Workflow 来实现更复杂的任务处理;通过支持 MCP 协议,Cline 可以和本地或远程的 MCP 服务器进行交互,使用其提供的工具与资源。

Cline 工作流程架构

在深入分析 Cline 的 Prompt 设计之前,我们先通过架构图直观了解其完整的工作流程:

graph TB Start([用户任务输入
User Task Input]) --> Assemble[消息组装层
Message Assembly] Assemble --> |包含| UserReq[用户请求
User Request] Assemble --> |包含| SysPrompt[系统提示词
System Prompt] Assemble --> |包含| EnvCtx[环境上下文
Environment Context] UserReq -.-> Assemble SysPrompt -.-> Assemble EnvCtx -.-> Assemble Assemble --> ModeCheck{当前模式?
Current Mode} ModeCheck -->|PLAN MODE| PlanMode[PLAN MODE
规划模式] ModeCheck -->|ACT MODE| ActMode[ACT MODE
执行模式] %% PLAN MODE Flow PlanMode --> PlanExplore[信息收集
read_file, search_files
ask_followup_question] PlanExplore --> PlanAnalyze[分析与规划
Analyze & Plan] PlanAnalyze --> PlanRespond[呈现方案
plan_mode_respond] PlanRespond --> UserReview{用户审查
User Review} UserReview -->|需要修改| PlanExplore UserReview -->|批准| SwitchToAct[切换到 ACT MODE] SwitchToAct --> ActMode %% ACT MODE Flow ActMode --> ActAnalyze[任务分析
Task Analysis] ActAnalyze --> SetGoals[设定目标与成功标准
Set Goals & Success Criteria] SetGoals --> InitProgress[创建任务进度清单
Initialize task_progress] InitProgress --> SelectTool[选择工具
Tool Selection] SelectTool --> ToolExec[执行工具
Tool Execution] ToolExec --> |需要批准| ApprovalCheck{requires_approval?} ApprovalCheck -->|true| UserApproval{用户批准?} ApprovalCheck -->|false/auto-approve| ToolRun[运行工具
Run Tool] UserApproval -->|拒绝| SelectTool UserApproval -->|批准| ToolRun ToolRun --> ToolResult[获取工具结果
Tool Result] ToolResult --> UpdateProgress[更新进度
Update task_progress] UpdateProgress --> AnalyzeResult[分析结果
Analyze Result] AnalyzeResult --> TaskComplete{任务完成?
Task Complete?} TaskComplete -->|否| SelectTool TaskComplete -->|是| Completion[呈现结果
attempt_completion] Completion --> UserFeedback{用户反馈
User Feedback} UserFeedback -->|需要改进| SelectTool UserFeedback --> End([任务完成
Task Done]) %% Styling classDef planStyle fill:#E3F2FD,stroke:#90CAF9,stroke-width:2px classDef actStyle fill:#FFF8E1,stroke:#FFD54F,stroke-width:2px classDef toolStyle fill:#F3E5F5,stroke:#CE93D8,stroke-width:2px classDef decisionStyle fill:#FFEBEE,stroke:#EF9A9A,stroke-width:2px classDef resultStyle fill:#E8F5E9,stroke:#A5D6A7,stroke-width:2px class PlanMode,PlanExplore,PlanAnalyze,PlanRespond planStyle class ActMode,ActAnalyze,SetGoals,InitProgress,SelectTool actStyle class ToolExec,ToolRun,ToolResult toolStyle class ModeCheck,UserReview,ApprovalCheck,UserApproval,TaskComplete,UserFeedback decisionStyle class Completion,End resultStyle

架构图说明

该图展示了 Cline 从接收用户任务到完成任务的完整流程,主要包括:

  1. 消息组装层:整合用户请求、系统提示词和环境上下文
  2. 双模式工作流
    • PLAN MODE:规划阶段,收集信息并制定执行方案
    • ACT MODE:执行阶段,逐步使用工具完成任务
  3. 工具执行机制:单次调用、批准机制、结果分析
  4. 决策节点:模式选择、用户批准、任务完成判断
  5. 进度跟踪 :通过task_progress实时更新任务状态
  6. 完成状态:任务完成与结果呈现

Cline 的 Prompt 设计

Cline 的系统提示词是一个高度模块化的架构,支持多种 AI 模型和自定义配置。模版如下:

ts 复制代码
export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}}

{{${SystemPromptSection.TOOL_USE}}}

## {{${SystemPromptSection.TASK_PROGRESS}}}

## {{${SystemPromptSection.RULES}}}

## {{${SystemPromptSection.ACT_VS_PLAN}}}

## {{${SystemPromptSection.CLI_SUBAGENTS}}}

## {{${SystemPromptSection.CAPABILITIES}}}

## {{${SystemPromptSection.EDITING_FILES}}}

## {{${SystemPromptSection.TODO}}}

## {{${SystemPromptSection.MCP}}}

## {{${SystemPromptSection.SYSTEM_INFO}}}

## {{${SystemPromptSection.OBJECTIVE}}}

## {{${SystemPromptSection.USER_INSTRUCTIONS}}}`

为什么要使用模块化的 Prompt 设计?主要有以下几个好处:

  • 可维护性: 各个部分独立,便于更新和维护
  • 可扩展性: 不同 LLM 模型有不同的偏好和限制,模块化设计允许针对不同模型进行定制,比如 Claude 偏好 XML 格式,GLM 需要更简洁的指令
  • 灵活性: 具体启用的模块因模型变体与运行环境而异,某些段落(如 CLI_SUBAGENTS、TODO)可能被裁剪或由宿主环境动态注入

系统 Prompt 包含了角色定义、工具使用、任务处理、上下文管理等等,这些都是我们在设计 Agent 时必须定义的部分,除此之外还涉及到文件操作、用户自定义规则等。完整的系统 Prompt 包含以下核心部分:

  • AGENT_ROLE: 定义 Cline 的身份和能力
  • TOOL_USE: 工具使用规则和约定
  • TASK_PROGRESS: 任务进度跟踪
  • RULES: 操作规则和约束
  • ACT_VS_PLAN: ACT MODE 和 PLAN MODE 的区别
  • CAPABILITIES: 详细能力描述
  • EDITING_FILES: 文件编辑指南
  • MCP: Model Context Protocol 集成
  • OBJECTIVE: 任务执行处理的规范和流程
  • USER_INSTRUCTIONS: 用户自定义指令

Agent Role

AGENT_ROLE 用来定义 Cline 的身份和能力。以某个模型变体为例(GPT-5.1),角色定义如下:

You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.

注意:不同模型变体可能有不同的角色定义与能力描述。

Tool Use

TOOL_USE 部分定义了 Cline 可以使用的工具和命令,以 GPT-5.1 变体为例:

md 复制代码
You have access to a set of tools that are executed upon the user's approval. You can only use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.

## Tool-Calling Convention and Preambles

When switching domains or task_progress steps, you may want to provide a brief preamble explaining:

- **What tool** you are about to use
- **Why** you are using it (what problem it solves or what information it will provide)
- **What result** you expect from the tool call

Format: "Now that we have [very brief summary of last task_progress items that was completed], I will use [ToolName] to [specific action/goal]"

After receiving the tool result, briefly reflect on whether the result matches your expectations. If it doesn't, explain the discrepancy and adjust your approach accordingly. This improves transparency, accuracy, and helps you catch potential issues early.`

对于工具的使用有以下约定:

  • 每次只能使用一个工具
  • 潜在有副作用的操作(如写文件、执行命令、网络操作)需设置 requires_approval=true;安全的读取/查询类操作可设置为 false。用户可启用自动批准模式,此时安全操作会直接执行
  • 使用工具前说明使用目的和预期结果、使用后对结果进行反思是推荐的最佳实践,具体执行取决于模型变体与提示词覆盖

Task Progress

TASK_PROGRESS 用于跟踪任务进度和展示完成进度,通过 Checklist 格式来展示工具执行后的任务状态。

ts 复制代码
/**
 * Common parameter shared between tools for tracking task progress
 */
export const TASK_PROGRESS_PARAMETER = {
	name: "task_progress",
	required: false,
	instruction: `A checklist showing task progress after this tool use is completed. The task_progress parameter must be included as a separate parameter inside of the parent tool call, it must be separate from other parameters such as content, arguments, etc. (See 'UPDATING TASK PROGRESS' section for more details)`,
	usage: "Checklist here (optional)",
}

Rules

RULES 定义了 Cline 的操作规则和约束条件,比如在 GPT-5.1 变体中定义了执行命令、创建项目、输出格式等规范。主要规则包括:

md 复制代码
- The current working directory is \`{{CWD}}\` - this is the directory where all the tools will be executed from.
- When creating a new application from scratch, you must implement it locally and not use global packages or tools that are not part of the local project dependencies. For example, if npm couldn't create the Vite app because the global npm cache is owned by root, create the project using a local cache in the repo (no sudo required)
- After completing reasoning traces, provide a concise summary of your conclusions and next steps in the final response to the user. You should do this prior to tool calls.
- When responding to the user outside of tool calls, include rich markdown formatting where applicable.
- Ensure that any code snippets you provide are properly formatted with syntax highlighting for better readability.
- When performing regex searches, try to craft search patterns that will not return an excessive amount of results.

ACT MODE vs PLAN MODE

Cline 提供了两种工作模式:

  • ACT MODE : 执行模式,可以使用除 plan_mode_respond 外的所有工具来完成用户任务。每条消息只能调用一个工具,并需等待工具执行结果后再继续。任务完成后使用 attempt_completion 工具呈现结果。进度通过 task_progress 参数跟踪
  • PLAN MODE : 规划模式,主要使用 plan_mode_respond 与探索类工具(如 read_filesearch_files)收集信息并创建详细计划,与用户讨论方案,确认后切换到 ACT MODE 实施
md 复制代码
ACT MODE V.S. PLAN MODE

In each user message, the environment_details will specify the current mode. There are two modes:

- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_respond tool.
 - In ACT MODE, you can use the act_mode_respond tool to provide progress updates to the user without interrupting your workflow. Use this tool to explain what you're about to do before executing tools, or to provide updates during long-running tasks.
 - In ACT MODE, you use tools to accomplish the user's task. Once you've fully completed the user's task, you use the attempt_completion tool to present the result of the task to the user.

- PLAN MODE: In this special mode, you have access to the plan_mode_respond tool.
 - In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before switching to ACT MODE to implement the solution.
 - In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_respond tool to deliver your response directly.
 - In PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task.${context.yoloModeToggled !== true ? " You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task." : ""}
 - In PLAN MODE, Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
 - In PLAN MODE, once you have presented a plan to the user, you should request that the user switch you to ACT MODE so that you may proceed with implementation.

Objective

OBJECTIVE 定义了任务执行的总体目标和方法论,确保 Cline 在执行任务时有明确的方向,是执行任务的核心指南:

md 复制代码
OBJECTIVE

You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.

## Deliverables and Success Criteria

For every task, establish clear deliverables and success criteria at the outset:

- **Goal**: What specific feature, bug fix, or improvement are you delivering?
- **Deliverables**: What code changes, tests, documentation, or configuration updates will be produced?
- **Success Criteria**: How will you know when you're done? (e.g., code passes existing tests, follows domain-driven design boundaries, uses TypeScript conventions, integrates with existing Git-based checkpoint workflow)
- **Constraints**: What are the technical, architectural, or project-specific constraints? (e.g., must not modify core interfaces, must maintain backward compatibility, must follow existing patterns)

Report progress via task_progress parameter throughout the task to maintain visibility into what's been accomplished and what remains.

## Context Boundaries and Clarification

When working in a codebase:

- Always reference the **relevant module/file path** and **domain concept** before proposing or making edits
- Track context across files, modules, and feature boundaries to ensure changes are coherent
- If task scope is ambiguous, existing architecture is unclear, or constraints are undefined, ${context.yoloModeToggled !== true ? "**ask clarifying questions** using ask_followup_question rather than making assumptions" : "state your assumptions clearly before proceeding"}
- When in doubt about existing patterns, conventions, or dependencies, **investigate first** using read_file and search_files before making changes

This ensures your work aligns with the existing codebase structure and avoids unintended side effects.

## Implementation Workflow

1. **Analyze the user's task** and establish deliverables, success criteria, and constraints (as above). Prioritize goals in a logical order.

2. **Work through goals sequentially**, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go. 
   
   **IMPORTANT: In ACT MODE, make use of the act_mode_respond tool when switching domains or task_progress steps to keep the conversation informative:**
   - ALWAYS use act_mode_respond when switching domains or task_progress steps to briefly explain your progress and intended changes
   - Use act_mode_respond when starting a new logical phase of work (e.g., moving from backend to frontend, or from one feature to another)
   - Use act_mode_respond during long sequences of operations to provide progress updates
   - Use act_mode_respond to explain your reasoning when changing approaches or encountering issues/mistakes
   
   This tool is non-blocking, so using it frequently improves user experience and ensures long tasks are completed successfully.

   Additionally, you MUST NOT call act_mode_respond more than once in a row. After using act_mode_respond, your next assistant message MUST either call a different tool or perform additional work without using act_mode_respond again. If you attempt to call act_mode_respond consecutively, the tool call will fail with an explicit error and you must choose a different action instead.

3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params)${context.yoloModeToggled !== true ? " and instead, ask the user to provide the missing parameters using the ask_followup_question tool" : ""}. DO NOT ask for more information on optional parameters if it is not provided.

4. **Code Generation Self-Review Loop**: After generating code, evaluate against an internal quality rubric using your reasoning:
   - **Readability**: Is the code clear, well-named, and easy to understand?
   - **Modularity**: Are concerns properly separated? Is the code DRY (Don't Repeat Yourself)?
   - **Testability**: Can this code be easily tested? Are dependencies injectable?
   - **Domain Alignment**: Does it respect domain-driven design boundaries and follow existing architectural patterns?
   - **Best Practices**: Does it follow language idioms, framework conventions, and project standards?
   
   If issues are found during this self-review, refine the code and present the improved version. Mention what you improved and why.

5. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.

6. If the task is not actionable, you may use the attempt_completion tool to explain to the user why the task cannot be completed, or provide a simple answer if that is what the user is looking for.

在执行任务时,Cline 会遵循上述工作流程。当接收到用户请求后,Cline 会生成任务目标、完成标准,然后拆分任务,逐步使用工具完成任务(每次只调用一个工具并等待结果),最后通过 attempt_completion 工具向用户展示结果。这是一个典型的 Plan & Execute Agent 流程。

其他核心部分

  • CAPABILITIES: 详细描述 Cline 的能力,包括文件操作、命令执行、浏览器交互、MCP 服务器集成等
  • EDITING_FILES : 提供 write_to_filereplace_in_file 两种文件编辑工具以及使用方法。小范围修改优先使用 replace_in_file(需精确匹配完整行),大范围修改或新建文件使用 write_to_file。注意自动格式化可能影响 SEARCH 块的精确匹配
  • MCP: 除了内置的基础工具,Cline 也支持 Model Context Protocol 协议,允许与本地或远程的 MCP 服务器通信,使用其提供的工具与资源,这极大扩展了 Cline 的能力
  • USER_INSTRUCTIONS : 用户可以通过自定义指令(仓库内的 .clinerules 或全局 Rules)来扩展或修改系统行为。仓库内规则通常优先于全局规则,多层规则会被合并,最终生效的系统提示词由变体与环境共同决定

示例

我们来实际看一个简单的 Task,输入获取北京的最近一周的天气,输出到文件

  1. 首先 Cline 会将用户请求、系统提示词、运行时上下文等信息打包成消息发送给模型
json 复制代码
{
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "<task>获取北京的最近一周的天气,输出到文件</task>"
            },
            {
                "type": "text",
                "text": "Prompt..."
            },
            {
                "type": "text",
                "text": "Environment Details: {...}"
            }
        ]
}

系统 Prompt 示例如下(实际内容因模型变体而异):

md 复制代码
# task_progress RECOMMENDED

When starting a new task, it is recommended to include a todo list using the task_progress parameter.


1. Include a todo list using the task_progress parameter in your next tool call
2. Create a comprehensive checklist of all steps needed
3. Use markdown format: - [ ] for incomplete, - [x] for complete

**Benefits of creating a todo/task_progress list now:**
	- Clear roadmap for implementation
	- Progress tracking throughout the task
	- Nothing gets forgotten or missed
	- Users can see, monitor, and edit the plan

**Example structure:**```
- [ ] Analyze requirements
- [ ] Set up necessary files
- [ ] Implement main functionality
- [ ] Handle edge cases
- [ ] Test the implementation
- [ ] Verify results```

Keeping the task_progress list updated helps track progress and ensures nothing is missed.


<environment_details>
# Visual Studio Code Visible Files

# Visual Studio Code Open Tabs

# Current Time
12/3/2025, 11:42:01 AM (UTC, UTC+0:00)

# Current Working Directory
...

# Detected CLI Tools
These are some of the tools on the user's machine, and may be useful if needed to accomplish the task: gh, git, docker, podman, kubectl, go, curl, jq, make, python, code, grep, sed, awk, helm, wget. This list is not exhaustive, and other tools may be available.

# Current Mode
ACT MODE
</environment_details>

可以看到 Cline 会建议创建一个任务进度列表,帮助跟踪任务完成情况。需要注意的是,environment_details 是运行时上下文,由宿主系统自动注入,并非系统 Prompt 的固有段落,但它可能影响命令路径、工具选择与模型行为。

  1. Assistant 收到消息后,结合系统 Prompt 和上下文,生成响应内容,决定使用哪些工具来完成任务:
xml 复制代码
Model: Claude 4.5 Sonnet

I'll help you fetch the weather forecast for Beijing for the next week and save it to a file. Let me break this down into steps.

<thinking>
The user wants to:
1. Get weather forecast for Beijing for the next week
2. Save the output to a file

I need to:
1. Find a way to get weather data for Beijing
2. Save the result to a file

I can use curl to fetch weather data from a free weather API. One good option is wttr.in which provides weather information in a simple format. I can also try using a weather API if available.

Let me first check if there are any MCP tools available that might help with weather data. Looking at the environment details, I can see there's a dod-assistant MCP server, but it's for JIRA tickets and HanaCloud questions, not weather data.

I'll use curl with wttr.in service which provides weather forecasts. The command would be:
- curl wttr.in/Beijing to get weather for Beijing

Then I'll save the output to a file.
</thinking>

I'll fetch the weather forecast for Beijing for the next week and save it to a file.

<execute_command>
<command>curl -s "wttr.in/Beijing?format=j1" > beijing_weather.json && curl -s "wttr.in/Beijing?lang=zh-cn" > beijing_weather.txt</command>
<requires_approval>false</requires_approval>
<task_progress>
- [x] Fetch weather data for Beijing
- [ ] Verify the data was saved correctly
- [ ] Format and present the results
</task_progress>
</execute_command>

在第二步生成了任务计划,并使用execute_command工具获取天气数据,并保存到文件中,同时更新了任务进度。

  1. 工具执行后,Assistant 会收到工具调用结果,然后必须等待并分析结果 后再继续执行后续步骤,最终通过 attempt_completion 工具将结果返回给用户。
xml 复制代码
[execute_command for 'curl -s "wttr.in/Beijing?format=j1" > beijing_weather.json && curl -s "wttr.in/Beijing?lang=zh-cn" > beijing_weather.txt'] Result:
Command executed.
Output:
The command's output could not be captured due to some technical issue, however it has been executed successfully. Here's the current terminal's content to help you get the command's output:

➜ curl -s "wttr.in/Beijing?format=j1" > beijing_weather.json && curl -s "wttr.in/Beijing?lang=zh-cn" > beijing_weather.txt

<environment_details>
...
</environment_details>

后续会调用其他工具来验证文件内容,最后通过attempt_completion工具将结果返回给用户。至此,一个完整的任务执行流程结束。

对比上面完整的 Prompt 模板,示例中的 Prompt 省略了很多部分,这与使用的具体模型有关。不同模型会裁剪或增强不同的功能模块,对应的 Prompt 部分也会相应调整。

总结

Cline 通过精心设计的系统提示词,实现了一个强大而灵活的 AI 编程助手。其模块化的架构使得系统易于扩展和维护,同时通过 MCP 协议提供了与本地或远程工具的集成能力。

通过分析 Cline 的 Prompt 设计,我们可以学到以下几点:

  1. 模块化设计:将系统提示词分解为独立模块,便于针对不同模型变体进行定制
  2. 严格的工具使用规范:每次只调用一个工具、等待结果、明确批准机制,确保任务执行的可靠性
  3. 双模式工作流:Plan Mode 用于规划,Act Mode 用于执行,实现了典型的 Plan & Execute Agent 模式
  4. 进度跟踪机制 :通过 task_progress 参数实时展示任务完成情况
  5. 高扩展性:通过 MCP 协议与用户自定义规则,可以灵活扩展系统能力

这些设计原则对构建高效的 AI Agent 系统具有重要的参考价值,当前大模型在指令遵循、意图理解方面已有显著提升,结合合理的 Prompt 设计与工具集成,能够实现更复杂的任务处理。

Explore more in qingwave.github.io

相关推荐
Learn-Share_HY15 天前
[Python]如何用uv套件建置python專案與虛擬環境?
python·ai·virtualenv·uv·server·mcp·cline
不老刘21 天前
使用 Docker Compose 一键更新:深入理解 docker-compose pull 的适用场景
docker·容器·eureka·cline
听吉米讲故事3 个月前
开源AI编程工具Kilo Code的深度分析:与Cline和Roo Code的全面对比
开源·ai编程·cline·roo code·kilo code
candyTong4 个月前
Cline 的检查点/工作区快照是如何实现的
openai·cline
AlfredZhao4 个月前
SQLcl:不仅是 SQL*Plus 的继任者,更是 AI 时代的连接器
vscode·server·mcp·cline·sqlcl
ZackSock6 个月前
Cline 如何调用自己的 MCP 服务器
mcp·cline
SleepyZone6 个月前
Cline 源码浅析 - Prompt 设计
ai编程·cline
SleepyZone6 个月前
Cline 源码浅析 - 从输入到输出
前端·ai编程·cline
BIBI20496 个月前
VsCode 安装 Cline 插件并使用免费模型(例如 DeepSeek)
vscode·deepseek·cline