Files
alan 06001697c8 Add per-chat thinking levels for Codex, Claude Code and OpenCode
Codex: model/list supportedReasoningEfforts per model, turn/start effort,
thread reasoningEffort as the current level. Claude Code: initialize
supportedEffortLevels, apply_flag_settings effortLevel at the next turn
start. OpenCode v2: model variants via the session model endpoint.
chat_effort sets a level; rows and chat_models carry the levels; Codex and
Claude levels persist in operator_sessions.chat_effort and are re-applied
before every turn.
2026-11-09 20:07:41 +00:00

495 lines
13 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/claudehost"
"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{}
// mode is the permission mode this process runs in, guarded by the
// session's mu: set at spawn and after a confirmed set_permission_mode.
mode string
// effort is the thinking level this process was told with
// apply_flag_settings, guarded by the session's mu; "" until then.
effort string
// link is set when a detachable host owns the CLI (hosted.go); cmd and
// stdin are then unused.
link *hostLink
// ready closes once a reattached process has replayed the output it
// missed; a process this server started is ready at once.
ready chan struct{}
readyOnce sync.Once
// models, account and appliedModel carry an attached host's
// initialize state until the session adopts it.
models []protocol.ChatModel
account accountIdentity
appliedModel string
automations *claudehost.AutomationSnapshot
}
func newProcess(s *session, mode string) *process {
return &process{session: s, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), ready: make(chan struct{}), mode: mode}
}
type controlReply struct {
response json.RawMessage
err string
}
// cliArgs builds the CLI arguments for one spawn and returns the permission
// mode it applied. resume continues an existing transcript; otherwise the CLI
// pins the id recorded at create time. A known chat title is passed as --name,
// which Claude Code records as the session's display name, so `claude --resume`
// in a terminal lists the chat by its title.
func (s *session) cliArgs(resume bool) ([]string, string) {
args := []string{
"-p",
"--input-format", "stream-json",
"--output-format", "stream-json",
"--verbose",
"--include-partial-messages",
"--permission-prompt-tool=stdio",
"--permission-prompts", "host",
}
if resume {
args = append(args, "--resume", s.id)
} else {
args = append(args, "--session-id", s.id)
}
s.mu.Lock()
model, mode, title, toolsOff := s.model, s.mode, s.title, s.toolsOff
s.mu.Unlock()
if !toolsOff {
args = append(args, pipelinesToolArgs(s.id)...)
}
if model != "" {
args = append(args, "--model", model)
}
if mode != "" && mode != defaultMode {
args = append(args, "--permission-mode", mode)
}
if name := sessionDisplayName(title); name != "" {
args = append(args, "--name", name)
}
return args, mode
}
// sessionDisplayName folds a chat title onto one line for the CLI's session name.
func sessionDisplayName(title string) string {
return strings.Join(strings.Fields(title), " ")
}
// 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.
// With hosting configured the CLI runs in a detachable host (hosted.go).
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)
}
if p := s.existingHost(); p != nil {
return p, nil
}
p, err := s.spawnOnce(ctx)
if err == nil || ctx.Err() != nil || !s.disableTools(err) {
return p, err
}
if p := s.existingHost(); p != nil {
return p, nil
}
return s.spawnOnce(ctx)
}
// spawnOnce starts and initializes one CLI process with the current arguments.
func (s *session) spawnOnce(ctx context.Context) (*process, error) {
args, mode := s.cliArgs(findTranscriptFile(s.id) != "")
env, notices := s.chat.processEnv(ctx, s.directory)
s.mu.Lock()
s.envNotices = notices
s.mu.Unlock()
var p *process
var err error
if s.chat.hostDir != "" {
p, err = s.startHosted(ctx, args, mode, env)
} else {
p, err = s.startDirect(args, mode, env)
}
if err != nil {
return nil, err
}
// 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, account, err := p.initialize(initCtx)
if err != nil {
p.close()
return nil, err
}
s.mu.Lock()
s.models = models
s.account = account
s.chat.rememberCatalog(models)
s.lastErr = ""
s.mu.Unlock()
return p, nil
}
// startDirect runs the CLI as this server's own child.
func (s *session) startDirect(args []string, mode string, env []string) (*process, error) {
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
cmd.Env = env
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 := newProcess(s, mode)
p.cmd, p.stdin = cmd, stdin
p.markReady()
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
return p, nil
}
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, error) {
raw, err := p.request(ctx, "initialize", map[string]any{
"hooks": map[string]any{"Stop": []any{map[string]any{
"hookCallbackIds": []string{claudehost.NativeAutomationCallbackID},
"timeout": 5, "onFailure": "continue",
}}},
})
if err != nil {
return nil, accountIdentity{}, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
}
return parseInitialize(raw)
}
// parseInitialize reads the CLI's initialize response: its model catalog and
// signed-in account.
func parseInitialize(raw json.RawMessage) ([]protocol.ChatModel, accountIdentity, error) {
var reply struct {
Models []struct {
Value string `json:"value"`
ResolvedModel string `json:"resolvedModel"`
DisplayName string `json:"displayName"`
Description string `json:"description"`
SupportsEffort bool `json:"supportsEffort"`
SupportedEffortLevels []string `json:"supportedEffortLevels"`
} `json:"models"`
Account json.RawMessage `json:"account"`
}
if err := json.Unmarshal(raw, &reply); err != nil {
return nil, accountIdentity{}, 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, Resolved: m.ResolvedModel, Efforts: effortLevels(m.SupportsEffort, m.SupportedEffortLevels)})
}
if len(models) == 0 {
return nil, accountIdentity{}, errors.New("Claude Code reported no models; check that the CLI is signed in")
}
return models, decodeAccountIdentity(reply.Account), 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
}
p.writeMu.Lock()
defer p.writeMu.Unlock()
p.mu.Lock()
exited := p.exited
p.mu.Unlock()
if exited {
return errProcessClosed
}
if p.link != nil {
return p.link.send(claudehost.Frame{Op: claudehost.OpIn, Data: data})
}
data = append(data, '\n')
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:
}
}
if p.stdin != nil {
_ = p.stdin.Close()
}
p.session.processExit(p, err)
}
func (p *process) close() {
p.mu.Lock()
exited := p.exited
p.mu.Unlock()
if exited {
return
}
if p.link != nil {
p.closeHosted()
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.steered = 0
s.awaitFollowUp = false
s.resetStreamLocked()
// Background commands and subagents run inside the CLI process, so its
// exit ends them: report each as exited, or it would stay "running" (in the
// chat list and in chat_shells) with nothing left to report its end.
ended := s.endShellsLocked()
s.mu.Unlock()
for _, shell := range ended {
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell})
}
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}})
}