| 1 | package cliconversation |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
| 8 | |
| 9 | |
| 10 | type ToolActivity struct { |
| 11 | ID string `json:"id"` |
| 12 | Name string `json:"name"` |
| 13 | Detail string `json:"detail,omitempty"` |
| 14 | Status string `json:"status"` |
| 15 | } |
| 16 | |
| 17 | func updateTools(tools []ToolActivity, role string, line []byte) ([]ToolActivity, bool) { |
| 18 | var msg struct { |
| 19 | Message struct { |
| 20 | Content []struct { |
| 21 | Type string `json:"type"` |
| 22 | ID string `json:"id"` |
| 23 | Name string `json:"name"` |
| 24 | Input map[string]json.RawMessage `json:"input"` |
| 25 | ToolUseID string `json:"tool_use_id"` |
| 26 | IsError bool `json:"is_error"` |
| 27 | } `json:"content"` |
| 28 | } `json:"message"` |
| 29 | } |
| 30 | if json.Unmarshal(line, &msg) != nil { |
| 31 | return tools, false |
| 32 | } |
| 33 | changed := false |
| 34 | for _, b := range msg.Message.Content { |
| 35 | if role == "user" && b.Type == "tool_result" { |
| 36 | for i := range tools { |
| 37 | if tools[i].ID == b.ToolUseID && tools[i].Status == "called" { |
| 38 | tools[i].Status = "completed" |
| 39 | if b.IsError { |
| 40 | tools[i].Status = "failed" |
| 41 | } |
| 42 | changed = true |
| 43 | break |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | if role != "assistant" || (b.Type != "tool_use" && b.Type != "server_tool_use") || !toolNamePattern.MatchString(b.Name) || b.ID == "" || len(b.ID) > 128 || len(tools) >= 64 { |
| 48 | continue |
| 49 | } |
| 50 | duplicate := false |
| 51 | for _, item := range tools { |
| 52 | if item.ID == b.ID { |
| 53 | duplicate = true |
| 54 | break |
| 55 | } |
| 56 | } |
| 57 | if duplicate { |
| 58 | continue |
| 59 | } |
| 60 | detail := "" |
| 61 | for _, key := range []string{"description", "subject", "file_path", "pattern", "query", "skill", "subagent_type"} { |
| 62 | var value string |
| 63 | if json.Unmarshal(b.Input[key], &value) == nil && strings.TrimSpace(value) != "" { |
| 64 | runes := []rune(strings.TrimSpace(value)) |
| 65 | detail = string(runes[:min(len(runes), 160)]) |
| 66 | break |
| 67 | } |
| 68 | } |
| 69 | tools = append(tools, ToolActivity{ID: b.ID, Name: b.Name, Detail: detail, Status: "called"}) |
| 70 | changed = true |
| 71 | } |
| 72 | return tools, changed |
| 73 | } |