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