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 chat": the terminal client of the daemon. Each line of
22 // input is a user message, and the line /stop interrupts the running turn. The
23 // client shows the replies, the tool calls, and their results as they happen.
24 // It ends at the end of the input or when the daemon closes the connection.
25 func terminal(ctx context.Context, in io.Reader, out io.Writer) error {
31 path := filepath.Join(dir, socketFileName)
32 err = checkSocketPath(path)
38 conn, err := dialer.DialContext(ctx, "unix", path)
40 return fmt.Errorf(`connect to the daemon (start it with "onechat daemon"): %w`, err)
43 return terminalSession(ctx, conn, in, out)
46 // terminalSession runs the client on conn until the input ends, the daemon
47 // closes the connection, or ctx ends, and closes conn. A read of the input that
48 // waits for a line can stay behind when the daemon closes the connection.
49 func terminalSession(ctx context.Context, conn net.Conn, in io.Reader, out io.Writer) error {
50 sent := make(chan error, 1)
52 sent <- terminalSendLines(ctx, conn, in)
55 shown := make(chan error, 1)
57 shown <- terminalShowEvents(conn, out)
63 err = errors.Join(err, conn.Close())
66 err = errors.Join(terminalCmpError(err, errTerminalDaemonClosed), conn.Close())
75 // terminalSendLines sends each line of in as a request until the input ends.
76 func terminalSendLines(ctx context.Context, conn net.Conn, in io.Reader) error {
77 encoder := json.NewEncoder(conn)
78 scanner := bufio.NewScanner(in)
79 scanner.Buffer(make([]byte, 64*1024), requestBytes)
80 for ctx.Err() == nil && scanner.Scan() {
81 line := scanner.Text()
82 request := clientRequest{
87 switch strings.TrimSpace(line) {
91 request = clientRequest{
96 err := encoder.Encode(request)
98 return fmt.Errorf("send to the daemon: %w", err)
105 // terminalShowEvents writes each event from the daemon to out until the
106 // connection closes.
107 func terminalShowEvents(conn net.Conn, out io.Writer) error {
108 scanner := bufio.NewScanner(conn)
109 scanner.Buffer(make([]byte, 64*1024), requestBytes)
112 err := json.Unmarshal(scanner.Bytes(), &event)
114 return fmt.Errorf("decode event: %w", err)
117 text := terminalEventText(event)
122 _, err = io.WriteString(out, text+"\n")
131 // terminalCmpError returns err, or fallback when err is nil.
132 func terminalCmpError(err, fallback error) error {
140 // terminalEventText returns the text that the client shows for event, or "" for
141 // none. The client shows a user message only from another source, such as
142 // telegram, because the user typed the others. A tool result shows its first
143 // terminalResultLines lines.
144 func terminalEventText(event Event) string {
147 return "[connected to " + event.Text + "]"
149 if event.Source == terminalSource {
153 return "[" + event.Source + "] " + event.Text
157 return "[tool] " + event.Text
159 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
165 return "[error] " + event.Text
171 // terminalFirstLines returns the first count lines of text, with the number of
172 // the lines left out.
173 func terminalFirstLines(text string, count int) string {
174 text = strings.TrimRight(text, "\n")
175 lines := strings.Split(text, "\n")
176 if len(lines) <= count {
180 return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)