15 // terminalResultLines is the most lines of a tool result that the client shows.
16 const terminalResultLines = 10
18 // errTerminalDaemonClosed tells that the daemon closed the connection.
19 var errTerminalDaemonClosed = errors.New("the daemon closed the connection")
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 {
33 path := filepath.Join(dir, socketFileName)
34 err = checkSocketPath(path)
41 conn, err := dialer.DialContext(ctx, "unix", path)
43 return fmt.Errorf(`connect to the daemon (start it with "onechat daemon"): %w`, err)
46 return terminalSession(ctx, conn, in, out)
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)
55 sent <- terminalSendLines(ctx, conn, in)
58 shown := make(chan error, 1)
60 shown <- terminalShowEvents(conn, out)
67 err = errors.Join(err, conn.Close())
71 err = errors.Join(terminalCmpError(err, errTerminalDaemonClosed), conn.Close())
79 return fmt.Errorf("run terminal client: %w", err)
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)
91 for ctx.Err() == nil && scanner.Scan() {
92 line := scanner.Text()
93 request := SocketRequest{
98 name, stop := stopSubagentName(line)
99 args, whatsapp := whatsappCommandArgs(line)
101 case strings.TrimSpace(line) == "":
103 case strings.TrimSpace(line) == stopCommand:
104 request = SocketRequest{
108 request = SocketRequest{
113 request = SocketRequest{
119 err := encoder.Encode(request)
121 return fmt.Errorf("send to the daemon: %w", err)
127 return fmt.Errorf("read terminal input: %w", err)
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)
142 err := json.Unmarshal(scanner.Bytes(), &event)
144 return fmt.Errorf("decode event: %w", err)
147 text := terminalEventText(event)
152 _, err = io.WriteString(out, text+"\n")
154 return fmt.Errorf("write terminal event: %w", err)
160 return fmt.Errorf("read daemon events: %w", err)
166 // terminalCmpError returns err, or fallback when err is nil.
167 func terminalCmpError(err, fallback error) error {
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 {
183 return "[connected to " + event.Text + "]"
185 if event.Source == terminalSource {
189 return "[" + event.Source + "] " + event.Text
193 return "[tool] " + event.Text
195 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
197 return "[" + event.Text + "] started"
205 return "[error] " + event.Text
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 {
222 return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)