循环没变,只是多了工具
用 Map<String, ToolHandler> 实现工具注册。模型返回 block.name,代码用 map.get() 找到对应 handler 执行。
A simple Map lookup replaces if-else chains. Tool name from the model maps directly to a handler instance.
safePath() 检查路径不越界,危险命令(rm -rf /、sudo)被拦截。安全层独立于业务逻辑。
safePath() validates file paths stay within project boundaries. Dangerous commands are intercepted before execution.
Agent loop 代码一字未改。新增工具只需往 Map 里注册一个 handler,循环自动分发。开闭原则的完美体现。
The agent loop code is unchanged from S01. Adding tools only requires registering new handlers in the map.
| Tool Name | Handler Method | 说明 |
|---|---|---|
| bash | BashTool.execute(command) | 执行 shell 命令,返回 stdout/stderr |
| read_file | ReadFileTool.execute(path) | 读取文件内容,safePath 校验 |
| write_file | WriteFileTool.execute(path, content) | 写入文件,自动创建目录 |
| edit_file | EditFileTool.execute(path, old, new) | 精准替换,避免重写整个文件 |
"读取 pom.xml 文件"
"Read the file pom.xml"
"创建一个名为 Greeter.java 的文件,包含一个 greet(name) 方法"
"Create a file called Greeter.java with a greet(name) function"
"编辑 Greeter.java,为方法添加文档注释"
"Edit Greeter.java to add a docstring to the function"
"读取 Greeter.java 验证编辑成功"
"Read Greeter.java to verify the edit worked"