Agent 智能体开发实战 · 第五课:Mini-Cursor —— 手写 AI 编程 Agent 终极实战

📅 2026/7/12 18:17:15
Agent 智能体开发实战 · 第五课:Mini-Cursor —— 手写 AI 编程 Agent 终极实战
上节回顾第四课我们打造了完整的四工具模块化工具箱all-tools.mjs覆盖了读、写、列、执行四个核心能力。本课聚焦把工具箱接入一个完整的 Agent 主程序用ReAct 循环 安全护栏 工程化细节从零手写一个能真正干活的小型 AI 编程 Agent ——Mini-Cursor。 本课目录一、什么是 Mini-Cursor二、架构全景图三、Agent 主程序逐层拆解四、实战Agent 如何生成 React TodoList 项目五、工程化精要六、本课学习总结一、什么是 Mini-Cursor 定位Mini-Cursor是五节课的集大成者——把前四课的所有能力串联成一个可独立运行的 AI 编程 Agent第一课 Tool 定义 ──┐ 第二课 Agent Loop ──┤ 第三课 CLI Tool ──┼──▶ Mini-Cursor 第四课工具箱 第五课主程序 第四课 完整工具集 ──┘更直白地说运行mini-cursor.mjs它会自动调用all-tools.mjs里的四个工具在大约 10-15 轮 ReAct 循环后在hello-langchain/react-todo-app/下生成一个完整可运行的 React TodoList 项目。 与 Cursor/Trae 的关系特性Mini-CursorCursor / TraeLLM 推理✅ DeepSeek✅ GPT/Claude文件读写✅ read write✅ 完整 IDE 集成命令执行✅ spawn✅ 终端集成项目结构感知✅ list_directory✅ 文件树多文件编辑✅ 循环多次✅ diff apply代码补全❌✅ 内置GUI 界面❌✅ VS Code / IDE Mini-Cursor 去掉 GUI 和高级功能保留了 AI 编程 Agent 最核心的本质LLM 思考 工具执行 循环反馈。二、架构全景图┌──────────────────────────────────────────────────────────┐ │ Mini-Cursor │ │ │ │ ┌────────────┐ ┌────────────────┐ ┌────────────┐ │ │ │ LLM │ │ runAgentWith │ │ all-tools │ │ │ │ deepseek │◄──►│ Tools() │◄──►│ .mjs │ │ │ │ v4-pro │ │ 主循环函数 │ │ 工具箱 │ │ │ └────────────┘ └────────────────┘ └────────────┘ │ │ │ │ │ │ │ ┌────────┼─────┐ │ │ │ │ │ │ │ │ │ read ✍️write list ️exec│ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ │ │ chalk 彩色输出 node:fs node:child │ │ .promises _process │ └──────────────────────────────────────────────────────────┘ 文件关系src/ ├── all-tools.mjs ← 第四课产物四工具模块 └── mini-cursor.mjs ← 本课产物Agent 主程序 mini-cursor.mjs ──import──▶ all-tools.mjs │ └── runAgentWithTools(case1) ──▶ 生成 react-todo-app/三、Agent 主程序逐层拆解️ Layer 1依赖导入与 LLM 初始化// 手写 mini-cursor// 使用 vite 基于 react 创建 todolist 项目帮我跑起来// 给我目录列表// 编程 Agent 自动化importdotenv/config;import{ChatOpenAI}fromlangchain/openai;import{HumanMessage,SystemMessage,ToolMessage}fromlangchain/core/messages;import{executeCommandTool,readFileTool,writeFileTool,listDirectoryTool}from./all-tools.mjs;importchalkfromchalk;// 颜色输出 突出重点依赖来源作用dotenv/confignpm加载.env环境变量ChatOpenAIlangchain/openaiLLM 统一接口{Human, System, Tool}Messagelangchain/core消息角色{四工具}./all-tools.mjs工具箱模块chalknpm 彩色终端输出突出重点constmodelnewChatOpenAI({modelName:deepseek-v4-pro,// ⬆️ 升级pro 模型编程能力更强apiKey:process.env.DEEPSEEK_API_KEY,temperature:0,configuration:{baseURL:https://api.deepseek.com/v1,},});consttools[readFileTool,writeFileTool,listDirectoryTool,executeCommandTool]// lang chain链constmodelWithToolsmodel.bindTools(tools);为什么用deepseek-v4-proMini-Cursor 需要 LLM 生成大量 React 代码编程任务对模型能力要求高pro 模型比 flash 更适合。️ Layer 2任务 Promptcase1constcase1创建一个功能丰富的 React TodoList 应用 1. 创建项目 echo -e n\nn | pnpm create vite react-todo-app --template react-ts 2. 修改 src/App.tsx实现完整功能的 TodoList: - 添加、删除、标记完成 - 分类筛选全部/进行中/已完成 - 统计信息显示 - localStorage 数据持久化 3. 添加复杂样式 - 渐变背景蓝到紫 - 卡片阴影圆角 - 悬停效果 4. 添加动画 - 添加/删除时的过渡动画 - 使用 css transitions 5. 列出目录确定 注意 使用 pnpm功能要完整样式要美观要有动画效果 之后 react-todo-app 项目中 1. 使用 pnpm install 安装依赖 2. 使用 pnpm run dev 启动服务器 这个 Prompt 是一个完整的编程任务规格书涵盖了项目创建、代码实现、样式设计、运行验证四个阶段。LLM 需要自己规划步骤、调用工具、逐步完成。️ Layer 3核心 Agent 执行函数// Agent 执行函数 ReActasyncfunctionrunAgentWithTools(query,maxIterations30){constmessages[newSystemMessage(你是一个项目管理助手使用工具完成任务。 当前工作目录:${process.cwd()}工具: 1. read_file: 读取文件 2. write_file: 写入文件 3. execute_command: 执行命令支持 workingDirectory 参数 4. list_directory: 列出目录 重要规则 - execute_command - workingDirectory 参数会自动切换到指定目录 - 当使用 workingDirectory 时绝对不要在 command 中使用 cd - 错误示例: { command: cd react-todo-app pnpm install, workingDirectory: react-todo-app } 这是错误的因为 workingDirectory 已经在 react-todo-app 目录了再 cd react-todo-app 会找不到目录 - 正确示例: { command: pnpm install, workingDirectory: react-todo-app } 这样就对了workingDirectory 已经切换到 react-todo-app直接执行命令即可 回复要简洁只说做了什么),newHumanMessage(query)]; SystemMessage 的两个关键设计设计说明当前工作目录: ${process.cwd()}告知 LLM 它在哪个目录下操作避免路径混乱⚠️workingDirectory规则防止 LLM 犯典型错误在 workingDirectory 里重复 cd导致路径叠加找不到目录 这就是写 Agent 的经验——在 System Prompt 里提前埋好防坑规则比事后修 bug 高效得多。// ReAct 循环是 Agent 执行流程for(leti0;imaxIterations;i){console.log(chalk.bgGreen(正在等待第${i}次 AI 思考...))constresponseawaitmodelWithTools.invoke(messages);messages.push(response);if(!response.tool_calls||response.tool_calls.length0){console.log(\n: AI 最终回复\n${response.content}\n);returnresponse.content}for(consttoolCallofresponse.tool_calls){constfoundTooltools.find(tt.nametoolCall.name);if(foundTool){consttoolResultawaitfoundTool.invoke(toolCall.args)messages.push(newToolMessage({content:toolResult,tool_call_id:toolCall.id}))}}}returnmessages[messages.length-1].content} for vs while本课用for而非while因为maxIterations 30提供了硬性兜底对比项whilefor退出条件LLM 不返回 tool_callsLLM 不返回 tool_calls或达到最大次数安全性可能无限循环maxIterations硬性兜底适用场景简单任务1-2轮复杂工程任务10轮️安全护栏任务复杂时 Agent 可能反复调用工具陷入循环maxIterations确保最多 30 轮就会停止不会无限烧 token。️ Layer 4执行入口 超时兜底try{awaitrunAgentWithTools(case1);}catch(err){console.error(\n 错误${err.message});}// ⏰ 超时兜底强制退出进程setTimeout((){console.log(⏰ 超时兜底强制退出进程);process.exit(0);},1000000);防护层机制作用️ 第一层maxIterations 30防止无限循环️ 第二层try-catch捕获未预期的异常️ 第三层setTimeout超时退出兜底1,000,000ms约16分钟后强制退出进程三重安全护栏是工程级 Agent 的标配——Agent 运行在服务器上时不能因为任何原因卡死。四、实战Agent 如何生成 React TodoList 项目 执行过程还原当runAgentWithTools(case1)运行时Agent 经历了约10-15 轮ReAct 循环 Mini-Cursor 启动 │ ├── Round 1-2 ️ 创建项目 │ REASON: 需要先创建 Vite 项目骨架 │ ACT: execute_command echo -e n\nn | pnpm create vite react-todo-app --template react-ts │ OBSERVE: ✅ 项目创建成功 │ ├── Round 3 了解项目结构 │ REASON: 查看 react-todo-app/src 下有哪些文件 │ ACT: list_directory react-todo-app/src │ OBSERVE: App.tsx, main.tsx, index.css ... │ ├── Round 4 读取现有代码 │ REASON: 了解 App.tsx 现有内容准备修改 │ ACT: read_file react-todo-app/src/App.tsx │ OBSERVE: 当前是默认的 Vite 模板代码 │ ├── Round 5-6 ✍️ 写入 TodoList 组件 │ REASON: 生成完整的 TodoList React 组件代码 │ ACT: write_file react-todo-app/src/App.tsx (200 行代码) │ OBSERVE: ✅ 成功写入 │ ├── Round 7 ✍️ 写入样式文件 │ REASON: 添加渐变背景、卡片阴影、动画效果 │ ACT: write_file react-todo-app/src/index.css (样式代码) │ OBSERVE: ✅ 成功写入 │ ├── Round 8 安装依赖 │ REASON: 项目需要安装依赖才能运行 │ ACT: execute_command pnpm install (workingDirectory: react-todo-app) │ OBSERVE: ✅ 依赖安装成功 │ ├── Round 9 启动开发服务器 │ REASON: 一切就绪启动项目 │ ACT: execute_command pnpm run dev (workingDirectory: react-todo-app) │ OBSERVE: ✅ VITE 启动在 http://localhost:5173/ │ ├── Round 10 最终确认 │ REASON: 列出最终目录结构确认所有文件就位 │ ACT: list_directory react-todo-app/src │ OBSERVE: App.tsx, index.css, main.tsx, ... 全部就位 │ └── ✅ 任务完成输出总结 工具调用统计工具调用次数典型用途️execute_command4-5 次创建项目、安装依赖、启动服务✍️write_file2-3 次写入组件代码、样式文件read_file1-2 次读取现有文件内容list_directory2-3 次了解目录结构、确认文件就位 生成的项目实锤hello-langchain/react-todo-app/目录真实存在它就是node src/mini-cursor.mjs跑出来的产物。Agent 在没有任何人工编写代码的情况下全自动生成了以下内容✅ Vite React TypeScript 项目骨架npm init vite创建✅ 完整的 TodoList 组件添加、删除、标记完成✅ 分类筛选全部 / 进行中 / 已完成✅ 统计信息显示共 X 项已完成 Y 项✅ localStorage 数据持久化刷新不丢失✅ 渐变背景蓝→紫 卡片阴影 圆角 悬停效果✅ CSS transitions 过渡动画添加/删除时平滑过渡✅ 依赖已安装pnpm install、开发服务器已启动pnpm run dev五、工程化精要 Mini-Cursor 的工程化要点要点实现位置 模块分离工具定义独立于 Agent 逻辑all-tools.mjs←mini-cursor.mjs 可视化反馈chalk 彩色输出chalk.bgGreen(...) 迭代上限maxIterations 30runAgentWithTools参数️ 异常兜底try-catch 超时setTimeout最外层 防坑规则Prompt EngineeringSystemMessage 中的workingDirectory规则 模型选型编程任务用 pro 模型deepseek-v4-pro 完整启动流程# 1. 确保 .env 配置了 DEEPSEEK_API_KEY# 2. 运行 Agentnodesrc/mini-cursor.mjs# 3. Agent 自动完成# - 创建 react-todo-app 项目# - 编写组件代码# - 安装依赖# - 启动开发服务器# 4. 浏览器打开 http://localhost:5173/ 查看成果六、本课学习总结 思维导图 Mini-Cursor · 知识全景 │ ├── ️ 架构全景 │ ├── LLMdeepseek-v4-pro │ ├── Agent 主循环runAgentWithTools() │ ├── 四工具工具箱all-tools.mjs │ └── 彩色输出chalk │ ├── ⚙️ 核心函数runAgentWithTools(query, maxIterations) │ ├── messages 初始化 │ │ ├── SystemMessage角色 规则 │ │ └── HumanMessage任务 │ ├── for 循环最多 maxIterations 轮 │ │ ├── LLM.invoke() → 推理 │ │ ├── 无 tool_calls → 返回最终结果 │ │ ├── 有 tool_calls → 遍历执行工具 │ │ └── ToolMessage → 喂回 LLM │ └── return 最终回复 │ ├── ️ 三重安全护栏 │ ├── ① maxIterations迭代上限防无限循环 │ ├── ② try-catch异常捕获防崩溃 │ └── ③ setTimeout超时退出防卡死 │ ├── SystemMessage 防坑规则 │ ├── 告知当前工作目录 │ ├── workingDirectory 参数说明 │ └── 禁止重复 cd避免路径叠加 │ ├── 实战React TodoList10 轮 ReAct │ ├── Round 1-2execute_command → 创建 Vite 项目 │ ├── Round 3list_directory → 了解项目结构 │ ├── Round 4read_file → 读取现有模板 │ ├── Round 5-6write_file → 写入组件代码 │ ├── Round 7write_file → 写入动画样式 │ ├── Round 8execute_command → pnpm install │ ├── Round 9execute_command → pnpm run dev │ └── Round 10list_directory → 最终确认 │ └── 工程化精要 ├── 模块分离all-tools.mjs ↔ mini-cursor.mjs ├── 可视化反馈chalk 彩色输出 ├── 迭代上限maxIterations 30 ├── 异常兜底try-catch ├── 防坑规则System Prompt 预设 └── 模型选型编程任务用 pro 模型✅ 知识清单编号掌握项核心要点1Mini-Cursor 架构LLM 四工具 ReAct Loop 安全护栏2runAgentWithTools函数通用 Agent 执行器接收 query 和 maxIterations3forvswhile循环for 可选代上限防止无限循环4System Prompt 防坑在提示词中预设规则如 workingDirectory 禁止 cd5chalk 彩色输出chalk.bgGreen(...)让终端反馈更直观6三重安全护栏maxIterations try-catch setTimeout7模型选型策略编程任务用 pro 模型简单查询用 flash8模块化导入import { 四工具 } from ./all-tools.mjs9Agent 完整执行流程10 轮 ReAct 循环4 个工具协同完成复杂任务 五课能力进化维度第一课第二课第三课第四课第五课核心能力Tool 定义Agent LoopCLI 执行完整工具集完整 Agent工具数量11244复用代码组织单文件单文件单文件模块化主从分离安全护栏无无无无三重防护工程成熟度★☆☆★★☆★★☆★★★★★★★Agent 完整度30%60%80%90%✅ 100% 五课总结Agent 学习全景Agent 学习路线图 第一课 第二课 第三课 Tool 定义 Agent Loop CLI Tool ───────── ───────── ───────── 给 LLM 装手 让循环转起来 操控命令行 │ │ │ └───────────────────┼───────────────────┘ │ ▼ 第四课完整工具集 ───────────────── 读 写 列 执行 模块化导出 │ ▼ 第五课Mini-Cursor ───────────────── AI 编程 Agent 终极实战 ️ 三重护栏 chalk ✅ 可独立运行的完整产品五课学完你已经掌握了用 LangChain 定义 Tool给 LLM 装上手用 ReAct 循环让 Agent 持续推理和执行用 child_process 让 Agent 操控命令行构建模块化的完整工具集整合所有能力手写一个能独立运行的 AI 编程 Agent从零到一Mini-Cursor 就是你的 Agent 开发毕业作品。 2026-07-10 | ️ Agent · Mini-Cursor · ReAct · AI编程 · 第五课 · 完结