Files

250 lines
8.9 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"
)
// NativeAutomationCallbackID is private to this adapter. Other hook callbacks
// (and operator permission requests) must never be acknowledged as snapshots.
const NativeAutomationCallbackID = "pipelines-native-session-automations-v1"
const MaxAutomationEntries = 128
// 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"`
}
// Task is a native background tool still owned by the hosted CLI. It is kept
// separately from the bounded output spool, so trimming old output cannot erase
// the identity needed by a reattaching server. Missing metadata stays absent.
type Task struct {
ToolUseID string `json:"tool_use_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
TaskType string `json:"task_type,omitempty"`
Command string `json:"command,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
}
// 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"`
// Tasks is the authoritative running background set at End. Nil means an
// older host did not report this capability; a nonnil empty list means it
// knows that no background tasks remain. Reconcile after replay reaches End.
Tasks *[]Task `json:"tasks,omitempty"`
// 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"`
// Automations is the last validated native Stop-hook snapshot. A nil value
// means unknown (including hosts that predate this capability).
Automations *AutomationSnapshot `json:"automations,omitempty"`
}
// AutomationSnapshot contains only bounded native schedule identities and a
// count. This snapshot omits prompts; native CLI events follow the existing
// bounded private spool policy.
type AutomationSnapshot struct {
SessionID string `json:"session_id"`
IDs []string `json:"ids"`
ObservedAtMS int64 `json:"observed_at_ms"`
}
// IsAutomationHook recognizes the private callback without making any claim
// about its optional metadata. Recognized callbacks must always be answered.
func IsAutomationHook(callbackID string) bool { return callbackID == NativeAutomationCallbackID }
// ParseAutomationHook accepts only the SDK's main-thread Stop input. It returns
// false for absent or malformed metadata; callers should still acknowledge a
// callback recognized by IsAutomationHook, while treating the snapshot as
// unknown.
func ParseAutomationHook(callbackID, expectedSession string, input json.RawMessage, nowMS int64) (*AutomationSnapshot, bool) {
if callbackID != NativeAutomationCallbackID || expectedSession == "" || len(input) == 0 || len(input) > 1<<20 {
return nil, false
}
var hook struct {
SessionID string `json:"session_id"`
HookEventName string `json:"hook_event_name"`
SessionCrons *[]struct {
ID string `json:"id"`
} `json:"session_crons"`
}
if json.Unmarshal(input, &hook) != nil || hook.SessionID != expectedSession || hook.HookEventName != "Stop" || hook.SessionCrons == nil || len(*hook.SessionCrons) > MaxAutomationEntries {
return nil, false
}
ids := make([]string, 0, len(*hook.SessionCrons))
seen := map[string]bool{}
for _, cron := range *hook.SessionCrons {
if cron.ID == "" || len(cron.ID) > 256 || seen[cron.ID] {
return nil, false
}
seen[cron.ID] = true
ids = append(ids, cron.ID)
}
return &AutomationSnapshot{SessionID: expectedSession, IDs: ids, ObservedAtMS: nowMS}, true
}
// 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)
}