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