c810437aa5
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.
181 lines
5.8 KiB
Go
181 lines
5.8 KiB
Go
// 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)
|
|
}
|