gunk-dev/the-valley

consult.go

sourcec14b0e68e9c3main's published tip history
16.6 KiB
1package cmd
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "os/signal"
12 "path/filepath"
13 "sort"
14 "strings"
15 "syscall"
16 "time"
17
18 "the-valley/flow/internal/backend"
19 "the-valley/flow/internal/config"
20 "the-valley/flow/internal/consult"
21 "the-valley/flow/internal/event"
22 "the-valley/flow/internal/flowenv"
23 "the-valley/flow/internal/git"
24 "the-valley/flow/internal/jobs"
25 "the-valley/flow/internal/project"
26 "the-valley/flow/internal/run"
27 "github.com/spf13/cobra"
28)
29
30func newConsultCmd() *cobra.Command {
31 c := &cobra.Command{
32 Use: "consult [flags] (\"<question>\" | --prompt-file PATH)",
33 Short: "Ask another model a read-only question without launching a worker",
34 Long: `Consult a model as a thinking partner, critic, or code reviewer. Answers stream
35as plain text. Defaults to the first installed backend other than VALLEY_FLOW_BACKEND
36(or KLAUS_BACKEND), using consult.order and per-backend model/effort defaults.
37
38Use --thread NAME for a persistent conversation in the current flow session
39(or the most recent session outside a pane). Its backend, model, effort, role,
40and directory are retained; conflicting overrides are rejected. --list shows
41these threads. One-shot questions also work without a flow session.
42
43--file inlines attachments (200KB total), each under a header with its path,
44so the partner needn't open them; for agy, which can't open a path outside its
45workspace, each sits between BEGIN and END lines. Attachment and prompt-file
46paths are relative to the invoking directory. --dir selects the partner's
47workspace, read as it stands. --repo selects a registered local project and
48reads a snapshot of origin's default branch (default_branch in the project's
49config, else main), fetched at the start of the turn: a detached worktree of
50the project's clone under ~/.klaus, never the clone's working tree. A
51--repo thread keeps the project and its own snapshot, which every later turn
52fetches and moves to the current origin branch; a one-shot consult's snapshot,
53shared by a panel, is removed when it ends. The prompt's first line names the
54commit read ("Workspace: <project> at origin/<branch> <commit>"), and the
55thread, the consult:started event and the job record keep it. When the fetch
56fails, a thread reads its last snapshot, with a warning naming its commit; with
57no snapshot yet, the consult fails. valley flow cleanup --all removes threads'
58snapshots. --panel queries all
59installed model families other than the caller concurrently and groups their
60answers by backend. Panel answers are buffered to keep each response together.
61Each backend has a 10-minute deadline; use --timeout to change it. Timed-out
62members report "timed out" while other members finish.
63
64Inside a flow session each backend call emits consult:started and
65consult:completed events (see valley flow watch) sharing a consult-... run ID, and
66leaves a job record under that ID (see valley flow jobs): valley flow status and the
67dashboard list it while it runs and after it ends. A one-shot consult's
68answer is saved beside the record, and a thread's stays in its log; either
69way 'valley flow jobs show <id> --answer' prints it.`,
70 Args: cobra.MaximumNArgs(1),
71 RunE: runConsult,
72 }
73 f := c.Flags()
74 f.String("backend", "", "Model family: claude, codex, or agy (default: another installed family)")
75 f.String("model", "", "Model identifier (default: backends.<kind>.model)")
76 f.String("effort", "", "Reasoning effort (default: backends.<kind>.effort)")
77 f.String("role", "", "partner, critic, reviewer, or a verbatim system prompt (default: consult.default_role)")
78 f.String("thread", "", "Continue a named conversation in the current or most recent flow session")
79 f.String("dir", "", "Read-only workspace, read as it stands (default: cwd, or saved thread directory)")
80 f.String("repo", "", "Registered local project to read, as a fresh snapshot of origin's default branch")
81 f.StringArray("file", nil, "Inline a file in the prompt; repeatable, 200KB total")
82 f.String("prompt-file", "", "Read the question from a file instead of a positional argument")
83 f.Duration("timeout", 10*time.Minute, "Deadline per backend call (positive duration, e.g. 30s or 10m)")
84 f.Bool("panel", false, "Ask all installed families other than the caller concurrently")
85 f.Bool("list", false, "List stored threads with backend, turn count, and last-used time")
86 c.MarkFlagsMutuallyExclusive("dir", "repo")
87 c.MarkFlagsMutuallyExclusive("panel", "thread")
88 c.MarkFlagsMutuallyExclusive("panel", "backend")
89 return c
90}
91
92func runConsult(cmd *cobra.Command, args []string) error {
93 ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
94 defer stop()
95 cmd.SetContext(ctx)
96 str := func(name string) string { v, _ := cmd.Flags().GetString(name); return v }
97 panel, _ := cmd.Flags().GetBool("panel")
98 list, _ := cmd.Flags().GetBool("list")
99 name := str("thread")
100 var store consult.Store
101 var jobStore jobs.Store
102 baseDir := ""
103 if s, err := sessionStore(); err == nil {
104 baseDir = s.(*run.HomeDirStore).BaseDir()
105 store = consult.NewStore(baseDir)
106 jobStore = jobs.NewStore(baseDir)
107 } else if list || name != "" {
108 return err
109 }
110 if list {
111 if len(args) > 0 {
112 return fmt.Errorf("--list cannot be combined with a question")
113 }
114 for _, flag := range []string{"backend", "model", "effort", "role", "thread", "dir", "repo", "file", "prompt-file", "panel"} {
115 if cmd.Flags().Changed(flag) {
116 return fmt.Errorf("--list cannot be combined with --%s", flag)
117 }
118 }
119 threads, err := store.List()
120 if err != nil {
121 return err
122 }
123 names := make([]string, 0, len(threads))
124 for n := range threads {
125 names = append(names, n)
126 }
127 sort.Strings(names)
128 fmt.Fprintln(cmd.OutOrStdout(), "THREAD\tBACKEND\tTURNS\tLAST-USED")
129 for _, n := range names {
130 t := threads[n]
131 fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%d\t%s\n", n, t.Backend, t.Turns, t.LastUsed.Format(time.RFC3339))
132 }
133 return nil
134 }
135 timeout, _ := cmd.Flags().GetDuration("timeout")
136 if timeout <= 0 {
137 return fmt.Errorf("--timeout must be positive")
138 }
139 question, err := resolvePrompt(args, str("prompt-file"))
140 if err != nil {
141 return err
142 }
143 if strings.TrimSpace(question) == "" {
144 return fmt.Errorf("question must not be empty")
145 }
146 excerpt := promptExcerpt(question)
147 paths, _ := cmd.Flags().GetStringArray("file")
148 files, err := consult.ReadFiles(paths)
149 if err != nil {
150 return err
151 }
152 var saved *consult.Thread
153 if name != "" {
154 unlock, err := store.Lock(name)
155 if err != nil {
156 return err
157 }
158 defer unlock()
159 saved, err = store.Load(name)
160 if err != nil && !os.IsNotExist(err) {
161 return err
162 }
163 }
164 dir := str("dir")
165 repo := str("repo")
166 if saved != nil && (saved.Repo != "" || repo != "") {
167 switch {
168 case saved.Repo == "" || cmd.Flags().Changed("dir"):
169 return fmt.Errorf("workspace conflicts with saved thread %q", name)
170 case repo != "" && repo != saved.Repo:
171 return fmt.Errorf("--repo conflicts with saved thread %q", name)
172 }
173 repo = saved.Repo
174 }
175 // A --repo consult reads a snapshot of origin's default branch, fetched
176 // now: a thread's at a path of its own that every turn moves, a one-shot
177 // consult's (shared by a panel's members) in a directory removed after.
178 var snap *repoSnapshot
179 if repo != "" {
180 if name != "" {
181 if dir, err = store.WorkspaceDir(name); err != nil {
182 return err
183 }
184 } else {
185 var parent string
186 if parent, dir, err = oneShotSnapshotDir(repo); err != nil {
187 return err
188 }
189 defer func() {
190 warnSnapshot(cmd.ErrOrStderr(), git.RemoveSnapshot(context.Background(), dir))
191 os.RemoveAll(parent)
192 }()
193 }
194 if snap, err = prepareRepoSnapshot(cmd.Context(), repo, dir, cmd.ErrOrStderr()); err != nil {
195 return err
196 }
197 }
198 if dir == "" && saved != nil {
199 dir = saved.Dir
200 }
201 if dir == "" {
202 dir = "."
203 }
204 dir, err = filepath.Abs(dir)
205 if err != nil {
206 return err
207 }
208 dir, err = filepath.EvalSymlinks(dir)
209 if err != nil {
210 return err
211 }
212 info, err := os.Stat(dir)
213 if err != nil {
214 return err
215 }
216 if !info.IsDir() {
217 return fmt.Errorf("workspace %s is not a directory", dir)
218 }
219 cfgDir := dir
220 if root, err := exec.CommandContext(cmd.Context(), "git", "-C", dir, "rev-parse", "--show-toplevel").Output(); err == nil {
221 cfgDir = strings.TrimSpace(string(root))
222 }
223 cfg, err := config.Load(cfgDir)
224 if err != nil {
225 return err
226 }
227 role := str("role")
228 if role == "" {
229 role = cfg.Consult.DefaultRole
230 }
231 if role == "" {
232 role = "partner"
233 }
234 var kinds []backend.Kind
235 switch {
236 case saved != nil:
237 if saved.BackendSessionID == "" {
238 return fmt.Errorf("thread %q has no backend session ID", name)
239 }
240 if kind, err := backend.Parse(string(saved.Backend)); err != nil || kind != saved.Backend {
241 return fmt.Errorf("invalid backend in saved thread %q", name)
242 }
243 for flag, value := range map[string]string{"backend": string(saved.Backend), "model": saved.Model, "effort": saved.Effort, "role": saved.Role} {
244 if cmd.Flags().Changed(flag) && str(flag) != value {
245 return fmt.Errorf("--%s conflicts with saved thread %q", flag, name)
246 }
247 }
248 if dir != saved.Dir {
249 return fmt.Errorf("workspace conflicts with saved thread %q", name)
250 }
251 kinds = []backend.Kind{saved.Backend}
252 case str("backend") != "":
253 kind, err := backend.Parse(str("backend"))
254 if err != nil {
255 return err
256 }
257 kinds = []backend.Kind{kind}
258 default:
259 order := cfg.Consult.Order
260 if len(order) == 0 {
261 order = []string{"codex", "claude", "agy"}
262 }
263 if panel {
264 order = append(append([]string{}, order...), "codex", "claude", "agy")
265 }
266 kinds, err = consult.Installed(order, flowenv.Backend.Get())
267 if err != nil {
268 return err
269 }
270 if len(kinds) == 0 {
271 return fmt.Errorf("no other backend installed; install one or choose --backend explicitly")
272 }
273 if !panel {
274 kinds = kinds[:1]
275 }
276 }
277 // A --repo consult carries the house rules, read once for all its members.
278 var houseRules string
279 if repo != "" {
280 reg, _ := project.Load()
281 _, clone := resolveRepoTarget(repo, "", reg)
282 houseRules = loadHouseRules(cmd.Context(), clone, cfg, reg, cmd.ErrOrStderr()).Text
283 }
284 threads := make([]*consult.Thread, 0, len(kinds))
285 for _, kind := range kinds {
286 defaults := cfg.AgentDefaults(string(kind))
287 t := &consult.Thread{Backend: kind, Model: defaults.Model, Effort: defaults.Effort, Role: role, Dir: dir, Repo: repo, CreatedAt: time.Now().UTC()}
288 if cmd.Flags().Changed("model") {
289 t.Model = str("model")
290 }
291 if cmd.Flags().Changed("effort") {
292 t.Effort = str("effort")
293 }
294 if saved != nil {
295 t = saved
296 }
297 if err := kind.ValidateEffort(t.Effort); err != nil {
298 return err
299 }
300 if snap != nil {
301 t.Commit = snap.commit
302 }
303 t.HouseRules = houseRules
304 threads = append(threads, t)
305 }
306 panelID := ""
307 if panel {
308 panelID = eventID("panel")
309 }
310 ask := func(t *consult.Thread, out, errOut io.Writer) (askErr error) {
311 prompt := consult.InlineFiles(t.Backend, question, files)
312 if snap != nil {
313 prompt = snap.workspaceLine() + "\n\n" + prompt
314 }
315 callCtx, cancel := context.WithTimeout(cmd.Context(), timeout)
316 defer cancel()
317 start := time.Now()
318 var job *jobs.Job
319 var turn *consult.Turn
320 var result consult.Result
321 if baseDir != "" {
322 consultID, data := consultEventID(), map[string]interface{}{"backend": t.Backend, "model": t.Model, "effort": t.Effort, "role": t.Role, "thread": name, "dir": t.Dir, "panel": panel, "prompt": excerpt}
323 if snap != nil {
324 data["repo"] = snap.project
325 data["commit"] = snap.commit
326 }
327 if str("prompt-file") != "" {
328 data["prompt_file"] = str("prompt-file")
329 }
330 if key := dirRepoKey(cmd.Context(), t.Dir); key != "" {
331 data["repo_key"] = key
332 }
333 job = &jobs.Job{ID: consultID, Kind: jobs.KindConsult, Panel: panelID, Thread: name, Role: t.Role,
334 Backend: string(t.Backend), Model: t.Model, Effort: t.Effort, Dir: t.Dir, Repo: repo, Commit: t.Commit, Prompt: excerpt}
335 warnJob(errOut, job, jobStore.Start(job))
336 emitEvent(baseDir, consultID, event.ConsultStarted, data)
337 // SIGINT/SIGTERM cancel cmd.Context() rather than killing the
338 // process, so every start gets a completion except on SIGKILL.
339 defer func() {
340 status, errText := jobOutcome(askErr, cmd.Context().Err() != nil,
341 errors.Is(callCtx.Err(), context.DeadlineExceeded), "timeout after "+timeout.String())
342 done := make(map[string]interface{}, len(data)+3)
343 for k, v := range data {
344 done[k] = v
345 }
346 done["duration_ms"] = time.Since(start).Milliseconds()
347 done["success"] = askErr == nil
348 if errText != "" {
349 done["error"] = errText
350 }
351 emitEvent(baseDir, consultID, event.ConsultCompleted, done)
352 finishConsultJob(jobStore, job, turn, result, status, errText, errOut)
353 }()
354 }
355 id := ""
356 if name != "" && t.Backend == backend.Claude && t.BackendSessionID == "" {
357 id = genUUIDv4()
358 }
359 if name != "" {
360 revision := t.Commit
361 if snap == nil {
362 out, _ := exec.CommandContext(callCtx, "git", "-C", t.Dir, "rev-parse", "--short", "HEAD").Output()
363 revision = strings.TrimSpace(string(out))
364 }
365 var err error
366 turn, err = store.BeginTurn(name, t, prompt, revision)
367 if err != nil {
368 return err
369 }
370 if job != nil {
371 job.Turn = turn.Number
372 warnJob(errOut, job, jobStore.Save(job))
373 }
374 }
375 result, askErr = consult.Ask(callCtx, t, prompt, name != "", id, out, errOut)
376 if name != "" {
377 if askErr != nil {
378 path, err := store.SaveRaw(name, turn.Number, result)
379 if err != nil {
380 askErr = errors.Join(askErr, fmt.Errorf("saving raw output %s: %w", path, err))
381 } else {
382 turn.RawOutput = path
383 askErr = fmt.Errorf("%w; raw output: %s", askErr, path)
384 }
385 }
386 if result.SessionID != "" && (askErr == nil || result.SessionIDSource != "assigned") {
387 t.BackendSessionID = result.SessionID
388 if askErr == nil {
389 t.Turns++
390 }
391 t.LastUsed = time.Now().UTC()
392 askErr = errors.Join(askErr, store.Save(name, t))
393 }
394 askErr = errors.Join(askErr, store.FinishTurn(name, turn, result, askErr))
395 }
396 return askErr
397 }
398
399 if !panel {
400 return ask(threads[0], cmd.OutOrStdout(), cmd.ErrOrStderr())
401 }
402 type result struct {
403 thread *consult.Thread
404 answer, stderr string
405 err error
406 }
407 results := make(chan result, len(threads))
408 for _, t := range threads {
409 go func() {
410 var out, errOut bytes.Buffer
411 err := ask(t, &out, &errOut)
412 results <- result{t, out.String(), errOut.String(), err}
413 }()
414 }
415 var errs []error
416 for range threads {
417 r := <-results
418 model := r.thread.Model
419 if model == "" {
420 model = "default"
421 }
422 if errors.Is(r.err, context.DeadlineExceeded) {
423 r.answer = "timed out"
424 }
425 fmt.Fprintf(cmd.OutOrStdout(), "## %s (%s)\n\n%s\n", r.thread.Backend, model, r.answer)
426 if r.stderr != "" {
427 fmt.Fprintf(cmd.ErrOrStderr(), "[%s]\n%s", r.thread.Backend, r.stderr)
428 }
429 if r.err != nil {
430 errs = append(errs, r.err)
431 }
432 }
433 return errors.Join(errs...)
434}
435
436// warnSnapshot reports a one-shot consult's snapshot that couldn't be
437// removed; the answer stands.
438func warnSnapshot(w io.Writer, err error) {
439 if err != nil {
440 fmt.Fprintf(w, "warning: %v\n", err)
441 }
442}
443
444// consultEventID identifies one backend call in events.jsonl and its job
445// record, using the run ID format with a consult- prefix so it never
446// collides with an agent run.
447func consultEventID() string { return eventID("consult") }
448
449// eventID is a run ID with a prefix, such as consult-, review- or panel-.
450func eventID(prefix string) string {
451 id, err := run.GenID()
452 if err != nil {
453 id = time.Now().Format("20060102-1504")
454 }
455 return prefix + "-" + id
456}
457
458// finishConsultJob records how a consult call ended, and where its answer
459// is: a threaded consult's turn already keeps it, and its raw output on
460// failure; a one-shot consult's answer, or on failure everything the backend
461// wrote, goes in a file beside the record.
462func finishConsultJob(store jobs.Store, job *jobs.Job, turn *consult.Turn, result consult.Result, status jobs.Status, errText string, warn io.Writer) {
463 switch {
464 case turn != nil:
465 job.RawOutput = turn.RawOutput
466 case job.Thread != "":
467 // The thread never began its turn: there is no output.
468 case status == jobs.Succeeded:
469 path, err := store.WriteFile(job.ID, ".answer", []byte(result.Answer))
470 warnJob(warn, job, err)
471 if err == nil {
472 job.AnswerFile = path
473 }
474 case result.Answer != "" || result.Stderr != "":
475 path, err := store.WriteFile(job.ID, ".raw", []byte(result.Raw()))
476 warnJob(warn, job, err)
477 if err == nil {
478 job.RawOutput = path
479 }
480 }
481 warnJob(warn, job, store.Finish(job, status, errText))
482}
483
484// promptExcerpt is the first non-blank line of the question, capped at 120
485// characters, so events identify a consult without carrying the full prompt.
486func promptExcerpt(prompt string) string {
487 for _, line := range strings.Split(prompt, "\n") {
488 if strings.TrimSpace(line) != "" {
489 return truncateLine(line, 120)
490 }
491 }
492 return ""
493}
494
495func init() { rootCmd.AddCommand(newConsultCmd()) }