v1.4 工具集扩展 + Windows 编码攻坚

- 新增 BashTool(bash 命令执行,30s 超时 + 自愈 + 截断)
- 新增 WriteFileTool(文件写入)
- Windows GBK 编码自动转 UTF-8(golang.org/x/text)
- OpenAIProvider 新增 API 交互日志
- dumpMessages 移除截断,完整展示上下文
- cmd/claw 三段式任务演示
This commit is contained in:
zhuyongxin
2026-05-15 17:11:43 +08:00
parent b94460083a
commit cefabd68dc
8 changed files with 497 additions and 274 deletions
+99 -99
View File
@@ -16,15 +16,15 @@ type AgentEngine struct {
registry tools.Registry
// WorkDir (工作区): 借鉴 OpenClaw 的理念,Agent 必须有一个明确的物理边界
WorkDir string
WorkDir string
EnableThinking bool // 【新增】慢思考模式开关
}
func NewAgentEngine(p provider.LLMProvider, r tools.Registry, workDir string, enableThinking bool) *AgentEngine {
return &AgentEngine{
provider: p,
registry: r,
WorkDir: workDir,
provider: p,
registry: r,
WorkDir: workDir,
EnableThinking: enableThinking,
}
}
@@ -37,9 +37,9 @@ func (e *AgentEngine) String() string {
func dumpMessages(msgs []schema.Message) {
for i, msg := range msgs {
content := msg.Content
if len(content) > 80 {
content = content[:80] + "..."
}
// if len(content) > 80 {
// content = content[:80] + "..."
// }
log.Printf(" [%02d] %-10s | %s", i, msg.Role, content)
}
}
@@ -57,116 +57,116 @@ func dumpTools(tools []schema.ToolDefinition) {
// internal/engine/loop.go (续)
func (e *AgentEngine) Run(ctx context.Context, userPrompt string) error {
log.Printf("[Engine] 引擎启动,锁定工作区: %s\n", e.WorkDir)
log.Printf("[Engine] 慢思考模式 (Thinking Phase): %v\n", e.EnableThinking)
log.Printf("[Engine] 引擎启动,锁定工作区: %s\n", e.WorkDir)
log.Printf("[Engine] 慢思考模式 (Thinking Phase): %v\n", e.EnableThinking)
contextHistory := []schema.Message{
{
Role: schema.RoleSystem,
Content: "You are go-tiny-claw, an expert coding assistant. You have full access to tools in the workspace.",
},
{
Role: schema.RoleUser,
Content: userPrompt,
},
}
contextHistory := []schema.Message{
{
Role: schema.RoleSystem,
Content: "You are go-tiny-claw, an expert coding assistant. You have full access to tools in the workspace.",
},
{
Role: schema.RoleUser,
Content: userPrompt,
},
}
turnCount := 0
const maxTurns = 10
turnCount := 0
const maxTurns = 10
for {
turnCount++
if turnCount > maxTurns {
log.Printf("[Engine] 已达最大轮数 (%d),强制终止。\n", maxTurns)
break
}
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
dumpMessages(contextHistory)
for {
turnCount++
if turnCount > maxTurns {
log.Printf("[Engine] 已达最大轮数 (%d),强制终止。\n", maxTurns)
break
}
log.Printf("\n========== [Turn %d] 开始 ==========\n", turnCount)
dumpMessages(contextHistory)
// 获取当前挂载的所有工具定义
availableTools := e.registry.GetAvailableTools()
dumpTools(availableTools)
// 获取当前挂载的所有工具定义
availableTools := e.registry.GetAvailableTools()
dumpTools(availableTools)
// ====================================================================
// Phase 1: 慢思考阶段 (Thinking) - 仅第一轮执行初始规划
// ====================================================================
if e.EnableThinking && turnCount == 1 {
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
// ====================================================================
// Phase 1: 慢思考阶段 (Thinking) - 仅第一轮执行初始规划
// ====================================================================
if e.EnableThinking && turnCount == 1 {
log.Println("[Engine][Phase 1] 剥夺工具访问权,强制进入慢思考与规划阶段...")
// 核心机制:传入的 availableTools 为 nil!
// 大模型看不到任何 JSON Schema,被迫只能输出纯文本的思考过程。
thinkResp, err := e.provider.Generate(ctx, contextHistory, nil)
if err != nil {
return fmt.Errorf("Thinking 阶段生成失败: %w", err)
}
// 核心机制:传入的 availableTools 为 nil!
// 大模型看不到任何 JSON Schema,被迫只能输出纯文本的思考过程。
thinkResp, err := e.provider.Generate(ctx, contextHistory, nil)
if err != nil {
return fmt.Errorf("Thinking 阶段生成失败: %w", err)
}
// 如果模型输出了思考过程,我们将其作为 Assistant 消息追加到上下文中
if thinkResp.Content != "" {
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
contextHistory = append(contextHistory, *thinkResp)
}
// 如果模型输出了思考过程,我们将其作为 Assistant 消息追加到上下文中
if thinkResp.Content != "" {
fmt.Printf("🧠 [内部思考 Trace]: %s\n", thinkResp.Content)
contextHistory = append(contextHistory, *thinkResp)
}
// 插入过渡指令:让模型知道现在可以调用工具了
contextHistory = append(contextHistory, schema.Message{
Role: schema.RoleUser,
Content: "根据你的推理,现在请使用可用的工具来完成任务。执行具体行动。",
})
}
// 插入过渡指令:让模型知道现在可以调用工具了
contextHistory = append(contextHistory, schema.Message{
Role: schema.RoleUser,
Content: "根据你的推理,现在请使用可用的工具来完成任务。执行具体行动。",
})
}
// ====================================================================
// Phase 2: 行动阶段 (Action) - 恢复工具,顺着规划执行
// ====================================================================
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
// ====================================================================
// Phase 2: 行动阶段 (Action) - 恢复工具,顺着规划执行
// ====================================================================
log.Println("[Engine][Phase 2] 恢复工具挂载,等待模型采取行动...")
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace + 过渡指令。
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
if err != nil {
return fmt.Errorf("Action 阶段生成失败: %w", err)
}
// 此时的 contextHistory 中已经包含了上一阶段模型自己的 Thinking Trace + 过渡指令。
// 模型会顺着自己的逻辑,结合恢复的 availableTools 发起精准的工具调用。
actionResp, err := e.provider.Generate(ctx, contextHistory, availableTools)
if err != nil {
return fmt.Errorf("Action 阶段生成失败: %w", err)
}
contextHistory = append(contextHistory, *actionResp)
contextHistory = append(contextHistory, *actionResp)
if actionResp.Content != "" {
fmt.Printf("🤖 [对外回复]: %s\n", actionResp.Content)
}
if actionResp.Content != "" {
fmt.Printf("🤖 [对外回复]: %s\n", actionResp.Content)
}
// ====================================================================
// 退出与执行逻辑 (与上一讲保持一致)
// ====================================================================
if len(actionResp.ToolCalls) == 0 {
log.Println("[Engine] 模型未请求调用工具,任务宣告完成。")
break
}
// ====================================================================
// 退出与执行逻辑 (与上一讲保持一致)
// ====================================================================
if len(actionResp.ToolCalls) == 0 {
log.Println("[Engine] 模型未请求调用工具,任务宣告完成。")
break
}
log.Printf("[Engine] 模型请求调用 %d 个工具...\n", len(actionResp.ToolCalls))
log.Printf("[Engine] 模型请求调用 %d 个工具...\n", len(actionResp.ToolCalls))
for _, toolCall := range actionResp.ToolCalls {
log.Printf(" -> 🛠️ 执行工具: %s, 参数: %s\n", toolCall.Name, string(toolCall.Arguments))
for _, toolCall := range actionResp.ToolCalls {
log.Printf(" -> 🛠️ 执行工具: %s, 参数: %s\n", toolCall.Name, string(toolCall.Arguments))
result := e.registry.Execute(ctx, toolCall)
result := e.registry.Execute(ctx, toolCall)
status := "✅ 成功"
if result.IsError {
status = "❌ 失败"
}
log.Printf(" -> 📋 ToolCall %s: %s, 结果: %s\n", toolCall.ID, status, result.Output)
status := "✅ 成功"
if result.IsError {
status = "❌ 失败"
}
log.Printf(" -> 📋 ToolCall %s: %s, 结果: %s\n", toolCall.ID, status, result.Output)
if result.IsError {
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
} else {
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
}
if result.IsError {
log.Printf(" -> ❌ 工具执行报错: %s\n", result.Output)
} else {
log.Printf(" -> ✅ 工具执行成功 (返回 %d 字节)\n", len(result.Output))
}
// 将工具执行的观察结果追加到 Context,准备进入下一轮
observationMsg := schema.Message{
Role: schema.RoleUser,
Content: result.Output,
ToolCallID: toolCall.ID,
}
contextHistory = append(contextHistory, observationMsg)
}
}
// 将工具执行的观察结果追加到 Context,准备进入下一轮
observationMsg := schema.Message{
Role: schema.RoleUser,
Content: result.Output,
ToolCallID: toolCall.ID,
}
contextHistory = append(contextHistory, observationMsg)
}
}
return nil
return nil
}
+180 -160
View File
@@ -2,192 +2,212 @@
package provider
import (
"context"
"encoding/json"
"fmt"
// "os"
"context"
"encoding/json"
"fmt"
"log"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/packages/param"
"github.com/openai/openai-go/v3/shared"
"go-tiny-claw/internal/schema"
// "os"
"go-tiny-claw/internal/schema"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/packages/param"
"github.com/openai/openai-go/v3/shared"
)
type OpenAIProvider struct {
client openai.Client // 值类型,非指针
model string
client openai.Client // 值类型,非指针
model string
}
// NewZhipuOpenAIProvider 构造函数:基于 OpenAI V3 SDK,指向智谱底座
func DeepseekOpenAIProvider(model string) *OpenAIProvider {
apiKey := "sk-1f44696abe644bd684f09cc43f12c557"
if apiKey == "" {
panic("请设置 ZHIPU_API_KEY 环境变量")
}
// 核心:将官方 SDK 的地址替换为智谱的兼容端点
baseURL := "https://api.deepseek.com"
apiKey := "sk-1f44696abe644bd684f09cc43f12c557"
if apiKey == "" {
panic("请设置 ZHIPU_API_KEY 环境变量")
}
// 核心:将官方 SDK 的地址替换为智谱的兼容端点
baseURL := "https://api.deepseek.com"
return &OpenAIProvider{
client: openai.NewClient(option.WithAPIKey(apiKey), option.WithBaseURL(baseURL)),
model: model,
}
return &OpenAIProvider{
client: openai.NewClient(option.WithAPIKey(apiKey), option.WithBaseURL(baseURL)),
model: model,
}
}
func (p *OpenAIProvider) Generate(ctx context.Context, msgs []schema.Message, availableTools []schema.ToolDefinition) (*schema.Message, error) {
var openaiMsgs []openai.ChatCompletionMessageParamUnion
phase := "Action"
if len(availableTools) == 0 {
phase = "Thinking"
}
log.Printf("[Provider] → API 调用 | 模型: %s | 阶段: %s | 消息数: %d | 工具数: %d",
p.model, phase, len(msgs), len(availableTools))
// 1. 翻译上下文消息
for _, msg := range msgs {
switch msg.Role {
case schema.RoleSystem:
openaiMsgs = append(openaiMsgs, openai.SystemMessage(msg.Content))
var openaiMsgs []openai.ChatCompletionMessageParamUnion
case schema.RoleUser:
if msg.ToolCallID != "" {
// 注意:v3 新版参数顺序是 (content, toolCallID)
openaiMsgs = append(openaiMsgs, openai.ToolMessage(msg.Content, msg.ToolCallID))
} else {
openaiMsgs = append(openaiMsgs, openai.UserMessage(msg.Content))
}
// 1. 翻译上下文消息
for _, msg := range msgs {
switch msg.Role {
case schema.RoleSystem:
openaiMsgs = append(openaiMsgs, openai.SystemMessage(msg.Content))
case schema.RoleAssistant:
// Deepseek thinking mode: reasoning_content 必须回传
if msg.ReasoningContent != "" || len(msg.ToolCalls) > 0 {
msgMap := map[string]interface{}{
"role": "assistant",
"content": msg.Content,
}
if msg.ReasoningContent != "" {
msgMap["reasoning_content"] = msg.ReasoningContent
}
if len(msg.ToolCalls) > 0 {
var toolCalls []map[string]interface{}
for _, tc := range msg.ToolCalls {
toolCalls = append(toolCalls, map[string]interface{}{
"id": tc.ID,
"type": "function",
"function": map[string]interface{}{
"name": tc.Name,
"arguments": string(tc.Arguments),
},
})
}
msgMap["tool_calls"] = toolCalls
}
rawJSON, _ := json.Marshal(msgMap)
astParam := param.Override[openai.ChatCompletionAssistantMessageParam](json.RawMessage(rawJSON))
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
OfAssistant: &astParam,
})
break
}
case schema.RoleUser:
if msg.ToolCallID != "" {
// 注意:v3 新版参数顺序是 (content, toolCallID)
openaiMsgs = append(openaiMsgs, openai.ToolMessage(msg.Content, msg.ToolCallID))
} else {
openaiMsgs = append(openaiMsgs, openai.UserMessage(msg.Content))
}
astParam := openai.ChatCompletionAssistantMessageParam{}
case schema.RoleAssistant:
// Deepseek thinking mode: reasoning_content 必须回传
if msg.ReasoningContent != "" || len(msg.ToolCalls) > 0 {
msgMap := map[string]interface{}{
"role": "assistant",
"content": msg.Content,
}
if msg.ReasoningContent != "" {
msgMap["reasoning_content"] = msg.ReasoningContent
}
if len(msg.ToolCalls) > 0 {
var toolCalls []map[string]interface{}
for _, tc := range msg.ToolCalls {
toolCalls = append(toolCalls, map[string]interface{}{
"id": tc.ID,
"type": "function",
"function": map[string]interface{}{
"name": tc.Name,
"arguments": string(tc.Arguments),
},
})
}
msgMap["tool_calls"] = toolCalls
}
rawJSON, _ := json.Marshal(msgMap)
astParam := param.Override[openai.ChatCompletionAssistantMessageParam](json.RawMessage(rawJSON))
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
OfAssistant: &astParam,
})
break
}
if msg.Content != "" {
astParam.Content = openai.ChatCompletionAssistantMessageParamContentUnion{
OfString: openai.String(msg.Content),
}
}
astParam := openai.ChatCompletionAssistantMessageParam{}
// 【重要】如果历史包含 ToolCalls,必须原样放回,以维系大模型的逻辑链
if len(msg.ToolCalls) > 0 {
var toolCalls []openai.ChatCompletionMessageToolCallUnionParam
for _, tc := range msg.ToolCalls {
// OfFunction 对应 GetFunction(),字段类型严格要求为指针
toolCalls = append(toolCalls, openai.ChatCompletionMessageToolCallUnionParam{
OfFunction: &openai.ChatCompletionMessageFunctionToolCallParam{
ID: tc.ID,
Type: "function",
Function: openai.ChatCompletionMessageFunctionToolCallFunctionParam{
Name: tc.Name,
Arguments: string(tc.Arguments),
},
},
})
}
astParam.ToolCalls = toolCalls
}
if msg.Content != "" {
astParam.Content = openai.ChatCompletionAssistantMessageParamContentUnion{
OfString: openai.String(msg.Content),
}
}
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
OfAssistant: &astParam,
})
}
}
// 【重要】如果历史包含 ToolCalls,必须原样放回,以维系大模型的逻辑链
if len(msg.ToolCalls) > 0 {
var toolCalls []openai.ChatCompletionMessageToolCallUnionParam
for _, tc := range msg.ToolCalls {
// OfFunction 对应 GetFunction(),字段类型严格要求为指针
toolCalls = append(toolCalls, openai.ChatCompletionMessageToolCallUnionParam{
OfFunction: &openai.ChatCompletionMessageFunctionToolCallParam{
ID: tc.ID,
Type: "function",
Function: openai.ChatCompletionMessageFunctionToolCallFunctionParam{
Name: tc.Name,
Arguments: string(tc.Arguments),
},
},
})
}
astParam.ToolCalls = toolCalls
}
// 2. 翻译工具定义 (v3 新 API 特性适配)
var openaiTools []openai.ChatCompletionToolUnionParam
for _, toolDef := range availableTools {
var params shared.FunctionParameters
openaiMsgs = append(openaiMsgs, openai.ChatCompletionMessageParamUnion{
OfAssistant: &astParam,
})
}
}
// 尝试直接断言,如果不成功则通过 JSON 往返序列化来保证类型匹配
if m, ok := toolDef.InputSchema.(map[string]interface{}); ok {
params = shared.FunctionParameters(m)
} else {
// fallback:JSON 往返序列化
b, _ := json.Marshal(toolDef.InputSchema)
_ = json.Unmarshal(b, &params)
}
// 2. 翻译工具定义 (v3 新 API 特性适配)
var openaiTools []openai.ChatCompletionToolUnionParam
for _, toolDef := range availableTools {
var params shared.FunctionParameters
openaiTools = append(openaiTools, openai.ChatCompletionFunctionTool(
shared.FunctionDefinitionParam{
Name: toolDef.Name,
Description: openai.String(toolDef.Description),
Parameters: params,
},
))
}
// 尝试直接断言,如果不成功则通过 JSON 往返序列化来保证类型匹配
if m, ok := toolDef.InputSchema.(map[string]interface{}); ok {
params = shared.FunctionParameters(m)
} else {
// fallback:JSON 往返序列化
b, _ := json.Marshal(toolDef.InputSchema)
_ = json.Unmarshal(b, &params)
}
// 3. 构建请求并发送
params := openai.ChatCompletionNewParams{
Model: p.model,
Messages: openaiMsgs,
}
openaiTools = append(openaiTools, openai.ChatCompletionFunctionTool(
shared.FunctionDefinitionParam{
Name: toolDef.Name,
Description: openai.String(toolDef.Description),
Parameters: params,
},
))
}
// 【慢思考机制支撑】仅当 availableTools 存在时才挂载 Tools
if len(openaiTools) > 0 {
params.Tools = openaiTools
}
// 3. 构建请求并发送
params := openai.ChatCompletionNewParams{
Model: p.model,
Messages: openaiMsgs,
}
resp, err := p.client.Chat.Completions.New(ctx, params)
if err != nil {
return nil, fmt.Errorf("OpenAI/Zhipu API 请求失败: %w", err)
}
if len(resp.Choices) == 0 {
return nil, fmt.Errorf("API 返回了空的 Choices")
}
// 【慢思考机制支撑】仅当 availableTools 存在时才挂载 Tools
if len(openaiTools) > 0 {
params.Tools = openaiTools
}
// 4. 将 API Response 反向翻译为内部 schema.Message
choice := resp.Choices[0].Message
resultMsg := &schema.Message{
Role: schema.RoleAssistant,
Content: choice.Content,
}
resp, err := p.client.Chat.Completions.New(ctx, params)
if err != nil {
return nil, fmt.Errorf("OpenAI/Zhipu API 请求失败: %w", err)
}
if len(resp.Choices) == 0 {
return nil, fmt.Errorf("API 返回了空的 Choices")
}
// Deepseek thinking mode: 从原始响应中提取 reasoning_content
rawMsg := choice.RawJSON()
if rawMsg != "" {
var rawMap map[string]json.RawMessage
if err := json.Unmarshal([]byte(rawMsg), &rawMap); err == nil {
if rc, ok := rawMap["reasoning_content"]; ok {
var s string
if json.Unmarshal(rc, &s) == nil {
resultMsg.ReasoningContent = s
}
}
}
}
// 4. 将 API Response 反向翻译为内部 schema.Message
choice := resp.Choices[0].Message
resultMsg := &schema.Message{
Role: schema.RoleAssistant,
Content: choice.Content,
}
for _, tc := range choice.ToolCalls {
if tc.Type == "function" {
resultMsg.ToolCalls = append(resultMsg.ToolCalls, schema.ToolCall{
ID: tc.ID,
Name: tc.Function.Name,
Arguments: []byte(tc.Function.Arguments), // 提取 JSON 字符串字节
})
}
}
// Deepseek thinking mode: 从原始响应中提取 reasoning_content
rawMsg := choice.RawJSON()
if rawMsg != "" {
var rawMap map[string]json.RawMessage
if err := json.Unmarshal([]byte(rawMsg), &rawMap); err == nil {
if rc, ok := rawMap["reasoning_content"]; ok {
var s string
if json.Unmarshal(rc, &s) == nil {
resultMsg.ReasoningContent = s
}
}
}
}
return resultMsg, nil
}
for _, tc := range choice.ToolCalls {
if tc.Type == "function" {
resultMsg.ToolCalls = append(resultMsg.ToolCalls, schema.ToolCall{
ID: tc.ID,
Name: tc.Function.Name,
Arguments: []byte(tc.Function.Arguments),
})
}
}
// 打印响应摘要
contentPreview := resultMsg.Content
// if len(contentPreview) > 60 {
// contentPreview = contentPreview[:60] + "..."
// }
log.Printf("[Provider] ← API 响应 | 内容: %q | 工具调用: %d", contentPreview, len(resultMsg.ToolCalls))
for _, tc := range resultMsg.ToolCalls {
log.Printf("[Provider] ↳ ToolCall: %s(%s)", tc.Name, string(tc.Arguments))
}
return resultMsg, nil
}
+89
View File
@@ -0,0 +1,89 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"os/exec"
"time"
"go-tiny-claw/internal/schema"
)
type BashTool struct {
workDir string // 工作区约束
}
func NewBashTool(workDir string) *BashTool {
return &BashTool{workDir: workDir}
}
func (t *BashTool) Name() string {
return "bash"
}
func (t *BashTool) Definition() schema.ToolDefinition {
return schema.ToolDefinition{
Name: t.Name(),
Description: "在当前工作区执行任意的 bash 命令。支持链式命令(如 &&)。返回标准输出(stdout)和标准错误(stderr)。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"command": map[string]interface{}{
"type": "string",
"description": "要执行的 bash 命令,例如: ls -la 或 go test ./...",
},
},
"required": []string{"command"},
},
}
}
type bashArgs struct {
Command string `json:"command"`
}
func (t *BashTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
var input bashArgs
if err := json.Unmarshal(args, &input); err != nil {
return "", fmt.Errorf("参数解析失败: %w", err)
}
// 【驾驭底线 1】:Time Budgeting (时间预算与超时控制)
timeoutCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Unix 和 Windows 统一使用 bash -c(Windows 需安装 Git Bash),编码转换在下方处理
cmd := exec.CommandContext(timeoutCtx, "bash", "-c", input.Command)
// 【驾驭底线 2】:绑定执行的工作区目录
cmd.Dir = t.workDir
// 执行并捕获 CombinedOutput (合并 stdout 和 stderr)
out, err := cmd.CombinedOutput()
outputStr := string(out)
// 如果命令执行超时,返回警告信息让模型知晓
if timeoutCtx.Err() == context.DeadlineExceeded {
return outputStr + "\n[警告: 命令执行超时(30s),已被系统强制终止。如果是启动常驻服务,请尝试将其转入后台。]", nil
}
// 【驾驭底线 3】:错误原样回传 (Self-Correction 自愈机制)
if err != nil {
return fmt.Sprintf("执行报错: %v\n输出:\n%s", err, outputStr), nil
}
// 如果没有终端输出,给模型一个明确的执行成功的反馈
if outputStr == "" {
return "命令执行成功,无终端输出。", nil
}
// 【驾驭底线 4】:长度截断保护 (防 OOM)
const maxLen = 8000
if len(outputStr) > maxLen {
return fmt.Sprintf("%s\n\n...[终端输出过长,已截断至前 %d 字节]...", outputStr[:maxLen], maxLen), nil
}
return outputStr, nil
}
+72
View File
@@ -0,0 +1,72 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"go-tiny-claw/internal/schema"
)
type WriteFileTool struct {
workDir string // 工作区约束
}
func NewWriteFileTool(workDir string) *WriteFileTool {
return &WriteFileTool{workDir: workDir}
}
func (t *WriteFileTool) Name() string {
return "write_file"
}
func (t *WriteFileTool) Definition() schema.ToolDefinition {
return schema.ToolDefinition{
Name: t.Name(),
Description: "创建或覆盖写入一个文件。如果目录不存在会自动创建。请提供相对于工作区的相对路径。",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"path": map[string]interface{}{
"type": "string",
"description": "要写入的文件路径,如 src/main.go",
},
"content": map[string]interface{}{
"type": "string",
"description": "要写入的完整文件内容",
},
},
"required": []string{"path", "content"},
},
}
}
type writeFileArgs struct {
Path string `json:"path"`
Content string `json:"content"`
}
func (t *WriteFileTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
var input writeFileArgs
if err := json.Unmarshal(args, &input); err != nil {
return "", fmt.Errorf("参数解析失败: %w", err)
}
// 【安全防线】:限制在 WorkDir 下执行,防止大模型修改系统级文件
fullPath := filepath.Join(t.workDir, input.Path)
// 自动创建缺失的父级目录
if err := os.MkdirAll(filepath.Dir(fullPath), 0755); err != nil {
return "", fmt.Errorf("创建父目录失败: %w", err)
}
// 写入文件内容,权限设为 0644
err := os.WriteFile(fullPath, []byte(input.Content), 0644)
if err != nil {
return "", fmt.Errorf("写入文件失败: %w", err)
}
return fmt.Sprintf("成功将内容写入到文件: %s", input.Path), nil
}