Files
pipelines/internal/claudehost/client.go
T
alan c810437aa5 Claude Code chats survive server restarts in a detachable host
A pipelines-claude-host process owns each claude -p CLI and its pipes,
spools its stream-json output with offsets and serves a private Unix
socket. The server detaches on shutdown and reattaches on start,
replaying the spool to rebuild turns, approvals, questions, background
tasks and the live model. Explicit close, idle release and CLI exit stop
the host; a crashed host falls back to --resume with a notice.
2026-11-04 16:09:56 +00:00

218 lines
5.8 KiB
Go

package claudehost
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
// Conn is a server's connection to one host.
type Conn struct {
conn net.Conn
reader *bufio.Reader
writeMu sync.Mutex
}
// Dial connects to a host socket.
func Dial(socket string, timeout time.Duration) (*Conn, error) {
conn, err := net.DialTimeout("unix", socket, timeout)
if err != nil {
return nil, err
}
return &Conn{conn: conn, reader: bufio.NewReaderSize(conn, 256<<10)}, nil
}
// Send writes one frame.
func (c *Conn) Send(frame Frame) error {
data, err := json.Marshal(frame)
if err != nil {
return err
}
data = append(data, '\n')
c.writeMu.Lock()
defer c.writeMu.Unlock()
_, err = c.conn.Write(data)
return err
}
// Recv reads one frame.
func (c *Conn) Recv() (Frame, error) {
line, err := c.reader.ReadBytes('\n')
if err != nil && len(strings.TrimSpace(string(line))) == 0 {
return Frame{}, err
}
var frame Frame
if err := json.Unmarshal(line, &frame); err != nil {
return Frame{}, fmt.Errorf("invalid host frame: %w", err)
}
return frame, nil
}
// Buffered reports whether more frames are already read from the socket.
func (c *Conn) Buffered() bool { return c.reader.Buffered() > 0 }
func (c *Conn) Close() error { return c.conn.Close() }
// Attach dials socket and starts delivery from offset. It returns the status
// the host replied with; output frames follow on the connection.
func Attach(socket string, offset int64, timeout time.Duration) (*Conn, *Status, error) {
conn, err := Dial(socket, timeout)
if err != nil {
return nil, nil, err
}
_ = conn.conn.SetDeadline(time.Now().Add(timeout))
if err := conn.Send(Frame{Op: OpAttach, Offset: offset}); err != nil {
conn.Close()
return nil, nil, err
}
frame, err := conn.Recv()
if err != nil {
conn.Close()
return nil, nil, err
}
_ = conn.conn.SetDeadline(time.Time{})
if frame.Op != OpStatus || frame.Status == nil {
conn.Close()
return nil, nil, fmt.Errorf("unexpected host reply %q", frame.Op)
}
return conn, frame.Status, nil
}
// SpawnOptions starts one host.
type SpawnOptions struct {
// HostBinary is the pipelines-claude-host executable.
HostBinary string
// HostArgs are extra arguments placed before the host flags (a test binary
// uses them to select host mode).
HostArgs []string
Dir string
SessionID string
Claude string
Args []string
Env []string
Cwd string
Idle time.Duration
}
// Spawn starts a host in its own session, so it outlives the caller, and
// waits until its socket is serving. The caller reaps the returned command.
func Spawn(ctx context.Context, options SpawnOptions) (*exec.Cmd, error) {
if err := EnsureDir(options.Dir); err != nil {
return nil, err
}
paths := PathsFor(options.Dir, options.SessionID)
args := append([]string(nil), options.HostArgs...)
args = append(args, "-dir", options.Dir, "-id", options.SessionID)
if options.Idle > 0 {
args = append(args, "-idle", options.Idle.String())
}
args = append(args, "--", options.Claude)
args = append(args, options.Args...)
cmd := exec.Command(options.HostBinary, args...)
cmd.Dir = options.Cwd
cmd.Env = options.Env
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
logFile, err := os.OpenFile(paths.Log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
return nil, err
}
defer logFile.Close()
cmd.Stderr = logFile
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start the Claude Code host: %w", err)
}
type ready struct {
line string
err error
}
result := make(chan ready, 1)
go func() {
line, err := bufio.NewReader(stdout).ReadString('\n')
result <- ready{line: strings.TrimSpace(line), err: err}
}()
timer := time.NewTimer(15 * time.Second)
defer timer.Stop()
fail := func(err error) (*exec.Cmd, error) {
_ = cmd.Process.Kill()
_ = cmd.Wait()
return nil, err
}
select {
case <-ctx.Done():
return fail(ctx.Err())
case <-timer.C:
return fail(errors.New("the Claude Code host did not start in time"))
case r := <-result:
if strings.HasPrefix(r.line, "ready ") {
return cmd, nil
}
message := strings.TrimPrefix(r.line, "error ")
if message == "" {
message = "the Claude Code host exited during start"
if data, err := os.ReadFile(paths.Log); err == nil {
if tail := strings.TrimSpace(string(data)); tail != "" {
if len(tail) > 400 {
tail = tail[len(tail)-400:]
}
message += ": " + tail
}
}
}
return fail(errors.New(message))
}
}
// ProcessMatches reports whether pid is alive and its command line mentions
// every needle, so a recorded pid that the system reused is never signalled.
func ProcessMatches(pid int, needles ...string) bool {
if pid <= 1 {
return false
}
if syscall.Kill(pid, 0) != nil {
return false
}
out, err := exec.Command("ps", "-o", "command=", "-p", strconv.Itoa(pid)).Output()
if err != nil {
return false
}
command := string(out)
for _, needle := range needles {
if !strings.Contains(command, needle) {
return false
}
}
return true
}
// KillStale stops what a dead or unreachable host left behind: the host
// itself and its CLI's process group, each only when its command line still
// names the session. It then removes the session's host files.
func KillStale(dir string, record Record) {
if ProcessMatches(record.HostPID, record.SessionID) {
_ = syscall.Kill(record.HostPID, syscall.SIGKILL)
}
if ProcessMatches(record.ClaudePID, record.SessionID) {
_ = syscall.Kill(-record.ClaudePID, syscall.SIGTERM)
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) && syscall.Kill(record.ClaudePID, 0) == nil {
time.Sleep(50 * time.Millisecond)
}
_ = syscall.Kill(-record.ClaudePID, syscall.SIGKILL)
}
Remove(dir, record.SessionID)
}