tool_result_content.go

 1package chat
 2
 3import (
 4	"encoding/json"
 5	"strings"
 6
 7	"github.com/charmbracelet/crush/internal/diffdetect"
 8	"github.com/charmbracelet/crush/internal/stringext"
 9	"github.com/charmbracelet/crush/internal/ui/styles"
10)
11
12type toolResultContentWidths struct {
13	Body int
14	Diff int
15}
16
17func humanizedToolName(name string) string {
18	name = strings.ReplaceAll(name, "_", " ")
19	name = strings.ReplaceAll(name, "-", " ")
20	return stringext.Capitalize(name)
21}
22
23func looksLikeMarkdown(content string) bool {
24	patterns := []string{
25		"# ",
26		"## ",
27		"**",
28		"```",
29		"- ",
30		"1. ",
31		"> ",
32		"---",
33		"***",
34	}
35	for _, p := range patterns {
36		if strings.Contains(content, p) {
37			return true
38		}
39	}
40	return false
41}
42
43func renderToolResultTextContent(sty *styles.Styles, content string, widths toolResultContentWidths, expanded bool) string {
44	var result json.RawMessage
45	if err := json.Unmarshal([]byte(content), &result); err == nil {
46		prettyResult, err := json.MarshalIndent(result, "", "  ")
47		if err == nil {
48			return sty.Tool.Body.Render(toolOutputCodeContent(sty, "result.json", string(prettyResult), 0, widths.Body, expanded))
49		}
50		return sty.Tool.Body.Render(toolOutputPlainContent(sty, content, widths.Body, expanded))
51	}
52	if diffdetect.IsUnifiedDiff(content) {
53		return toolOutputDiffContentFromUnified(sty, content, widths.Diff, expanded)
54	}
55	if looksLikeMarkdown(content) {
56		return sty.Tool.Body.Render(toolOutputCodeContent(sty, "result.md", content, 0, widths.Body, expanded))
57	}
58	return sty.Tool.Body.Render(toolOutputPlainContent(sty, content, widths.Body, expanded))
59}