package claudehost import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "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() } // Status reads a snapshot without attaching or replacing the active delivery // client. It is bounded by ctx and closes the short-lived connection. func ReadStatus(ctx context.Context, socket string) (*Status, error) { if ctx == nil { ctx = context.Background() } deadline := time.Now().Add(3 * time.Second) if d, ok := ctx.Deadline(); ok && d.Before(deadline) { deadline = d } opCtx, cancel := context.WithDeadline(ctx, deadline) defer cancel() dialer := net.Dialer{} conn, err := dialer.DialContext(opCtx, "unix", socket) if err != nil { return nil, err } defer conn.Close() stopCancel := make(chan struct{}) go func() { select { case <-opCtx.Done(): _ = conn.Close() case <-stopCancel: } }() defer close(stopCancel) if err := conn.SetDeadline(deadline); err != nil { return nil, err } data, err := json.Marshal(Frame{Op: OpStatus}) if err != nil { return nil, err } data = append(data, '\n') if _, err := conn.Write(data); err != nil { if opCtx.Err() != nil { return nil, opCtx.Err() } return nil, err } const maxStatusBytes = 4 << 20 line, err := bufio.NewReader(io.LimitReader(conn, maxStatusBytes+1)).ReadBytes('\n') if err != nil { if opCtx.Err() != nil { return nil, opCtx.Err() } return nil, err } if len(line) > maxStatusBytes { return nil, fmt.Errorf("host status exceeds read limit") } var frame Frame if err := json.Unmarshal(line, &frame); err != nil || frame.Op != OpStatus || frame.Status == nil { return nil, fmt.Errorf("unexpected host status response") } return frame.Status, nil } // 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) }