]> git.giacomolli.uk - onechat/blob - terminal.go
203cb5e64adb2d6a8054f71e2b0431536e5c1331
[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.
138 func terminalShowEvents(conn net.Conn, out io.Writer) error {
139 scanner := bufio.NewScanner(conn)
140 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
141
142 for scanner.Scan() {
143 var event Event
144
145 err := json.Unmarshal(scanner.Bytes(), &event)
146 if err != nil {
147 return fmt.Errorf("decode event: %w", err)
148 }
149
150 text := terminalEventText(event)
151 if text == "" {
152 continue
153 }
154
155 columns := terminalColumns(out)
156 if columns > 0 && (event.Kind == "reply" || event.Kind == "work") {
157 text = strings.Join(terminalMarkdown(text, columns), "\n")
158 }
159
160 _, err = io.WriteString(out, text+"\n")
161 if err != nil {
162 return fmt.Errorf("write terminal event: %w", err)
163 }
164 }
165
166 err := scanner.Err()
167 if err != nil {
168 return fmt.Errorf("read daemon events: %w", err)
169 }
170
171 return nil
172 }
173
174 // terminalCmpError returns err, or fallback when err is nil.
175 func terminalCmpError(err, fallback error) error {
176 if err == nil {
177 return fallback
178 }
179
180 return err
181 }
182
183 // terminalEventText returns the text that the client shows for event, or "" for
184 // none. The client shows a user message only from another source, such as
185 // telegram, because the user typed the others. A tool result shows its first
186 // terminalResultLines lines. The report of a subagent shows whole, and it
187 // starts with the name of the subagent.
188 func terminalEventText(event Event) string {
189 switch event.Kind {
190 case "ready":
191 return "[connected to " + event.Text + "]"
192 case "user":
193 if event.Source == terminalSource {
194 return ""
195 }
196
197 return "[" + event.Source + "] " + event.Text
198 case "reply":
199 return event.Text
200 case "tool":
201 return "[tool] " + event.Text
202 case "echo":
203 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
204 case "subagent":
205 return "[" + event.Text + "] started"
206 case "work":
207 return event.Text
208 case "busy":
209 return "[working]"
210 case "idle":
211 return "[done]"
212 case "error":
213 return "[error] " + event.Text
214 case "notice":
215 return event.Text
216 default:
217 return ""
218 }
219 }
220
221 // terminalColumns returns the current terminal width, or zero for other output.
222 // A terminal that reports no columns uses 80.
223 func terminalColumns(out io.Writer) int {
224 file, ok := out.(interface{ Fd() uintptr })
225 if !ok {
226 return 0
227 }
228
229 size, err := unix.IoctlGetWinsize(int(file.Fd()), unix.TIOCGWINSZ)
230 if err != nil {
231 return 0
232 }
233
234 if size.Col == 0 {
235 return 80
236 }
237
238 return int(size.Col)
239 }
240
241 // terminalFirstLines returns the first count lines of text, with the number of
242 // the lines left out.
243 func terminalFirstLines(text string, count int) string {
244 text = strings.TrimRight(text, "\n")
245 lines := strings.Split(text, "\n")
246 if len(lines) <= count {
247 return text
248 }
249
250 return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)
251 }