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