]> git.giacomolli.uk - onechat/blob - terminal.go
Format only the Go files of the repository
[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 "golang.org/x/sys/unix"
15 )
16
17 // terminalResultLines is the most lines of a tool result that the client shows.
18 const terminalResultLines = 10
19
20 // errTerminalDaemonClosed tells that the daemon closed the connection.
21 var errTerminalDaemonClosed = errors.New("the daemon closed the connection")
22
23 // terminal runs "onechat" and "onechat chat": the terminal client of the
24 // daemon. Each line of input is a user message, the line /stop interrupts the
25 // running turn, the line /stop NAME stops the subagent NAME, and a line that
26 // starts with /whatsapp is a WhatsApp command. The client shows the replies,
27 // the tool calls, and their results as they happen. It ends at the end of the
28 // input or when the daemon closes the connection.
29 func terminal(ctx context.Context, in io.Reader, out io.Writer) error {
30 dir, err := dataDir()
31 if err != nil {
32 return err
33 }
34
35 path := filepath.Join(dir, socketFileName)
36 err = checkSocketPath(path)
37 if err != nil {
38 return err
39 }
40
41 var dialer net.Dialer
42
43 conn, err := dialer.DialContext(ctx, "unix", path)
44 if err != nil {
45 return fmt.Errorf(`connect to the daemon (start it with "onechat daemon"): %w`, err)
46 }
47
48 return terminalSession(ctx, conn, in, out)
49 }
50
51 // terminalSession runs the client on conn until the input ends, the daemon
52 // closes the connection, or ctx ends, and closes conn. A read of the input that
53 // waits for a line can stay behind when the daemon closes the connection.
54 func terminalSession(ctx context.Context, conn net.Conn, in io.Reader, out io.Writer) error {
55 sent := make(chan error, 1)
56 go func() {
57 sent <- terminalSendLines(ctx, conn, in)
58 }()
59
60 shown := make(chan error, 1)
61 go func() {
62 shown <- terminalShowEvents(conn, out)
63 }()
64
65 var err error
66
67 select {
68 case err = <-sent:
69 err = errors.Join(err, conn.Close())
70
71 <-shown
72 case err = <-shown:
73 err = errors.Join(terminalCmpError(err, errTerminalDaemonClosed), conn.Close())
74 case <-ctx.Done():
75 err = conn.Close()
76
77 <-shown
78 }
79
80 if err != nil {
81 return fmt.Errorf("run terminal client: %w", err)
82 }
83
84 return nil
85 }
86
87 // terminalSendLines sends each line of in as a request until the input ends.
88 func terminalSendLines(ctx context.Context, conn net.Conn, in io.Reader) error {
89 encoder := json.NewEncoder(conn)
90 scanner := bufio.NewScanner(in)
91 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
92
93 for ctx.Err() == nil && scanner.Scan() {
94 line := scanner.Text()
95 request := SocketRequest{
96 Type: "send",
97 Text: line,
98 }
99
100 name, stop := stopSubagentName(line)
101 args, whatsapp := whatsappCommandArgs(line)
102 switch {
103 case strings.TrimSpace(line) == "":
104 continue
105 case strings.TrimSpace(line) == stopCommand:
106 request = SocketRequest{
107 Type: "interrupt",
108 }
109 case stop:
110 request = SocketRequest{
111 Type: "stop",
112 Text: name,
113 }
114 case whatsapp:
115 request = SocketRequest{
116 Type: "whatsapp",
117 Text: args,
118 }
119 }
120
121 err := encoder.Encode(request)
122 if err != nil {
123 return fmt.Errorf("send to the daemon: %w", err)
124 }
125 }
126
127 err := scanner.Err()
128 if err != nil {
129 return fmt.Errorf("read terminal input: %w", err)
130 }
131
132 return nil
133 }
134
135 // terminalShowEvents writes each event from the daemon to out until the
136 // connection closes. Only replies and work messages use Markdown styles, and
137 // only when out is a terminal. Terminal output ends each shown idle event with
138 // an input prompt and clears that prompt before the next shown event.
139 func terminalShowEvents(conn net.Conn, out io.Writer) error {
140 busy, prompt := false, false
141 scanner := bufio.NewScanner(conn)
142 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
143
144 for scanner.Scan() {
145 var event Event
146
147 err := json.Unmarshal(scanner.Bytes(), &event)
148 if err != nil {
149 return fmt.Errorf("decode event: %w", err)
150 }
151
152 text := terminalEventText(event)
153 if text == "" {
154 continue
155 }
156
157 columns := terminalColumns(out)
158 if columns > 0 && (event.Kind == "reply" || event.Kind == "work") {
159 text = strings.Join(terminalMarkdown(text, columns), "\n")
160 }
161
162 switch event.Kind {
163 case "busy":
164 busy = true
165 case "idle":
166 busy = false
167 }
168
169 text += "\n"
170 if prompt {
171 text = "\r\x1b[2K" + text
172 }
173
174 prompt = columns > 0 && !busy
175 if prompt {
176 text += "> "
177 }
178
179 _, err = io.WriteString(out, text)
180 if err != nil {
181 return fmt.Errorf("write terminal event: %w", err)
182 }
183 }
184
185 err := scanner.Err()
186 if err != nil {
187 return fmt.Errorf("read daemon events: %w", err)
188 }
189
190 return nil
191 }
192
193 // terminalCmpError returns err, or fallback when err is nil.
194 func terminalCmpError(err, fallback error) error {
195 if err == nil {
196 return fallback
197 }
198
199 return err
200 }
201
202 // terminalEventText returns the text that the client shows for event, or "" for
203 // none. The client shows a user message only from another source, such as
204 // telegram, because the user typed the others. A tool result shows its first
205 // terminalResultLines lines. The report of a subagent shows whole, and it
206 // starts with the name of the subagent.
207 func terminalEventText(event Event) string {
208 switch event.Kind {
209 case "ready":
210 return "[connected to " + event.Text + "]"
211 case "user":
212 if event.Source == terminalSource {
213 return ""
214 }
215
216 return "[" + event.Source + "] " + event.Text
217 case "reply":
218 return event.Text
219 case "tool":
220 return "[tool] " + event.Text
221 case "echo":
222 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
223 case "subagent":
224 return "[" + event.Text + "] started"
225 case "work":
226 return event.Text
227 case "busy":
228 return "[working]"
229 case "idle":
230 return "[done]"
231 case "error":
232 return "[error] " + event.Text
233 case "notice":
234 return event.Text
235 default:
236 return ""
237 }
238 }
239
240 // terminalColumns returns the current terminal width, or zero for other output.
241 // A terminal that reports no columns uses 80.
242 func terminalColumns(out io.Writer) int {
243 file, ok := out.(interface{ Fd() uintptr })
244 if !ok {
245 return 0
246 }
247
248 size, err := unix.IoctlGetWinsize(int(file.Fd()), unix.TIOCGWINSZ)
249 if err != nil {
250 return 0
251 }
252
253 if size.Col == 0 {
254 return 80
255 }
256
257 return int(size.Col)
258 }
259
260 // terminalFirstLines returns the first count lines of text, with the number of
261 // the lines left out.
262 func terminalFirstLines(text string, count int) string {
263 text = strings.TrimRight(text, "\n")
264 lines := strings.Split(text, "\n")
265 if len(lines) <= count {
266 return text
267 }
268
269 return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)
270 }