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)
40 conn, err := dialer.DialContext(ctx, "unix", path)
42 return fmt.Errorf(`connect to the daemon (start it with "onechat daemon"): %w`, err)
45 return terminalSession(ctx, conn, in, out)
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)
54 sent <- terminalSendLines(ctx, conn, in)
57 shown := make(chan error, 1)
59 shown <- terminalShowEvents(conn, out)
65 err = errors.Join(err, conn.Close())
68 err = errors.Join(terminalCmpError(err, errTerminalDaemonClosed), conn.Close())
75 return fmt.Errorf("run terminal client: %w", err)
81 // terminalSendLines sends each line of in as a request until the input ends.
82 func terminalSendLines(ctx context.Context, conn net.Conn, in io.Reader) error {
83 encoder := json.NewEncoder(conn)
84 scanner := bufio.NewScanner(in)
85 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
86 for ctx.Err() == nil && scanner.Scan() {
87 line := scanner.Text()
88 request := SocketRequest{
93 name, stop := stopSubagentName(line)
94 args, whatsapp := whatsappCommandArgs(line)
96 case strings.TrimSpace(line) == "":
98 case strings.TrimSpace(line) == stopCommand:
99 request = SocketRequest{
103 request = SocketRequest{
108 request = SocketRequest{
114 err := encoder.Encode(request)
116 return fmt.Errorf("send to the daemon: %w", err)
122 return fmt.Errorf("read terminal input: %w", err)
128 // terminalShowEvents writes each event from the daemon to out until the
129 // connection closes.
130 func terminalShowEvents(conn net.Conn, out io.Writer) error {
131 scanner := bufio.NewScanner(conn)
132 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
135 err := json.Unmarshal(scanner.Bytes(), &event)
137 return fmt.Errorf("decode event: %w", err)
140 text := terminalEventText(event)
145 _, err = io.WriteString(out, text+"\n")
147 return fmt.Errorf("write terminal event: %w", err)
153 return fmt.Errorf("read daemon events: %w", err)
159 // terminalCmpError returns err, or fallback when err is nil.
160 func terminalCmpError(err, fallback error) error {
168 // terminalEventText returns the text that the client shows for event, or "" for
169 // none. The client shows a user message only from another source, such as
170 // telegram, because the user typed the others. A tool result shows its first
171 // terminalResultLines lines. The report of a subagent shows whole, and it
172 // starts with the name of the subagent.
173 func terminalEventText(event Event) string {
176 return "[connected to " + event.Text + "]"
178 if event.Source == terminalSource {
182 return "[" + event.Source + "] " + event.Text
186 return "[tool] " + event.Text
188 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
190 return "[" + event.Text + "] started"
198 return "[error] " + event.Text
206 // terminalFirstLines returns the first count lines of text, with the number of
207 // the lines left out.
208 func terminalFirstLines(text string, count int) string {
209 text = strings.TrimRight(text, "\n")
210 lines := strings.Split(text, "\n")
211 if len(lines) <= count {
215 return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)