一个面向 .NET / C# 项目 的自主编码 Agent 骨架:能在隔离的工作区中完成"需求分析 → 编码 → 编译/测试验证"的闭环。
DotNetCodingAgent.sln
├── src/
│ ├── DotNetCodingAgent.Core // Agent 循环、工具/LLM/UI 抽象、消息模型
│ ├── DotNetCodingAgent.Llm // OpenAI 兼容协议的 LLM 客户端
│ ├── DotNetCodingAgent.Tools // 内置工具(文件、grep、dotnet build/test/cli)
│ └── DotNetCodingAgent.Cli // 控制台入口(Spectre.Console UI)
└── tests/
└── DotNetCodingAgent.Tests // xUnit + FluentAssertions
- ReAct 循环:
AgentLoop反复"调用 LLM → 执行工具 → 把结果回灌到对话",直到 LLM 给出无工具调用的最终回答或达到MaxIterations。 - 工具即接口:
IAgentTool自描述 name / description / JSON Schema,新增工具只需实现接口并在ToolRegistrationExtensions注册。 - 沙箱:
WorkspaceHelper.ResolveSafePath阻止跳出工作区根;AgentContext.RequireConfirmationForRiskyOps控制写/删除/Shell 是否需要二次确认。 - OpenAI 兼容:
OpenAiLlmClient走chat/completions+tools,Azure OpenAI / DeepSeek / vLLM / Ollama-compat 都可直接接入,只需改Endpoint。 - 可替换 UI:
IUserInterface当前由SpectreConsoleUi实现;后续可换 Web / IDE 插件。
| 工具 | 作用 | 风险 |
|---|---|---|
read_file |
读取工作区文本文件 | 低 |
write_file |
写入/覆盖文件 | 高 |
list_directory |
列目录 | 低 |
grep_search |
正则搜索 | 低 |
dotnet |
执行任意 dotnet 子命令 | 高 |
dotnet_build |
编译并解析错误 | 低 |
dotnet_test |
运行测试并解析失败 | 低 |
# 1. 还原 + 构建 dotnet restore dotnet build # 2. 配置 LLM(推荐用 user-secrets 或 Local 文件,避免提交密钥) cd src/DotNetCodingAgent.Cli dotnet user-secrets init dotnet user-secrets set "Llm:ApiKey" "sk-..." # 或者:复制 appsettings.json -> appsettings.Local.json 后填写 # 3. 运行 dotnet run # 4. 在 REPL 中输入需求,例如: # > 在工作区创建一个名为 TodoApi 的最小 Web API,提供 /todos GET/POST,并跑通 dotnet build 和一个 xUnit 测试。
环境变量可用 DNAGENT_ 前缀覆盖任何配置,例如:
$env:DNAGENT_Llm__ApiKey = "sk-..." $env:DNAGENT_Llm__Model = "gpt-4o"
dotnet test
- Roslyn 工具:基于
Microsoft.CodeAnalysis提供符号查找、引用搜索、代码修复(tools/Roslyn目录已预留依赖)。 - 流式输出:
OpenAiLlmClient改用 SSE 流式 + 增量渲染。 - 记忆/向量库:把项目摘要/历史决策存入 SQLite + Embedding,按需召回。
- 任务规划器:在
Core中加入IPlanner,实现 plan → step → verify 的显式分解。 - VS Code 扩展宿主:替换
IUserInterface即可把同一套 Agent 嵌入 IDE。