gunk-dev/the-valley

formatter.go

sourced9c8073fd613main's published tip history
3.8 KiB
1package stream
2
3import (
4 "bufio"
5 "encoding/json"
6 "fmt"
7 "io"
8 "time"
9)
10
11// Event represents a parsed JSONL event from Claude's stream-json output.
12type Event struct {
13 Content string `json:"content,omitempty"`
14 Type string `json:"type"`
15 Subtype string `json:"subtype,omitempty"`
16 Model string `json:"model,omitempty"`
17 Message *AssistantMsg `json:"message,omitempty"`
18
19 // Result fields
20 TotalCostUSD *float64 `json:"total_cost_usd,omitempty"`
21 DurationMS *int64 `json:"duration_ms,omitempty"`
22}
23
24// AssistantMsg represents the message field in an assistant event.
25type AssistantMsg struct {
26 Content []ContentBlock `json:"content"`
27}
28
29// ContentBlock represents a single content block in an assistant message.
30type ContentBlock struct {
31 Type string `json:"type"`
32 Text string `json:"text,omitempty"`
33 Name string `json:"name,omitempty"`
34 Input json.RawMessage `json:"input,omitempty"`
35}
36
37// ToolInput is used to extract specific fields from tool_use input.
38type ToolInput struct {
39 FilePath string `json:"file_path,omitempty"`
40 Command string `json:"command,omitempty"`
41 Pattern string `json:"pattern,omitempty"`
42}
43
44// FormatStream reads JSONL from r and writes human-readable progress to w.
45func FormatStream(r io.Reader, w io.Writer) error {
46 return FormatStreamWatching(r, w, nil)
47}
48
49// FormatStreamWatching is FormatStream that also hands each line, as
50// NormalizeLine makes it, to watch when it arrives; watch may be nil.
51func FormatStreamWatching(r io.Reader, w io.Writer, watch *CheckWatcher) error {
52 scanner := bufio.NewScanner(r)
53 // Allow large lines (Claude output can be big)
54 scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
55
56 for scanner.Scan() {
57 line := scanner.Text()
58 if line == "" {
59 continue
60 }
61 FormatLine(line, w)
62 if watch != nil {
63 watch.Observe(NormalizeLine([]byte(line)), time.Now())
64 }
65 }
66 return scanner.Err()
67}
68
69// FormatLine formats a single JSONL line and writes it to w.
70func FormatLine(line string, w io.Writer) {
71 var ev Event
72 if err := json.Unmarshal(NormalizeLine([]byte(line)), &ev); err != nil {
73 return
74 }
75
76 switch ev.Type {
77 case "text_delta":
78 fmt.Fprint(w, ev.Content)
79 case "system":
80 if ev.Subtype == "init" {
81 model := ev.Model
82 if model == "" {
83 model = "unknown"
84 }
85 fmt.Fprintf(w, "── session started (model: %s) ──\n", model)
86 }
87
88 case "assistant":
89 if ev.Message == nil {
90 return
91 }
92 for _, block := range ev.Message.Content {
93 switch block.Type {
94 case "text":
95 fmt.Fprintln(w, block.Text)
96 case "tool_use":
97 fmt.Fprintln(w, formatToolUse(block))
98 }
99 }
100
101 case "result":
102 cost := float64(0)
103 if ev.TotalCostUSD != nil {
104 cost = *ev.TotalCostUSD
105 }
106 durationMS := int64(0)
107 if ev.DurationMS != nil {
108 durationMS = *ev.DurationMS
109 }
110 durationS := float64(durationMS) / 1000.0
111 fmt.Fprintln(w)
112 if ev.Subtype == "error_during_execution" {
113 fmt.Fprintln(w, "── agent failed ──")
114 } else if ev.TotalCostUSD == nil {
115 fmt.Fprintln(w, "── done (cost unavailable) ──")
116 } else {
117 fmt.Fprintf(w, "── done (%.1fs, $%.4f) ──\n", durationS, cost)
118 }
119 }
120}
121
122func formatToolUse(block ContentBlock) string {
123 var input ToolInput
124 if block.Input != nil {
125 json.Unmarshal(block.Input, &input)
126 }
127
128 switch block.Name {
129 case "Read":
130 return fmt.Sprintf("▶ Read %s", input.FilePath)
131 case "Edit":
132 return fmt.Sprintf("▶ Edit %s", input.FilePath)
133 case "Write":
134 return fmt.Sprintf("▶ Write %s", input.FilePath)
135 case "Bash":
136 cmd := input.Command
137 // Show only first line of command
138 for i, c := range cmd {
139 if c == '\n' {
140 cmd = cmd[:i]
141 break
142 }
143 }
144 return fmt.Sprintf("▶ Bash: %s", cmd)
145 case "Glob":
146 return fmt.Sprintf("▶ Glob %s", input.Pattern)
147 case "Grep":
148 return fmt.Sprintf("▶ Grep %s", input.Pattern)
149 default:
150 return fmt.Sprintf("▶ %s", block.Name)
151 }
152}