Files
pipelines/internal/claude/process.go
T

373 lines
9.2 KiB
Go

package claude
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"sync"
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// initializeTimeout bounds the CLI's first handshake. A cold start loads the
// operator's skills/plugins, so this is deliberately generous but still finite.
const initializeTimeout = 60 * time.Second
const controlRequestTimeout = 20 * time.Second
const maxLineBytes = 32 << 20
var errProcessClosed = errors.New("Claude Code process is not running")
// process is one owned CLI process for one session. Requests and responses are
// multiplexed on stdin/stdout; the reader goroutine is the only consumer, so a
// control request is always awaited by a different goroutine.
type process struct {
session *session
cmd *exec.Cmd
stdin io.WriteCloser
writeMu sync.Mutex
reqMu sync.Mutex
nextReq atomic.Uint64
pending map[string]chan controlReply
mu sync.Mutex
stderr strings.Builder
exited bool
exitErr error
done chan struct{}
stderrDone chan struct{}
}
type controlReply struct {
response json.RawMessage
err string
}
// spawn starts the CLI in the session directory. A session whose transcript
// already exists resumes it; a new one pins the id we recorded at create time.
func (s *session) spawn(ctx context.Context) (*process, error) {
if err := s.requireBinary(); err != nil {
return nil, err
}
if strings.TrimSpace(s.directory) == "" {
return nil, errors.New("a Claude session needs an existing absolute directory")
}
if info, err := os.Stat(s.directory); err != nil || !info.IsDir() {
return nil, fmt.Errorf("Claude session directory is not available: %s", s.directory)
}
args := []string{
"-p",
"--input-format", "stream-json",
"--output-format", "stream-json",
"--verbose",
"--include-partial-messages",
"--permission-prompt-tool=stdio",
"--permission-prompts", "host",
}
if findTranscriptFile(s.id) != "" {
args = append(args, "--resume", s.id)
} else {
args = append(args, "--session-id", s.id)
}
if s.model != "" {
args = append(args, "--model", s.model)
}
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
cmd.Env = os.Environ()
cmd.WaitDelay = 5 * time.Second
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start Claude Code: %w", err)
}
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{})}
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
// The CLI holds can_use_tool requests until the host has initialized. Do that
// before any user turn so an approval is never silently denied.
initCtx, cancel := context.WithTimeout(ctx, initializeTimeout)
defer cancel()
models, err := p.initialize(initCtx)
if err != nil {
p.close()
return nil, err
}
s.mu.Lock()
s.models = models
s.lastErr = ""
s.mu.Unlock()
return p, nil
}
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, error) {
raw, err := p.request(ctx, "initialize", map[string]any{"subtype": "initialize"})
if err != nil {
return nil, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
}
var reply struct {
Models []struct {
Value string `json:"value"`
ResolvedModel string `json:"resolvedModel"`
DisplayName string `json:"displayName"`
Description string `json:"description"`
} `json:"models"`
}
if err := json.Unmarshal(raw, &reply); err != nil {
return nil, errors.New("Claude Code returned an invalid initialize response")
}
models := make([]protocol.ChatModel, 0, len(reply.Models))
for _, m := range reply.Models {
if strings.TrimSpace(m.Value) == "" {
continue
}
name := m.DisplayName
if name == "" {
name = m.Value
}
models = append(models, protocol.ChatModel{ID: m.Value, Provider: Backend, Name: name})
}
if len(models) == 0 {
return nil, errors.New("Claude Code reported no models; check that the CLI is signed in")
}
return models, nil
}
// request sends one control request and waits for its control_response.
func (p *process) request(ctx context.Context, subtype string, payload map[string]any) (json.RawMessage, error) {
if payload == nil {
payload = map[string]any{}
}
payload["subtype"] = subtype
id := fmt.Sprintf("pipelines-%d-%d", time.Now().UnixNano(), p.nextReq.Add(1))
ch := make(chan controlReply, 1)
p.mu.Lock()
if p.exited {
p.mu.Unlock()
return nil, errProcessClosed
}
p.pending[id] = ch
p.mu.Unlock()
err := p.write(map[string]any{"type": "control_request", "request_id": id, "request": payload})
if err != nil {
p.mu.Lock()
delete(p.pending, id)
p.mu.Unlock()
return nil, err
}
select {
case <-ctx.Done():
p.mu.Lock()
delete(p.pending, id)
p.mu.Unlock()
return nil, ctx.Err()
case reply := <-ch:
if reply.err != "" {
return nil, errors.New(reply.err)
}
return reply.response, nil
case <-p.done:
return nil, errProcessClosed
}
}
// respond answers one CLI-initiated control request.
func (p *process) respond(requestID string, response any) error {
return p.write(map[string]any{
"type": "control_response",
"response": map[string]any{"subtype": "success", "request_id": requestID, "response": response},
})
}
func (p *process) write(value any) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
data = append(data, '\n')
p.writeMu.Lock()
defer p.writeMu.Unlock()
p.mu.Lock()
exited := p.exited
p.mu.Unlock()
if exited {
return errProcessClosed
}
if _, err := p.stdin.Write(data); err != nil {
return fmt.Errorf("write to Claude Code: %w", err)
}
return nil
}
func (p *process) readStderr(stderr io.Reader) {
defer close(p.stderrDone)
buffer := make([]byte, 4<<10)
for {
n, err := stderr.Read(buffer)
if n > 0 {
p.mu.Lock()
if p.stderr.Len() < stderrRetained {
remaining := stderrRetained - p.stderr.Len()
if n > remaining {
p.stderr.Write(buffer[:remaining])
} else {
p.stderr.Write(buffer[:n])
}
}
p.mu.Unlock()
}
if err != nil {
return
}
}
}
func (p *process) readStdout(stdout io.Reader) {
scanner := bufio.NewScanner(stdout)
scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
p.session.handleLine(p, line)
}
}
func (p *process) wait() {
err := p.cmd.Wait()
select {
case <-p.stderrDone:
case <-time.After(time.Second):
}
p.finish(err)
}
func (p *process) finish(err error) {
p.mu.Lock()
if p.exited {
p.mu.Unlock()
return
}
p.exited = true
p.exitErr = err
pending := p.pending
p.pending = map[string]chan controlReply{}
close(p.done)
p.mu.Unlock()
for id, ch := range pending {
select {
case ch <- controlReply{err: "Claude Code exited before answering " + id}:
default:
}
}
_ = p.stdin.Close()
p.session.processExit(p, err)
}
func (p *process) close() {
p.mu.Lock()
exited := p.exited
p.mu.Unlock()
if exited {
return
}
_ = p.stdin.Close()
if p.cmd.Process != nil {
_ = p.cmd.Process.Signal(os.Interrupt)
}
select {
case <-p.done:
case <-time.After(3 * time.Second):
if p.cmd.Process != nil {
_ = p.cmd.Process.Kill()
}
}
}
// diagnostic returns a short stderr tail for an actionable failure message.
func (p *process) diagnostic() string {
p.mu.Lock()
defer p.mu.Unlock()
text := strings.TrimSpace(p.stderr.String())
if text == "" {
return ""
}
if len(text) > 600 {
text = text[len(text)-600:]
}
return ": " + strings.ReplaceAll(text, "\n", " ")
}
// processExit settles a turn whose process disappeared instead of leaving the
// web spinner and its Stop control running forever.
func (s *session) processExit(p *process, err error) {
diagnostic := ""
if err != nil {
diagnostic = err.Error()
}
if tail := p.diagnostic(); tail != "" {
diagnostic += tail
}
s.mu.Lock()
if s.proc != p {
s.mu.Unlock()
// A resumed replacement already owns the session.
return
}
s.proc = nil
s.lastErr = strings.TrimSpace(diagnostic)
s.approvals = map[string]*pendingApproval{}
s.forms = map[string]*pendingForm{}
running := s.running
turn := s.turnID
s.running = false
s.turnID = ""
s.streamBlocks = map[int]blockState{}
s.streamText = map[int]string{}
s.streamOrdinals = map[string]int{}
s.mu.Unlock()
if !running {
return
}
message := "Claude Code exited before the turn finished"
if strings.TrimSpace(diagnostic) != "" {
message += ": " + strings.TrimSpace(diagnostic)
}
s.emit(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: turn,
MessageID: "claude-exit-" + turn,
Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: "claude-exit-" + turn,
Name: "Claude Code",
State: &protocol.ChatToolState{
Status: protocol.ChatToolError,
Error: &protocol.ChatError{Type: "process", Message: boundedText(message, 2<<10)},
},
},
})
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
}