]> git.giacomolli.uk - onechat/blob - terminal.go
Show the subagents in the clients
[onechat] / terminal.go
1 package main
2
3 import (
4         "bufio"
5         "context"
6         "encoding/json"
7         "errors"
8         "fmt"
9         "io"
10         "net"
11         "path/filepath"
12         "strings"
13 )
14
15 // terminalResultLines is the most lines of a tool result that the client shows.
16 const terminalResultLines = 10
17
18 // errTerminalDaemonClosed tells that the daemon closed the connection.
19 var errTerminalDaemonClosed = errors.New("the daemon closed the connection")
20
21 // terminal runs "onechat chat": the terminal client of the daemon. Each line of
22 // input is a user message, the line /stop interrupts the running turn, and the
23 // line /stop NAME stops the subagent NAME. The client shows the replies, the
24 // tool calls, and their results as they happen. It ends at the end of the input
25 // or when the daemon closes the connection.
26 func terminal(ctx context.Context, in io.Reader, out io.Writer) error {
27         dir, err := dataDir()
28         if err != nil {
29                 return err
30         }
31
32         path := filepath.Join(dir, socketFileName)
33         err = checkSocketPath(path)
34         if err != nil {
35                 return err
36         }
37
38         var dialer net.Dialer
39         conn, err := dialer.DialContext(ctx, "unix", path)
40         if err != nil {
41                 return fmt.Errorf(`connect to the daemon (start it with "onechat daemon"): %w`, err)
42         }
43
44         return terminalSession(ctx, conn, in, out)
45 }
46
47 // terminalSession runs the client on conn until the input ends, the daemon
48 // closes the connection, or ctx ends, and closes conn. A read of the input that
49 // waits for a line can stay behind when the daemon closes the connection.
50 func terminalSession(ctx context.Context, conn net.Conn, in io.Reader, out io.Writer) error {
51         sent := make(chan error, 1)
52         go func() {
53                 sent <- terminalSendLines(ctx, conn, in)
54         }()
55
56         shown := make(chan error, 1)
57         go func() {
58                 shown <- terminalShowEvents(conn, out)
59         }()
60
61         var err error
62         select {
63         case err = <-sent:
64                 err = errors.Join(err, conn.Close())
65                 <-shown
66         case err = <-shown:
67                 err = errors.Join(terminalCmpError(err, errTerminalDaemonClosed), conn.Close())
68         case <-ctx.Done():
69                 err = conn.Close()
70                 <-shown
71         }
72
73         return err
74 }
75
76 // terminalSendLines sends each line of in as a request until the input ends.
77 func terminalSendLines(ctx context.Context, conn net.Conn, in io.Reader) error {
78         encoder := json.NewEncoder(conn)
79         scanner := bufio.NewScanner(in)
80         scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
81         for ctx.Err() == nil && scanner.Scan() {
82                 line := scanner.Text()
83                 request := SocketRequest{
84                         Type: "send",
85                         Text: line,
86                 }
87
88                 name, stop := stopSubagentName(line)
89                 switch strings.TrimSpace(line) {
90                 case "":
91                         continue
92                 case stopCommand:
93                         request = SocketRequest{
94                                 Type: "interrupt",
95                         }
96                 default:
97                         if stop {
98                                 request = SocketRequest{
99                                         Type: "stop",
100                                         Text: name,
101                                 }
102                         }
103                 }
104
105                 err := encoder.Encode(request)
106                 if err != nil {
107                         return fmt.Errorf("send to the daemon: %w", err)
108                 }
109         }
110
111         return scanner.Err()
112 }
113
114 // terminalShowEvents writes each event from the daemon to out until the
115 // connection closes.
116 func terminalShowEvents(conn net.Conn, out io.Writer) error {
117         scanner := bufio.NewScanner(conn)
118         scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
119         for scanner.Scan() {
120                 var event Event
121                 err := json.Unmarshal(scanner.Bytes(), &event)
122                 if err != nil {
123                         return fmt.Errorf("decode event: %w", err)
124                 }
125
126                 text := terminalEventText(event)
127                 if text == "" {
128                         continue
129                 }
130
131                 _, err = io.WriteString(out, text+"\n")
132                 if err != nil {
133                         return err
134                 }
135         }
136
137         return scanner.Err()
138 }
139
140 // terminalCmpError returns err, or fallback when err is nil.
141 func terminalCmpError(err, fallback error) error {
142         if err == nil {
143                 return fallback
144         }
145
146         return err
147 }
148
149 // terminalEventText returns the text that the client shows for event, or "" for
150 // none. The client shows a user message only from another source, such as
151 // telegram, because the user typed the others. A tool result shows its first
152 // terminalResultLines lines. The report of a subagent shows whole, and it
153 // starts with the name of the subagent.
154 func terminalEventText(event Event) string {
155         switch event.Kind {
156         case "ready":
157                 return "[connected to " + event.Text + "]"
158         case "user":
159                 if event.Source == terminalSource {
160                         return ""
161                 }
162
163                 return "[" + event.Source + "] " + event.Text
164         case "reply":
165                 return event.Text
166         case "tool":
167                 return "[tool] " + event.Text
168         case "echo":
169                 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
170         case "subagent":
171                 return "[" + event.Text + "] started"
172         case "work":
173                 return event.Text
174         case "busy":
175                 return "[working]"
176         case "idle":
177                 return "[done]"
178         case "error":
179                 return "[error] " + event.Text
180         default:
181                 return ""
182         }
183 }
184
185 // terminalFirstLines returns the first count lines of text, with the number of
186 // the lines left out.
187 func terminalFirstLines(text string, count int) string {
188         text = strings.TrimRight(text, "\n")
189         lines := strings.Split(text, "\n")
190         if len(lines) <= count {
191                 return text
192         }
193
194         return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)
195 }