Files
pipelines/internal/server/chat_shell_terminal.go
alan 355b722a1d Run chat shell commands in a pseudo-terminal with typed input and resize
Commands start in a PTY (creack/pty; macOS and Linux) of the client's size
with TERM=xterm-256color in their own session. chat_shell_input writes typed
UTF-8 text in order through a bounded queue; chat_shell_resize sets the size.
Output stays the raw terminal stream with byte offsets as sequence numbers,
chat_shell_run_output resumes from an offset, and a plain-text rendering is
persisted for Copy output and Send to agent. Input is never stored or logged.
2026-11-09 19:57:46 +00:00

139 lines
4.1 KiB
Go

package server
import (
"errors"
"os"
"os/exec"
"strings"
"syscall"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// startChatShellCommand starts cmd with the server's environment, in a
// pseudo-terminal of cols x rows where the platform has one (TERM is then
// xterm-256color) and otherwise in its own process group with stdout and
// stderr on one pipe. It returns the output reader and, in a terminal, the
// terminal itself (the same file).
func startChatShellCommand(cmd *exec.Cmd, cols, rows int) (reader, terminal *os.File, err error) {
if chatShellTerminals {
cmd.Env = chatShellTerminalEnv(os.Environ())
terminal, err = startChatShellTerminal(cmd, cols, rows)
return terminal, terminal, err
}
reader, writer, err := os.Pipe()
if err != nil {
return nil, nil, err
}
cmd.Env = os.Environ()
cmd.Stdout, cmd.Stderr = writer, writer
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
err = cmd.Start()
writer.Close()
if err != nil {
reader.Close()
return nil, nil, err
}
return reader, nil, nil
}
// chatShellTerminalEnv is env with TERM naming the terminal the clients draw.
func chatShellTerminalEnv(env []string) []string {
out := make([]string, 0, len(env)+1)
for _, entry := range env {
if !strings.HasPrefix(entry, "TERM=") {
out = append(out, entry)
}
}
return append(out, "TERM=xterm-256color")
}
// chatShellTerminalSize clamps a requested size; zero picks the default.
func chatShellTerminalSize(cols, rows int) (int, int) {
if cols <= 0 {
cols = protocol.ChatShellTerminalDefaultCols
}
if rows <= 0 {
rows = protocol.ChatShellTerminalDefaultRows
}
return min(max(cols, protocol.ChatShellTerminalMinCols), protocol.ChatShellTerminalMaxCols),
min(max(rows, protocol.ChatShellTerminalMinRows), protocol.ChatShellTerminalMaxRows)
}
// terminalProcess is runID's running terminal command of sessionID.
func (r *chatShellRunner) terminalProcess(sessionID, runID string) (*chatShellProcess, error) {
p := r.activeProcess(sessionID, runID)
if p == nil {
return nil, errors.New("this command is not running")
}
if p.terminal == nil {
return nil, errors.New(protocol.ChatShellTerminalUnsupported)
}
return p, nil
}
// Input queues data for a running terminal command, in arrival order. It is
// written as typed and kept nowhere else: what the process echoes is output.
func (r *chatShellRunner) Input(sessionID, runID, data string) error {
if data == "" {
return errors.New("input is required")
}
if len(data) > protocol.ChatShellInputLimit {
return errors.New("the input exceeds 16 KiB; send it in parts")
}
if !utf8.ValidString(data) {
return errors.New("input must be UTF-8 text")
}
p, err := r.terminalProcess(sessionID, runID)
if err != nil {
return err
}
select {
case <-p.done:
return errors.New("this command is not running")
case p.input <- []byte(data):
return nil
default:
return errors.New("the command is not reading its input; wait for it or stop it")
}
}
// Resize sets a running terminal command's size and returns its record.
func (r *chatShellRunner) Resize(sessionID, runID string, cols, rows int) (protocol.ChatShellRunRecord, error) {
if cols <= 0 || rows <= 0 {
return protocol.ChatShellRunRecord{}, errors.New("positive cols and rows are required")
}
p, err := r.terminalProcess(sessionID, runID)
if err != nil {
return protocol.ChatShellRunRecord{}, err
}
cols, rows = chatShellTerminalSize(cols, rows)
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return protocol.ChatShellRunRecord{}, errors.New("this command is not running")
}
if err := resizeChatShellTerminal(p.terminal, cols, rows); err != nil {
return protocol.ChatShellRunRecord{}, err
}
p.record.Cols, p.record.Rows = cols, rows
record := p.record
return record, nil
}
// pumpInput writes queued input to the terminal until the command ends. A
// write blocks while the command does not read, which is what fills the queue.
func (p *chatShellProcess) pumpInput() {
for {
select {
case <-p.done:
return
case data := <-p.input:
if _, err := p.terminal.Write(data); err != nil {
return
}
}
}
}