gunk-dev/the-valley

consult.go

source60ad80d5a5a5main's published tip history
5.6 KiB
1package consult
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "regexp"
13 "strings"
14 "sync"
15 "syscall"
16 "time"
17
18 "the-valley/flow/internal/backend"
19)
20
21// LookupBinary permits executable substitution without adding fake backend kinds.
22var LookupBinary = exec.LookPath
23
24func Installed(order []string, caller string) ([]backend.Kind, error) {
25 var kinds []backend.Kind
26 seen := map[backend.Kind]bool{}
27 for _, name := range order {
28 kind, err := backend.Parse(name)
29 if err != nil || name == "" {
30 return nil, fmt.Errorf("invalid consult.order entry %q", name)
31 }
32 if seen[kind] || name == caller {
33 continue
34 }
35 seen[kind] = true
36 if _, err := LookupBinary(name); err == nil {
37 kinds = append(kinds, kind)
38 }
39 }
40 return kinds, nil
41}
42
43type Result struct {
44 Answer, Stderr, DiagnosticLog, SessionID, SessionIDSource string
45}
46
47func Ask(ctx context.Context, t *Thread, prompt string, threaded bool, sessionID string, out, errOut io.Writer) (Result, error) {
48 binary, err := LookupBinary(string(t.Backend))
49 if err != nil {
50 return Result{}, err
51 }
52 system := SystemPrompt(t.Role) + fmt.Sprintf("\n\nInspect the repository at %q. Resolve referenced code paths against that directory.", t.Dir)
53 if t.HouseRules != "" {
54 system += "\n\nThe operator's house rules for all their projects, which the repository's code should follow:\n\n<house-rules>\n" + strings.TrimSpace(t.HouseRules) + "\n</house-rules>"
55 }
56 agyAgent, diagnosticLog := "", ""
57 if t.Backend == backend.Agy {
58 var cleanup func()
59 agyAgent, cleanup, err = backend.PrepareAgyReadOnly()
60 if err != nil {
61 return Result{}, err
62 }
63 defer cleanup()
64 if threaded {
65 f, err := os.CreateTemp("", "klaus-consult-agy-*.log")
66 if err != nil {
67 return Result{}, err
68 }
69 diagnosticLog = f.Name()
70 f.Close()
71 defer os.Remove(diagnosticLog)
72 }
73 }
74 argv, err := backend.OneShot(t.Backend, backend.OneShotOptions{SystemPrompt: system, Model: t.Model, Effort: t.Effort, ResumeID: t.BackendSessionID, SessionID: sessionID, Threaded: threaded, AgyAgent: agyAgent, DiagnosticLog: diagnosticLog})
75 if err != nil {
76 return Result{}, err
77 }
78 cmd := exec.CommandContext(ctx, binary, argv[1:]...)
79 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
80 cmd.Cancel = func() error {
81 err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
82 if errors.Is(err, syscall.ESRCH) {
83 return os.ErrProcessDone
84 }
85 return err
86 }
87 cmd.WaitDelay = time.Second
88 cmd.Dir = t.Dir
89 cmd.Stdin = strings.NewReader(t.Backend.Stdin(system, prompt))
90 var stdout, stderr bytes.Buffer
91 var outputMu sync.Mutex
92 cmd.Stdout = io.MultiWriter(&stdout, lockedWriter{&outputMu, out})
93 cmd.Stderr = io.MultiWriter(&stderr, lockedWriter{&outputMu, errOut})
94 runErr := cmd.Run()
95 result := Result{Answer: stdout.String(), Stderr: stderr.String()}
96 var extractionErr error
97 if threaded && cmd.Process != nil {
98 data, _ := os.ReadFile(diagnosticLog)
99 result.DiagnosticLog = string(data)
100 result.SessionID, result.SessionIDSource, extractionErr = extractSessionID(t.Backend, t.BackendSessionID, sessionID, result.Answer, result.Stderr, string(data))
101 }
102 if ctx.Err() != nil {
103 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
104 return result, errors.Join(fmt.Errorf("consult %s timed out: %w", t.Backend, ctx.Err()), extractionErr)
105 }
106 return result, errors.Join(fmt.Errorf("consult %s: %w", t.Backend, ctx.Err()), extractionErr)
107 }
108 if runErr != nil {
109 return result, errors.Join(fmt.Errorf("consult %s: %w", t.Backend, runErr), extractionErr)
110 }
111 if extractionErr != nil {
112 return result, extractionErr
113 }
114 if strings.TrimSpace(result.Answer) == "" {
115 return result, fmt.Errorf("consult %s returned no answer", t.Backend)
116 }
117 return result, nil
118}
119
120func extractSessionID(kind backend.Kind, resumeID, assignedID, stdout, stderr, diagnostic string) (string, string, error) {
121 if kind == backend.Claude && assignedID != "" {
122 return assignedID, "assigned", nil
123 }
124 var tried []string
125 if kind == backend.Agy {
126 tried = append(tried, "diagnostic-log")
127 if m := agySessionHeader.FindStringSubmatch(diagnostic); len(m) > 1 {
128 return m[1], "diagnostic-log", nil
129 }
130 }
131 tried = append(tried, "stderr")
132 if id := sessionIDFromText(stderr); id != "" {
133 return id, "stderr", nil
134 }
135 if resumeID != "" {
136 return resumeID, "resume", nil
137 }
138 tried = append(tried, "stdout-json")
139 if id := sessionIDFromJSON(stdout); id != "" {
140 return id, "stdout-json", nil
141 }
142 tried = append(tried, "text")
143 if id := sessionIDHeader(stdout); id != "" {
144 return id, "text", nil
145 }
146 return "", "", fmt.Errorf("%s did not report a session ID; tried %s", kind, strings.Join(tried, ", "))
147}
148
149var agySessionHeader = regexp.MustCompile(`Sending user message to conversation ([a-zA-Z0-9_-]+) \(`)
150
151var sessionHeader = regexp.MustCompile(`(?mi)^session id:\s*([a-zA-Z0-9_-]+)\s*$`)
152
153func sessionIDFromText(text string) string {
154 if id := sessionIDHeader(text); id != "" {
155 return id
156 }
157 return sessionIDFromJSON(text)
158}
159
160func sessionIDHeader(text string) string {
161 if m := sessionHeader.FindStringSubmatch(text); len(m) > 1 {
162 return m[1]
163 }
164 return ""
165}
166
167func sessionIDFromJSON(text string) string {
168 for _, line := range strings.Split(text, "\n") {
169 var ev struct {
170 SessionID string `json:"session_id"`
171 ThreadID string `json:"thread_id"`
172 ConversationID string `json:"conversation_id"`
173 }
174 if json.Unmarshal([]byte(line), &ev) != nil {
175 continue
176 }
177 for _, id := range []string{ev.SessionID, ev.ThreadID, ev.ConversationID} {
178 if id != "" {
179 return id
180 }
181 }
182 }
183 return ""
184}
185
186type lockedWriter struct {
187 mu *sync.Mutex
188 writer io.Writer
189}
190
191func (w lockedWriter) Write(p []byte) (int, error) {
192 w.mu.Lock()
193 defer w.mu.Unlock()
194 return w.writer.Write(p)
195}