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.
This commit is contained in:
@@ -0,0 +1,217 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,710 @@
|
||||
package claudehost
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Defaults for a host started without explicit limits.
|
||||
const (
|
||||
DefaultIdle = 20 * time.Minute
|
||||
DefaultMaxDetached = 24 * time.Hour
|
||||
DefaultSpoolLimit = 64 << 20
|
||||
maxLineBytes = 32 << 20
|
||||
stderrRetained = 8 << 10
|
||||
)
|
||||
|
||||
type lineRef struct{ start, end int64 }
|
||||
|
||||
type transition struct {
|
||||
offset int64
|
||||
busy bool
|
||||
}
|
||||
|
||||
type client struct {
|
||||
conn net.Conn
|
||||
writeMu sync.Mutex
|
||||
gone chan struct{}
|
||||
once sync.Once
|
||||
exitSent bool
|
||||
}
|
||||
|
||||
func (c *client) 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
|
||||
}
|
||||
|
||||
func (c *client) close() {
|
||||
c.once.Do(func() {
|
||||
close(c.gone)
|
||||
_ = c.conn.Close()
|
||||
})
|
||||
}
|
||||
|
||||
type host struct {
|
||||
dir string
|
||||
id string
|
||||
paths Paths
|
||||
idle time.Duration
|
||||
maxDetached time.Duration
|
||||
spoolLimit int64
|
||||
listener net.Listener
|
||||
|
||||
cmd *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
stdinMu sync.Mutex
|
||||
|
||||
fileMu sync.RWMutex // guards spool replacement against readers
|
||||
mu sync.Mutex
|
||||
spool *os.File
|
||||
base int64
|
||||
end int64
|
||||
lines []lineRef
|
||||
acked int64
|
||||
trans []transition
|
||||
busy bool
|
||||
// pending maps unanswered CLI control request ids to their offsets.
|
||||
pending map[string]int64
|
||||
initID string
|
||||
init json.RawMessage
|
||||
modelReqs map[string]string
|
||||
modeReqs map[string]string
|
||||
model string
|
||||
mode string
|
||||
exited bool
|
||||
exitErr string
|
||||
exitedAt time.Time
|
||||
stderr strings.Builder
|
||||
changed chan struct{}
|
||||
active *client
|
||||
detached time.Time
|
||||
activity time.Time
|
||||
stopping bool
|
||||
stopped chan struct{}
|
||||
claudeEnd chan struct{}
|
||||
}
|
||||
|
||||
// Main runs a host. args are the host flags, then "--", then the Claude Code
|
||||
// executable and its arguments. The working directory and environment are the
|
||||
// CLI's own. It returns the process exit code.
|
||||
func Main(args []string) int {
|
||||
flags := flag.NewFlagSet("pipelines-claude-host", flag.ContinueOnError)
|
||||
dir := flags.String("dir", "", "private host directory (registry, socket, spool)")
|
||||
id := flags.String("id", "", "Claude session id")
|
||||
idle := flags.Duration("idle", DefaultIdle, "release an idle CLI after this long with no server attached")
|
||||
maxDetached := flags.Duration("max-detached", DefaultMaxDetached, "release the CLI after this long with no server attached, even when busy")
|
||||
spoolLimit := flags.Int64("spool-limit", DefaultSpoolLimit, "bytes of acknowledged output kept in the spool")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
command := flags.Args()
|
||||
if len(command) == 0 || *id == "" || *dir == "" {
|
||||
fmt.Fprintln(os.Stderr, "usage: pipelines-claude-host -dir DIR -id SESSION -- claude ARGS...")
|
||||
return 2
|
||||
}
|
||||
log.SetFlags(log.LstdFlags)
|
||||
log.SetPrefix("claude-host " + *id + ": ")
|
||||
syscall.Umask(0o077)
|
||||
if err := EnsureDir(*dir); err != nil {
|
||||
log.Print(err)
|
||||
return 1
|
||||
}
|
||||
h := &host{
|
||||
dir: *dir, id: *id, paths: PathsFor(*dir, *id), idle: *idle, maxDetached: *maxDetached, spoolLimit: *spoolLimit,
|
||||
pending: map[string]int64{}, modelReqs: map[string]string{}, modeReqs: map[string]string{},
|
||||
changed: make(chan struct{}), stopped: make(chan struct{}), claudeEnd: make(chan struct{}),
|
||||
trans: []transition{{offset: 0, busy: false}}, activity: time.Now(), detached: time.Now(),
|
||||
}
|
||||
h.model, h.mode = flagValue(command, "--model"), flagValue(command, "--permission-mode")
|
||||
if err := h.start(command); err != nil {
|
||||
log.Print(err)
|
||||
fmt.Fprintln(os.Stdout, "error "+strings.ReplaceAll(err.Error(), "\n", " "))
|
||||
return 1
|
||||
}
|
||||
// The server waits for this line, then stops reading our stdout.
|
||||
fmt.Fprintln(os.Stdout, "ready "+h.paths.Socket)
|
||||
if null, err := os.OpenFile(os.DevNull, os.O_RDWR, 0); err == nil {
|
||||
_ = syscall.Dup2(int(null.Fd()), 1)
|
||||
_ = syscall.Dup2(int(null.Fd()), 0)
|
||||
_ = null.Close()
|
||||
}
|
||||
signals := make(chan os.Signal, 2)
|
||||
signal.Ignore(syscall.SIGHUP, syscall.SIGPIPE)
|
||||
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
|
||||
go func() {
|
||||
<-signals
|
||||
h.shutdown("signal")
|
||||
}()
|
||||
go h.accept()
|
||||
go h.watchIdle()
|
||||
<-h.stopped
|
||||
return 0
|
||||
}
|
||||
|
||||
func flagValue(args []string, name string) string {
|
||||
for index, arg := range args {
|
||||
if arg == name && index+1 < len(args) {
|
||||
return args[index+1]
|
||||
}
|
||||
if strings.HasPrefix(arg, name+"=") {
|
||||
return strings.TrimPrefix(arg, name+"=")
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (h *host) start(command []string) error {
|
||||
if conn, err := net.DialTimeout("unix", h.paths.Socket, time.Second); err == nil {
|
||||
_ = conn.Close()
|
||||
return errors.New("a host is already serving this session")
|
||||
}
|
||||
_ = os.Remove(h.paths.Socket)
|
||||
spool, err := os.OpenFile(h.paths.Spool, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.spool = spool
|
||||
listener, err := net.Listen("unix", h.paths.Socket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Chmod(h.paths.Socket, 0o600)
|
||||
h.listener = listener
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
cmd.Env = os.Environ()
|
||||
// Its own process group, so the CLI and its tool subprocesses stop together.
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
_ = listener.Close()
|
||||
_ = os.Remove(h.paths.Socket)
|
||||
return fmt.Errorf("start Claude Code: %w", err)
|
||||
}
|
||||
h.cmd, h.stdin = cmd, stdin
|
||||
cwd, _ := os.Getwd()
|
||||
record := Record{Version: Version, SessionID: h.id, HostPID: os.Getpid(), ClaudePID: cmd.Process.Pid,
|
||||
Socket: h.paths.Socket, Spool: h.paths.Spool, Directory: cwd, Created: time.Now().UnixMilli()}
|
||||
data, _ := json.Marshal(record)
|
||||
if err := writeFileAtomic(h.paths.Record, data); err != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
return err
|
||||
}
|
||||
stderrDone := make(chan struct{})
|
||||
go h.readStderr(stderr, stderrDone)
|
||||
readDone := make(chan struct{})
|
||||
go h.readStdout(stdout, readDone)
|
||||
go func() {
|
||||
err := cmd.Wait()
|
||||
<-readDone
|
||||
select {
|
||||
case <-stderrDone:
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
h.mu.Lock()
|
||||
h.exited = true
|
||||
h.exitedAt = time.Now()
|
||||
if err != nil {
|
||||
h.exitErr = err.Error()
|
||||
}
|
||||
h.broadcastLocked()
|
||||
h.mu.Unlock()
|
||||
close(h.claudeEnd)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *host) readStderr(stderr io.Reader, done chan struct{}) {
|
||||
defer close(done)
|
||||
buffer := make([]byte, 4<<10)
|
||||
for {
|
||||
n, err := stderr.Read(buffer)
|
||||
if n > 0 {
|
||||
h.mu.Lock()
|
||||
if remaining := stderrRetained - h.stderr.Len(); remaining > 0 {
|
||||
if n > remaining {
|
||||
n = remaining
|
||||
}
|
||||
h.stderr.Write(buffer[:n])
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *host) readStdout(stdout io.Reader, done chan struct{}) {
|
||||
defer close(done)
|
||||
reader := bufio.NewReaderSize(stdout, 64<<10)
|
||||
for {
|
||||
line, err := reader.ReadBytes('\n')
|
||||
if len(line) > 0 && len(line) <= maxLineBytes {
|
||||
trimmed := strings.TrimSpace(string(line))
|
||||
if trimmed != "" {
|
||||
h.appendLine([]byte(trimmed))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// broadcastLocked wakes every sender. Callers hold h.mu.
|
||||
func (h *host) broadcastLocked() {
|
||||
close(h.changed)
|
||||
h.changed = make(chan struct{})
|
||||
}
|
||||
|
||||
type snoop struct {
|
||||
Type string `json:"type"`
|
||||
Subtype string `json:"subtype"`
|
||||
RequestID string `json:"request_id"`
|
||||
ParentToolUseID string `json:"parent_tool_use_id"`
|
||||
Request struct {
|
||||
Subtype string `json:"subtype"`
|
||||
Model string `json:"model"`
|
||||
Mode string `json:"mode"`
|
||||
} `json:"request"`
|
||||
Response struct {
|
||||
Subtype string `json:"subtype"`
|
||||
RequestID string `json:"request_id"`
|
||||
Response json.RawMessage `json:"response"`
|
||||
} `json:"response"`
|
||||
}
|
||||
|
||||
func (h *host) setBusyLocked(busy bool, offset int64) {
|
||||
if h.busy == busy {
|
||||
return
|
||||
}
|
||||
h.busy = busy
|
||||
h.trans = append(h.trans, transition{offset: offset, busy: busy})
|
||||
}
|
||||
|
||||
func (h *host) busyAtLocked(offset int64) bool {
|
||||
busy := false
|
||||
for _, t := range h.trans {
|
||||
if t.offset > offset {
|
||||
break
|
||||
}
|
||||
busy = t.busy
|
||||
}
|
||||
return busy
|
||||
}
|
||||
|
||||
func (h *host) appendLine(line []byte) {
|
||||
var env snoop
|
||||
_ = json.Unmarshal(line, &env)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
start := h.end
|
||||
data := append(append([]byte(nil), line...), '\n')
|
||||
h.fileMu.RLock()
|
||||
_, err := h.spool.WriteAt(data, start-h.base)
|
||||
h.fileMu.RUnlock()
|
||||
if err != nil {
|
||||
log.Printf("spool write: %v", err)
|
||||
}
|
||||
h.end += int64(len(data))
|
||||
h.lines = append(h.lines, lineRef{start: start, end: h.end})
|
||||
h.activity = time.Now()
|
||||
switch env.Type {
|
||||
case "control_request":
|
||||
if env.RequestID != "" {
|
||||
h.pending[env.RequestID] = start
|
||||
}
|
||||
case "control_cancel_request":
|
||||
delete(h.pending, env.RequestID)
|
||||
case "control_response":
|
||||
id := env.Response.RequestID
|
||||
if env.Response.Subtype == "success" {
|
||||
if id != "" && id == h.initID {
|
||||
h.init = append(json.RawMessage(nil), env.Response.Response...)
|
||||
}
|
||||
if model, ok := h.modelReqs[id]; ok {
|
||||
h.model = model
|
||||
}
|
||||
if mode, ok := h.modeReqs[id]; ok {
|
||||
h.mode = mode
|
||||
}
|
||||
}
|
||||
delete(h.modelReqs, id)
|
||||
delete(h.modeReqs, id)
|
||||
case "result":
|
||||
h.setBusyLocked(false, h.end)
|
||||
// A finished turn no longer waits on any approval.
|
||||
h.pending = map[string]int64{}
|
||||
case "stream_event", "assistant":
|
||||
if env.ParentToolUseID == "" {
|
||||
h.setBusyLocked(true, start)
|
||||
}
|
||||
}
|
||||
h.compactLocked()
|
||||
h.broadcastLocked()
|
||||
}
|
||||
|
||||
// compactLocked bounds the spool. Acknowledged output beyond the limit is
|
||||
// dropped first; unacknowledged output is dropped only beyond four times the
|
||||
// limit (a server gone for very long), which a reconnecting server sees as a
|
||||
// gap because Acked < Base.
|
||||
func (h *host) compactLocked() {
|
||||
size := h.end - h.base
|
||||
if size <= h.spoolLimit {
|
||||
return
|
||||
}
|
||||
keep := h.acked
|
||||
if h.end-keep > 4*h.spoolLimit {
|
||||
keep = h.end - h.spoolLimit
|
||||
}
|
||||
index := sort.Search(len(h.lines), func(i int) bool { return h.lines[i].start >= keep })
|
||||
if index == 0 || index >= len(h.lines) {
|
||||
return
|
||||
}
|
||||
keep = h.lines[index].start
|
||||
if keep-h.base < size/4 {
|
||||
return // not worth rewriting yet
|
||||
}
|
||||
next, err := os.OpenFile(h.paths.Spool+".next", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.fileMu.Lock()
|
||||
defer h.fileMu.Unlock()
|
||||
if _, err := io.Copy(next, io.NewSectionReader(h.spool, keep-h.base, h.end-keep)); err != nil {
|
||||
_ = next.Close()
|
||||
_ = os.Remove(h.paths.Spool + ".next")
|
||||
return
|
||||
}
|
||||
if err := os.Rename(h.paths.Spool+".next", h.paths.Spool); err != nil {
|
||||
_ = next.Close()
|
||||
return
|
||||
}
|
||||
_ = h.spool.Close()
|
||||
h.spool = next
|
||||
h.base = keep
|
||||
h.lines = append([]lineRef(nil), h.lines[index:]...)
|
||||
}
|
||||
|
||||
func (h *host) statusLocked() *Status {
|
||||
pending := make([]Pending, 0, len(h.pending))
|
||||
for id, offset := range h.pending {
|
||||
pending = append(pending, Pending{ID: id, Offset: offset})
|
||||
}
|
||||
sort.Slice(pending, func(i, j int) bool { return pending[i].Offset < pending[j].Offset })
|
||||
cwd, _ := os.Getwd()
|
||||
status := &Status{
|
||||
Version: Version, SessionID: h.id, HostPID: os.Getpid(),
|
||||
Base: h.base, End: h.end, Acked: h.acked, Busy: h.busy, BusyAtAcked: h.busyAtLocked(h.acked),
|
||||
Init: h.init, Model: h.model, Mode: h.mode, Pending: pending,
|
||||
Exited: h.exited, ExitErr: h.exitErr, Stderr: h.stderr.String(), Directory: cwd,
|
||||
}
|
||||
if h.cmd != nil && h.cmd.Process != nil {
|
||||
status.ClaudePID = h.cmd.Process.Pid
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func (h *host) accept() {
|
||||
for {
|
||||
conn, err := h.listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c := &client{conn: conn, gone: make(chan struct{})}
|
||||
go h.serveClient(c)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *host) serveClient(c *client) {
|
||||
defer h.dropClient(c)
|
||||
reader := bufio.NewReaderSize(c.conn, 64<<10)
|
||||
for {
|
||||
line, err := reader.ReadBytes('\n')
|
||||
if len(strings.TrimSpace(string(line))) > 0 {
|
||||
var frame Frame
|
||||
if json.Unmarshal(line, &frame) != nil {
|
||||
_ = c.send(Frame{Op: OpError, Error: "invalid frame"})
|
||||
} else if !h.handle(c, frame) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *host) dropClient(c *client) {
|
||||
c.close()
|
||||
h.mu.Lock()
|
||||
if h.active == c {
|
||||
h.active = nil
|
||||
h.detached = time.Now()
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// handle runs one client frame; false ends the connection.
|
||||
func (h *host) handle(c *client, frame Frame) bool {
|
||||
switch frame.Op {
|
||||
case OpAttach:
|
||||
h.mu.Lock()
|
||||
previous := h.active
|
||||
h.active = c
|
||||
status := h.statusLocked()
|
||||
h.mu.Unlock()
|
||||
if previous != nil && previous != c {
|
||||
previous.close()
|
||||
}
|
||||
if err := c.send(Frame{Op: OpStatus, Status: status}); err != nil {
|
||||
return false
|
||||
}
|
||||
go h.deliver(c, frame.Offset)
|
||||
case OpIn:
|
||||
h.writeIn(frame.Data)
|
||||
case OpAck:
|
||||
h.mu.Lock()
|
||||
if frame.Offset > h.acked && frame.Offset <= h.end {
|
||||
h.acked = frame.Offset
|
||||
h.trimTransitionsLocked()
|
||||
}
|
||||
h.mu.Unlock()
|
||||
case OpStatus:
|
||||
h.mu.Lock()
|
||||
status := h.statusLocked()
|
||||
h.mu.Unlock()
|
||||
_ = c.send(Frame{Op: OpStatus, Status: status})
|
||||
case OpClose:
|
||||
h.stopClaude()
|
||||
_ = c.send(Frame{Op: OpClosed})
|
||||
h.shutdown("closed")
|
||||
return false
|
||||
default:
|
||||
_ = c.send(Frame{Op: OpError, Error: "unknown op " + frame.Op})
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *host) trimTransitionsLocked() {
|
||||
keep := 0
|
||||
for i, t := range h.trans {
|
||||
if t.offset <= h.acked {
|
||||
keep = i
|
||||
}
|
||||
}
|
||||
h.trans = append([]transition(nil), h.trans[keep:]...)
|
||||
}
|
||||
|
||||
func (h *host) writeIn(data json.RawMessage) {
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
var env snoop
|
||||
_ = json.Unmarshal(data, &env)
|
||||
h.mu.Lock()
|
||||
h.activity = time.Now()
|
||||
switch env.Type {
|
||||
case "user":
|
||||
h.setBusyLocked(true, h.end)
|
||||
case "control_response":
|
||||
delete(h.pending, env.Response.RequestID)
|
||||
case "control_request":
|
||||
switch env.Request.Subtype {
|
||||
case "initialize":
|
||||
h.initID = env.RequestID
|
||||
case "set_model":
|
||||
h.modelReqs[env.RequestID] = env.Request.Model
|
||||
case "set_permission_mode":
|
||||
h.modeReqs[env.RequestID] = env.Request.Mode
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
line := append(append([]byte(nil), data...), '\n')
|
||||
h.stdinMu.Lock()
|
||||
defer h.stdinMu.Unlock()
|
||||
if _, err := h.stdin.Write(line); err != nil {
|
||||
log.Printf("write to Claude Code: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// deliver streams spooled lines from offset, then the exit, to one client.
|
||||
func (h *host) deliver(c *client, offset int64) {
|
||||
cursor := offset
|
||||
for {
|
||||
h.mu.Lock()
|
||||
if h.active != c {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
index := sort.Search(len(h.lines), func(i int) bool { return h.lines[i].start >= cursor })
|
||||
if index < len(h.lines) {
|
||||
ref := h.lines[index]
|
||||
h.fileMu.RLock()
|
||||
h.mu.Unlock()
|
||||
data := make([]byte, ref.end-ref.start)
|
||||
_, err := h.spool.ReadAt(data, ref.start-h.base)
|
||||
h.fileMu.RUnlock()
|
||||
if err != nil {
|
||||
log.Printf("spool read: %v", err)
|
||||
c.close()
|
||||
return
|
||||
}
|
||||
if err := c.send(Frame{Op: OpOut, Offset: ref.start, End: ref.end, Data: json.RawMessage(strings.TrimSpace(string(data)))}); err != nil {
|
||||
c.close()
|
||||
return
|
||||
}
|
||||
cursor = ref.end
|
||||
continue
|
||||
}
|
||||
if h.exited && !c.exitSent {
|
||||
c.exitSent = true
|
||||
status := h.statusLocked()
|
||||
h.mu.Unlock()
|
||||
_ = c.send(Frame{Op: OpExit, Status: status, Error: status.ExitErr})
|
||||
// The server has everything; it closes the connection, then we go.
|
||||
go func() {
|
||||
select {
|
||||
case <-c.gone:
|
||||
case <-time.After(30 * time.Second):
|
||||
}
|
||||
h.shutdown("exited")
|
||||
}()
|
||||
continue
|
||||
}
|
||||
changed := h.changed
|
||||
h.mu.Unlock()
|
||||
select {
|
||||
case <-changed:
|
||||
case <-c.gone:
|
||||
return
|
||||
case <-h.stopped:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stopClaude ends the CLI: stdin EOF, then an interrupt, then a kill, to the
|
||||
// CLI's whole process group.
|
||||
func (h *host) stopClaude() {
|
||||
if h.cmd == nil || h.cmd.Process == nil {
|
||||
return
|
||||
}
|
||||
h.stdinMu.Lock()
|
||||
_ = h.stdin.Close()
|
||||
h.stdinMu.Unlock()
|
||||
pid := h.cmd.Process.Pid
|
||||
select {
|
||||
case <-h.claudeEnd:
|
||||
return
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
}
|
||||
_ = syscall.Kill(-pid, syscall.SIGINT)
|
||||
select {
|
||||
case <-h.claudeEnd:
|
||||
return
|
||||
case <-time.After(3 * time.Second):
|
||||
}
|
||||
_ = syscall.Kill(-pid, syscall.SIGKILL)
|
||||
select {
|
||||
case <-h.claudeEnd:
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
|
||||
// shutdown stops the CLI, removes the host files and ends Main.
|
||||
func (h *host) shutdown(reason string) {
|
||||
h.mu.Lock()
|
||||
if h.stopping {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
h.stopping = true
|
||||
active := h.active
|
||||
h.mu.Unlock()
|
||||
log.Printf("stopping (%s)", reason)
|
||||
h.stopClaude()
|
||||
_ = h.listener.Close()
|
||||
Remove(h.dir, h.id)
|
||||
_ = os.Remove(h.paths.Spool + ".next")
|
||||
if active != nil {
|
||||
active.close()
|
||||
}
|
||||
close(h.stopped)
|
||||
}
|
||||
|
||||
// watchIdle releases the CLI while no server is attached: after the idle
|
||||
// expiry when nothing is in flight (the same release the server applies), and
|
||||
// after maxDetached regardless. A CLI that exited with nobody attached is
|
||||
// cleaned up after the idle expiry.
|
||||
func (h *host) watchIdle() {
|
||||
tick := h.idle / 10
|
||||
if tick > 5*time.Second {
|
||||
tick = 5 * time.Second
|
||||
}
|
||||
if tick < 50*time.Millisecond {
|
||||
tick = 50 * time.Millisecond
|
||||
}
|
||||
ticker := time.NewTicker(tick)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-h.stopped:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
now := time.Now()
|
||||
h.mu.Lock()
|
||||
attached := h.active != nil
|
||||
idle := !h.busy && len(h.pending) == 0 && now.Sub(h.detached) > h.idle && now.Sub(h.activity) > h.idle
|
||||
tooLong := now.Sub(h.detached) > h.maxDetached
|
||||
exitedLong := h.exited && now.Sub(h.exitedAt) > h.idle
|
||||
h.mu.Unlock()
|
||||
if attached {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case exitedLong:
|
||||
h.shutdown("exited with no server attached")
|
||||
return
|
||||
case idle:
|
||||
h.shutdown("idle with no server attached")
|
||||
return
|
||||
case tooLong:
|
||||
h.shutdown("no server attached for " + h.maxDetached.String())
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// Package claudehost keeps one Claude Code CLI process alive across Pipelines
|
||||
// server restarts.
|
||||
//
|
||||
// The server cannot own a `claude -p` process directly and also restart: the
|
||||
// CLI's stdin/stdout pipes die with their parent. A host is a small helper
|
||||
// process in its own session that owns those pipes instead. It spools the
|
||||
// CLI's stream-json output to a bounded per-session file with byte offsets and
|
||||
// serves one local Unix socket (0600, in a 0700 directory) on which the server
|
||||
// writes stdin frames, reads output from an offset, acknowledges what it has
|
||||
// processed, and finally closes the host. A restarted server finds live hosts
|
||||
// through their registry files, reconnects and replays from its last
|
||||
// acknowledged offset.
|
||||
//
|
||||
// The wire format is one JSON object per line in both directions.
|
||||
package claudehost
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Version is the host protocol version reported in every status.
|
||||
const Version = 1
|
||||
|
||||
// Client-to-host operations.
|
||||
const (
|
||||
// OpAttach starts (or restarts) delivery from Frame.Offset. The host
|
||||
// replies with OpStatus, then streams OpOut frames. A newer attach replaces
|
||||
// an older connection.
|
||||
OpAttach = "attach"
|
||||
// OpIn writes Frame.Data, one JSON line, to the CLI's stdin.
|
||||
OpIn = "in"
|
||||
// OpAck commits that output up to Frame.Offset has been processed.
|
||||
OpAck = "ack"
|
||||
// OpStatus asks for a status snapshot without changing delivery.
|
||||
OpStatus = "status"
|
||||
// OpClose stops the CLI and the host. The host replies OpClosed.
|
||||
OpClose = "close"
|
||||
)
|
||||
|
||||
// Host-to-client operations.
|
||||
const (
|
||||
OpOut = "out"
|
||||
OpExit = "exit"
|
||||
OpClosed = "closed"
|
||||
OpError = "error"
|
||||
)
|
||||
|
||||
// Frame is one line on the socket.
|
||||
type Frame struct {
|
||||
Op string `json:"op"`
|
||||
Offset int64 `json:"offset,omitempty"`
|
||||
End int64 `json:"end,omitempty"`
|
||||
Data json.RawMessage `json:"data,omitempty"`
|
||||
Status *Status `json:"status,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Pending is a CLI control request (can_use_tool, a hook) that nobody has
|
||||
// answered yet. It survives a disconnected server.
|
||||
type Pending struct {
|
||||
ID string `json:"id"`
|
||||
Offset int64 `json:"offset"`
|
||||
}
|
||||
|
||||
// Status is the host's snapshot of its CLI.
|
||||
type Status struct {
|
||||
Version int `json:"version"`
|
||||
SessionID string `json:"session_id"`
|
||||
HostPID int `json:"host_pid"`
|
||||
ClaudePID int `json:"claude_pid"`
|
||||
// Base is the oldest offset still in the spool; End is the offset after the
|
||||
// last spooled line; Acked is the last offset a client committed.
|
||||
Base int64 `json:"base"`
|
||||
End int64 `json:"end"`
|
||||
Acked int64 `json:"acked"`
|
||||
// Busy is whether a turn is in flight now; BusyAtAcked is whether one was
|
||||
// in flight at the Acked offset, which is where a reconnecting server's
|
||||
// live processing resumes.
|
||||
Busy bool `json:"busy"`
|
||||
BusyAtAcked bool `json:"busy_at_acked"`
|
||||
// Init is the CLI's initialize response (models, account), so a
|
||||
// reconnecting server does not initialize the CLI twice.
|
||||
Init json.RawMessage `json:"init,omitempty"`
|
||||
// Model and Mode are the CLI's model and permission mode as last applied
|
||||
// (start flags, then successful set_model / set_permission_mode).
|
||||
Model string `json:"model,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Pending []Pending `json:"pending"`
|
||||
Exited bool `json:"exited,omitempty"`
|
||||
ExitErr string `json:"exit_error,omitempty"`
|
||||
Stderr string `json:"stderr,omitempty"`
|
||||
// Directory is the CLI's working directory.
|
||||
Directory string `json:"directory,omitempty"`
|
||||
}
|
||||
|
||||
// Record is the registry file a host writes next to its socket so a
|
||||
// restarted server can find it.
|
||||
type Record struct {
|
||||
Version int `json:"version"`
|
||||
SessionID string `json:"session_id"`
|
||||
HostPID int `json:"host_pid"`
|
||||
ClaudePID int `json:"claude_pid"`
|
||||
Socket string `json:"socket"`
|
||||
Spool string `json:"spool"`
|
||||
Directory string `json:"directory"`
|
||||
Created int64 `json:"created"`
|
||||
}
|
||||
|
||||
// Key is the short file name used for a session's host files. Unix socket
|
||||
// paths are limited to about 100 bytes, so the session id is hashed.
|
||||
func Key(sessionID string) string {
|
||||
sum := sha256.Sum256([]byte(sessionID))
|
||||
return hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
// Paths are one session's files inside a host directory.
|
||||
type Paths struct {
|
||||
Socket, Record, Spool, Log string
|
||||
}
|
||||
|
||||
func PathsFor(dir, sessionID string) Paths {
|
||||
key := Key(sessionID)
|
||||
return Paths{
|
||||
Socket: filepath.Join(dir, key+".sock"),
|
||||
Record: filepath.Join(dir, key+".json"),
|
||||
Spool: filepath.Join(dir, key+".spool"),
|
||||
Log: filepath.Join(dir, key+".log"),
|
||||
}
|
||||
}
|
||||
|
||||
// EnsureDir creates a private host directory.
|
||||
func EnsureDir(dir string) error {
|
||||
if strings.TrimSpace(dir) == "" || !filepath.IsAbs(dir) {
|
||||
return errors.New("the Claude host directory must be absolute")
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(dir, 0o700)
|
||||
}
|
||||
|
||||
// Records lists the registry files in dir. Unreadable files are skipped.
|
||||
func Records(dir string) []Record {
|
||||
matches, _ := filepath.Glob(filepath.Join(dir, "*.json"))
|
||||
records := make([]Record, 0, len(matches))
|
||||
for _, path := range matches {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var record Record
|
||||
if json.Unmarshal(data, &record) != nil || record.SessionID == "" || record.Socket == "" {
|
||||
continue
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
// Remove deletes one session's host files.
|
||||
func Remove(dir, sessionID string) {
|
||||
paths := PathsFor(dir, sessionID)
|
||||
for _, path := range []string{paths.Record, paths.Socket, paths.Spool, paths.Log} {
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
}
|
||||
|
||||
func writeFileAtomic(path string, data []byte) error {
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
Reference in New Issue
Block a user