gunk-dev/the-valley

consult.go

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