Files
pipelines/internal/claude/chat.go
T

704 lines
20 KiB
Go

package claude
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Create records one Claude session. The CLI process starts on the first
// prompt, so creating a chat is fast and does not require a signed-in CLI yet.
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
directory = strings.TrimSpace(directory)
if directory == "" {
return protocol.ChatSession{}, errors.New("a directory is required")
}
if !filepath.IsAbs(directory) {
return protocol.ChatSession{}, errors.New("the chat directory must be absolute")
}
absolute, err := filepath.Abs(directory)
if err != nil {
return protocol.ChatSession{}, err
}
if info, err := os.Stat(absolute); err != nil || !info.IsDir() {
return protocol.ChatSession{}, errors.New("the chat directory is not an existing directory")
}
id, err := newSessionID()
if err != nil {
return protocol.ChatSession{}, err
}
title = strings.TrimSpace(title)
s := c.sessionFor(id, absolute)
s.mu.Lock()
s.title = title
s.createdAt = time.Now().UnixMilli()
s.mu.Unlock()
return protocol.ChatSession{
ID: id,
Backend: Backend,
Title: title,
ModelProvider: Backend,
Directory: absolute,
CreatedAt: s.createdAt,
UpdatedAt: s.createdAt,
Tag: protocol.ChatSessionTagOperator,
}, nil
}
// Session resolves one session from memory or from its retained transcript, so
// a registry row survives a server restart.
func (c *Chat) Session(ctx context.Context, id string) (protocol.ChatSession, bool, error) {
if s := c.session(id); s != nil {
s.mu.Lock()
session := s.chatSessionLocked()
s.mu.Unlock()
return session, true, nil
}
meta, ok := transcriptSession(id)
if !ok {
return protocol.ChatSession{}, false, nil
}
return meta, true, nil
}
// Sessions lists sessions this process has opened. Registry rows for sessions
// from an earlier server are resolved by the manager through Session.
func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
c.mu.Lock()
states := make([]*session, 0, len(c.sessions))
for _, s := range c.sessions {
states = append(states, s)
}
c.mu.Unlock()
sessions := make([]protocol.ChatSession, 0, len(states))
for _, s := range states {
s.mu.Lock()
sessions = append(sessions, s.chatSessionLocked())
s.mu.Unlock()
}
sort.Slice(sessions, func(i, j int) bool { return sessions[i].ID < sessions[j].ID })
return sessions, nil
}
func (s *session) chatSessionLocked() protocol.ChatSession {
model := s.modelActual
if model == "" {
model = s.model
}
return protocol.ChatSession{
ID: s.id,
Backend: Backend,
Title: s.title,
Model: model,
ModelProvider: Backend,
Directory: s.directory,
CreatedAt: s.createdAt,
UpdatedAt: s.lastUsed.UnixMilli(),
}
}
// Prompt starts one turn with the default model selection.
func (c *Chat) Prompt(ctx context.Context, id, text string) error {
return c.PromptWithMessageID(ctx, id, text, "")
}
func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID string) error {
return c.PromptWithMessageIDModelFiles(ctx, id, text, messageID, "", nil)
}
func (c *Chat) PromptWithMessageIDModel(ctx context.Context, id, text, messageID, model string) error {
return c.PromptWithMessageIDModelFiles(ctx, id, text, messageID, model, nil)
}
func (c *Chat) PromptWithMessageIDFiles(ctx context.Context, id, text, messageID string, files []opencode.PromptFile) error {
return c.PromptWithMessageIDModelFiles(ctx, id, text, messageID, "", files)
}
// PromptWithMessageIDModelFiles submits one user turn, optionally applying the
// saved next-turn model and the server's private attachment files.
func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, messageID, model string, files []opencode.PromptFile) error {
s := c.session(id)
if s == nil {
found := false
if meta, ok := transcriptSession(id); ok {
s = c.sessionFor(id, meta.Directory)
found = true
}
if !found {
return errors.New("unknown Claude session " + id)
}
}
s.mu.Lock()
if strings.TrimSpace(text) == "" {
s.mu.Unlock()
return errors.New("a nonempty chat prompt is required")
}
if model != "" {
s.model = model
}
directory := s.directory
s.lastUsed = time.Now()
s.mu.Unlock()
if directory == "" {
return errors.New("the Claude session has no working directory")
}
proc, err := s.ensureProcess(ctx)
if err != nil {
return err
}
// Apply a selection that the running process has not seen yet.
s.mu.Lock()
requested := s.model
applied := s.appliedModel
s.mu.Unlock()
if requested != "" && requested != applied {
setCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
_, err := proc.request(setCtx, "set_model", map[string]any{"model": requested})
cancel()
if err != nil {
return fmt.Errorf("switch Claude model: %w", err)
}
s.mu.Lock()
s.appliedModel = requested
s.mu.Unlock()
}
content, err := promptContent(text, files)
if err != nil {
return err
}
turn := fmt.Sprintf("claude-%d", time.Now().UnixNano())
s.mu.Lock()
s.turnID = turn
s.running = true
s.prompts = append(s.prompts, promptRecord{id: messageID, text: strings.TrimSpace(text)})
if len(s.prompts) > 200 {
s.prompts = s.prompts[len(s.prompts)-200:]
}
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
payload := map[string]any{
"type": "user",
"message": map[string]any{"role": "user", "content": content},
}
if err := proc.write(payload); err != nil {
s.finishTurn(turn, "Claude Code is not accepting input: "+err.Error())
return err
}
return nil
}
// finishTurn settles a turn that never reached a CLI result.
func (s *session) finishTurn(turn, diagnostic string) {
s.mu.Lock()
if s.turnID != turn {
s.mu.Unlock()
return
}
s.running = false
s.turnID = ""
s.mu.Unlock()
if diagnostic != "" {
s.emit(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: turn,
MessageID: "claude-error-" + turn,
Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: "claude-error-" + turn,
Name: "Claude Code",
State: &protocol.ChatToolState{Status: protocol.ChatToolError, Error: &protocol.ChatError{Type: "prompt", Message: boundedText(diagnostic, 2<<10)}},
},
})
}
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
}
func (s *session) ensureProcess(ctx context.Context) (*process, error) {
for {
s.mu.Lock()
if s.proc != nil {
p := s.proc
s.lastUsed = time.Now()
s.mu.Unlock()
return p, nil
}
if s.starting != nil {
wait := s.starting
s.mu.Unlock()
select {
case <-wait:
continue
case <-ctx.Done():
return nil, ctx.Err()
}
}
wait := make(chan struct{})
s.starting = wait
s.startErr = nil
s.mu.Unlock()
p, err := s.spawn(ctx)
s.mu.Lock()
if err == nil {
s.proc = p
} else {
s.startErr = err
}
s.starting = nil
close(wait)
s.mu.Unlock()
if err != nil {
return nil, err
}
return p, nil
}
}
// Stream subscribes to the session's live frames. History is loaded separately
// through Messages; a client attaching mid-turn is told to resync.
func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
s := c.session(id)
if s == nil {
meta, ok := transcriptSession(id)
if !ok {
return errors.New("unknown Claude session " + id)
}
s = c.sessionFor(id, meta.Directory)
}
ch := s.subscribe()
defer s.unsubscribe(ch)
if ready != nil {
ready()
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case frame, ok := <-ch:
if !ok {
return errors.New("Claude chat stream closed")
}
if err := emit(frame); err != nil {
return err
}
}
}
}
// Interrupt asks the CLI to cancel the in-flight turn, including queued turns.
func (c *Chat) Interrupt(ctx context.Context, id string) error {
s := c.session(id)
if s == nil {
return nil
}
s.mu.Lock()
proc := s.proc
running := s.running
s.mu.Unlock()
if proc == nil || !running {
return nil
}
requestCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
defer cancel()
_, err := proc.request(requestCtx, "interrupt", map[string]any{"cancel_queued": true})
return err
}
// ActivateSkill has no out-of-band equivalent in Claude Code; skills resolve
// through the CLI's own /skill mechanism.
func (c *Chat) ActivateSkill(context.Context, string, string) error {
return errors.New("Claude Code has no out-of-band skill activation")
}
// Models lists the CLI's own model choices, loaded at the initialize handshake.
func (c *Chat) Models(ctx context.Context, id string) ([]protocol.ChatModel, error) {
s := c.session(id)
if s == nil {
return nil, errors.New("unknown Claude session " + id)
}
proc, err := s.ensureProcess(ctx)
if err != nil {
return nil, err
}
_ = proc
s.mu.Lock()
models := append([]protocol.ChatModel(nil), s.models...)
s.mu.Unlock()
if len(models) == 0 {
return nil, errors.New("Claude Code reported no available models")
}
return models, nil
}
// SwitchModel changes the model for subsequent turns. The CLI applies it live
// when a process exists; otherwise the next process starts with it.
func (c *Chat) SwitchModel(ctx context.Context, id, provider, model string) error {
if provider != "" && provider != Backend {
return errors.New("Claude models use the claude provider")
}
model = strings.TrimSpace(model)
if model == "" {
return errors.New("a model is required")
}
s := c.session(id)
if s == nil {
return errors.New("unknown Claude session " + id)
}
s.mu.Lock()
previous := s.model
s.model = model
proc := s.proc
applied := s.appliedModel
s.mu.Unlock()
if proc != nil && model != applied {
requestCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
defer cancel()
if _, err := proc.request(requestCtx, "set_model", map[string]any{"model": model}); err != nil {
s.mu.Lock()
s.model = previous
s.mu.Unlock()
return fmt.Errorf("switch Claude model: %w", err)
}
s.mu.Lock()
s.appliedModel = model
s.mu.Unlock()
}
return nil
}
// Permissions returns the approvals still waiting for an operator answer.
func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermissionFrame, error) {
s := c.session(id)
if s == nil {
return []protocol.ChatPermissionFrame{}, nil
}
s.mu.Lock()
defer s.mu.Unlock()
frames := make([]protocol.ChatPermissionFrame, 0, len(s.approvals))
for _, approval := range s.approvals {
frames = append(frames, approval.frame)
}
sort.Slice(frames, func(i, j int) bool { return frames[i].RequestID < frames[j].RequestID })
return frames, nil
}
// Forms returns the pending operator questions.
func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error) {
s := c.session(id)
if s == nil {
return []protocol.ChatForm{}, nil
}
s.mu.Lock()
defer s.mu.Unlock()
forms := make([]protocol.ChatForm, 0, len(s.forms))
for _, form := range s.forms {
forms = append(forms, form.form)
}
sort.Slice(forms, func(i, j int) bool { return forms[i].ID < forms[j].ID })
return forms, nil
}
// Reply delivers one approval decision to the waiting CLI process.
func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
s := c.session(request.SessionID)
if s == nil {
return errors.New("unknown Claude session " + request.SessionID)
}
s.mu.Lock()
approval, ok := s.approvals[request.RequestID]
if !ok || approval.answering {
s.mu.Unlock()
return errors.New("the Claude approval is no longer awaiting an answer")
}
proc := approval.proc
var response any
switch request.Decision {
case protocol.ChatDecisionOnce:
response = map[string]any{"behavior": "allow", "updatedInput": approval.input}
case protocol.ChatDecisionAlways:
response = map[string]any{"behavior": "allow", "updatedInput": approval.input}
if len(approval.suggestions) > 0 && string(approval.suggestions) != "null" {
response = map[string]any{"behavior": "allow", "updatedInput": approval.input, "updatedPermissions": approval.suggestions}
}
case protocol.ChatDecisionReject:
response = map[string]any{"behavior": "deny", "message": "Denied by the operator"}
default:
s.mu.Unlock()
return errors.New("invalid approval decision")
}
if proc == nil {
s.mu.Unlock()
return errProcessClosed
}
approval.answering = true
s.mu.Unlock()
err := proc.respond(request.RequestID, response)
s.mu.Lock()
if err == nil {
delete(s.approvals, request.RequestID)
} else if current, exists := s.approvals[request.RequestID]; exists {
current.answering = false
}
s.mu.Unlock()
return err
}
// Answer delivers a question answer (or declines it) to the waiting CLI.
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
s := c.session(request.SessionID)
if s == nil {
return errors.New("unknown Claude session " + request.SessionID)
}
s.mu.Lock()
form, ok := s.forms[request.FormID]
if !ok || form.answering {
s.mu.Unlock()
return errors.New("the Claude question is no longer awaiting an answer")
}
proc := form.proc
s.mu.Unlock()
if proc == nil {
return errProcessClosed
}
deny := request.Action == "cancel" || request.Action == "decline"
var response any
if deny {
response = map[string]any{"behavior": "deny", "message": "The operator declined to answer"}
} else {
answers := map[string]string{}
for index, question := range form.questions {
key := fmt.Sprintf("q%d", index)
value, present := request.Answers[key]
if !present {
continue
}
switch typed := value.(type) {
case string:
answers[question] = typed
case []any:
labels := make([]string, 0, len(typed))
for _, item := range typed {
labels = append(labels, fmt.Sprint(item))
}
answers[question] = strings.Join(labels, ", ")
case []string:
answers[question] = strings.Join(typed, ", ")
default:
answers[question] = fmt.Sprint(typed)
}
}
response = map[string]any{
"behavior": "allow",
"updatedInput": map[string]any{"questions": form.rawQuestions, "answers": answers},
}
}
s.mu.Lock()
form.answering = true
s.mu.Unlock()
err := proc.respond(request.FormID, response)
s.mu.Lock()
if err == nil {
delete(s.forms, request.FormID)
} else if current, exists := s.forms[request.FormID]; exists {
current.answering = false
}
s.mu.Unlock()
return err
}
// Shells lists the commands still running in the session.
func (c *Chat) Shells(ctx context.Context, id string) ([]protocol.ChatShell, error) {
s := c.session(id)
if s == nil {
return []protocol.ChatShell{}, nil
}
s.mu.Lock()
defer s.mu.Unlock()
result := []protocol.ChatShell{}
for _, snapshot := range s.shells {
if snapshot.shell.Status == protocol.ChatShellRunning {
result = append(result, snapshot.shell)
}
}
sort.Slice(result, func(i, j int) bool { return result[i].ID < result[j].ID })
return result, nil
}
// ShellOutput pages the retained output of one command this session started.
func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
if query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
return protocol.ChatShellOutputPage{}, errors.New("invalid bounded Claude output query")
}
s := c.session(query.SessionID)
if s == nil {
return protocol.ChatShellOutputPage{Shell: protocol.ChatShell{ID: query.ShellID}, Unavailable: true}, nil
}
s.mu.Lock()
var snapshot *shellSnapshot
for _, candidate := range s.shells {
if candidate.shell.ID == query.ShellID {
snapshot = candidate
break
}
}
s.mu.Unlock()
if snapshot == nil {
return protocol.ChatShellOutputPage{Shell: protocol.ChatShell{ID: query.ShellID}, Unavailable: true}, nil
}
start := query.Cursor
if start > int64(len(snapshot.output)) {
start = int64(len(snapshot.output))
}
end := start + int64(query.Limit)
if end > int64(len(snapshot.output)) {
end = int64(len(snapshot.output))
}
return protocol.ChatShellOutputPage{
Shell: snapshot.shell,
Output: snapshot.output[start:end],
Cursor: end,
Size: snapshot.size,
Truncated: end < snapshot.size,
}, nil
}
// ---- CLI request handling --------------------------------------------------
type pendingApproval struct {
frame protocol.ChatPermissionFrame
input json.RawMessage
suggestions json.RawMessage
proc *process
answering bool
}
type pendingForm struct {
form protocol.ChatForm
rawQuestions json.RawMessage
questions []string
proc *process
answering bool
}
func (s *session) receivePermission(p *process, requestID string, request toolRequest) {
if requestID == "" {
return
}
if request.ToolName == "AskUserQuestion" {
s.receiveQuestion(p, requestID, request)
return
}
frame := protocol.ChatPermissionFrame{
SessionID: s.id,
RequestID: requestID,
Action: request.ToolName,
Source: &protocol.ChatPermissionSource{Type: "tool", ID: request.ToolUseID},
}
if name := request.DisplayName; name != "" && name != request.ToolName {
frame.Action = name
}
if request.Description != "" {
frame.Message = request.Description
}
frame.Resources = append(frame.Resources, permissionResources(request.ToolName, request.Input)...)
if len(request.PermissionSuggestions) > 0 && string(request.PermissionSuggestions) != "null" {
frame.AlwaysLabel = "Always allow"
}
s.mu.Lock()
s.approvals[requestID] = &pendingApproval{frame: frame, input: request.Input, suggestions: request.PermissionSuggestions, proc: p}
s.mu.Unlock()
}
func permissionResources(tool string, input json.RawMessage) []string {
var fields map[string]any
_ = json.Unmarshal(input, &fields)
text := func(key string) string {
if value, ok := fields[key].(string); ok {
return strings.TrimSpace(value)
}
return ""
}
switch tool {
case "Bash":
if command := text("command"); command != "" {
return []string{command}
}
case "Write", "Edit", "NotebookEdit", "Read":
if path := text("file_path"); path != "" {
return []string{path}
}
if path := text("notebook_path"); path != "" {
return []string{path}
}
case "WebFetch":
if target := text("url"); target != "" {
return []string{target}
}
case "WebSearch":
if query := text("query"); query != "" {
return []string{query}
}
}
// Fall back to a bounded, human-readable input summary so the operator sees
// what is being approved instead of an empty card.
bounded := boundedText(string(input), 1<<10)
if strings.TrimSpace(bounded) == "" {
return nil
}
return []string{bounded}
}
func (s *session) receiveQuestion(p *process, requestID string, request toolRequest) {
var payload struct {
Questions []struct {
Question string `json:"question"`
Header string `json:"header"`
MultiSelect bool `json:"multiSelect"`
Options []struct {
Label string `json:"label"`
Description string `json:"description"`
} `json:"options"`
} `json:"questions"`
}
if json.Unmarshal(request.Input, &payload) != nil || len(payload.Questions) == 0 {
// A question we cannot represent must not silently vanish: surface it as
// an approval card whose only useful action is deny.
s.receivePermission(p, requestID, toolRequest{ToolName: "AskUserQuestion", Input: request.Input})
return
}
form := protocol.ChatForm{ID: requestID, SessionID: s.id, Kind: "question", Title: "Claude asked a question"}
questions := make([]string, 0, len(payload.Questions))
for index, question := range payload.Questions {
questions = append(questions, question.Question)
field := protocol.ChatFormField{
Key: fmt.Sprintf("q%d", index),
Title: question.Question,
Type: "string",
Required: true,
}
if question.Header != "" {
form.Title = question.Header
}
if question.MultiSelect {
field.Type = "multiselect"
}
for _, option := range question.Options {
field.Options = append(field.Options, protocol.ChatFormOption{Value: option.Label, Label: option.Label, Description: option.Description})
}
form.Fields = append(form.Fields, field)
}
s.mu.Lock()
s.forms[requestID] = &pendingForm{form: form, rawQuestions: request.Input, questions: questions, proc: p}
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventForm, Form: &form})
}