]> git.giacomolli.uk - onechat/blob - terminal.go
Import WhatsApp exports before live messages
[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 return err
75 }
76
77 // terminalSendLines sends each line of in as a request until the input ends.
78 func terminalSendLines(ctx context.Context, conn net.Conn, in io.Reader) error {
79 encoder := json.NewEncoder(conn)
80 scanner := bufio.NewScanner(in)
81 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
82 for ctx.Err() == nil && scanner.Scan() {
83 line := scanner.Text()
84 request := SocketRequest{
85 Type: "send",
86 Text: line,
87 }
88
89 name, stop := stopSubagentName(line)
90 args, whatsapp := whatsappCommandArgs(line)
91 switch {
92 case strings.TrimSpace(line) == "":
93 continue
94 case strings.TrimSpace(line) == stopCommand:
95 request = SocketRequest{
96 Type: "interrupt",
97 }
98 case stop:
99 request = SocketRequest{
100 Type: "stop",
101 Text: name,
102 }
103 case whatsapp:
104 request = SocketRequest{
105 Type: "whatsapp",
106 Text: args,
107 }
108 }
109
110 err := encoder.Encode(request)
111 if err != nil {
112 return fmt.Errorf("send to the daemon: %w", err)
113 }
114 }
115
116 return scanner.Err()
117 }
118
119 // terminalShowEvents writes each event from the daemon to out until the
120 // connection closes.
121 func terminalShowEvents(conn net.Conn, out io.Writer) error {
122 scanner := bufio.NewScanner(conn)
123 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
124 for scanner.Scan() {
125 var event Event
126 err := json.Unmarshal(scanner.Bytes(), &event)
127 if err != nil {
128 return fmt.Errorf("decode event: %w", err)
129 }
130
131 text := terminalEventText(event)
132 if text == "" {
133 continue
134 }
135
136 _, err = io.WriteString(out, text+"\n")
137 if err != nil {
138 return err
139 }
140 }
141
142 return scanner.Err()
143 }
144
145 // terminalCmpError returns err, or fallback when err is nil.
146 func terminalCmpError(err, fallback error) error {
147 if err == nil {
148 return fallback
149 }
150
151 return err
152 }
153
154 // terminalEventText returns the text that the client shows for event, or "" for
155 // none. The client shows a user message only from another source, such as
156 // telegram, because the user typed the others. A tool result shows its first
157 // terminalResultLines lines. The report of a subagent shows whole, and it
158 // starts with the name of the subagent.
159 func terminalEventText(event Event) string {
160 switch event.Kind {
161 case "ready":
162 return "[connected to " + event.Text + "]"
163 case "user":
164 if event.Source == terminalSource {
165 return ""
166 }
167
168 return "[" + event.Source + "] " + event.Text
169 case "reply":
170 return event.Text
171 case "tool":
172 return "[tool] " + event.Text
173 case "echo":
174 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
175 case "subagent":
176 return "[" + event.Text + "] started"
177 case "work":
178 return event.Text
179 case "busy":
180 return "[working]"
181 case "idle":
182 return "[done]"
183 case "error":
184 return "[error] " + event.Text
185 case "notice":
186 return event.Text
187 default:
188 return ""
189 }
190 }
191
192 // terminalFirstLines returns the first count lines of text, with the number of
193 // the lines left out.
194 func terminalFirstLines(text string, count int) string {
195 text = strings.TrimRight(text, "\n")
196 lines := strings.Split(text, "\n")
197 if len(lines) <= count {
198 return text
199 }
200
201 return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)
202 }