gunk-dev/the-valley

consult.go

source30e24c82839bmain's published tip history
16.5 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/git"
23 "the-valley/flow/internal/jobs"
24 "the-valley/flow/internal/project"
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 KLAUS_BACKEND,
35using 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, os.Getenv("KLAUS_BACKEND"))
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, _ := project.Load()
280 _, clone := resolveRepoTarget(repo, "", reg)
281 houseRules = loadHouseRules(cmd.Context(), clone, cfg, reg, cmd.ErrOrStderr()).Text
282 }
283 threads := make([]*consult.Thread, 0, len(kinds))
284 for _, kind := range kinds {
285 defaults := cfg.AgentDefaults(string(kind))
286 t := &consult.Thread{Backend: kind, Model: defaults.Model, Effort: defaults.Effort, Role: role, Dir: dir, Repo: repo, CreatedAt: time.Now().UTC()}
287 if cmd.Flags().Changed("model") {
288 t.Model = str("model")
289 }
290 if cmd.Flags().Changed("effort") {
291 t.Effort = str("effort")
292 }
293 if saved != nil {
294 t = saved
295 }
296 if err := kind.ValidateEffort(t.Effort); err != nil {
297 return err
298 }
299 if snap != nil {
300 t.Commit = snap.commit
301 }
302 t.HouseRules = houseRules
303 threads = append(threads, t)
304 }
305 panelID := ""
306 if panel {
307 panelID = eventID("panel")
308 }
309 ask := func(t *consult.Thread, out, errOut io.Writer) (askErr error) {
310 prompt := consult.InlineFiles(t.Backend, question, files)
311 if snap != nil {
312 prompt = snap.workspaceLine() + "\n\n" + prompt
313 }
314 callCtx, cancel := context.WithTimeout(cmd.Context(), timeout)
315 defer cancel()
316 start := time.Now()
317 var job *jobs.Job
318 var turn *consult.Turn
319 var result consult.Result
320 if baseDir != "" {
321 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}
322 if snap != nil {
323 data["repo"] = snap.project
324 data["commit"] = snap.commit
325 }
326 if str("prompt-file") != "" {
327 data["prompt_file"] = str("prompt-file")
328 }
329 if key := dirRepoKey(cmd.Context(), t.Dir); key != "" {
330 data["repo_key"] = key
331 }
332 job = &jobs.Job{ID: consultID, Kind: jobs.KindConsult, Panel: panelID, Thread: name, Role: t.Role,
333 Backend: string(t.Backend), Model: t.Model, Effort: t.Effort, Dir: t.Dir, Repo: repo, Commit: t.Commit, Prompt: excerpt}
334 warnJob(errOut, job, jobStore.Start(job))
335 emitEvent(baseDir, consultID, event.ConsultStarted, data)
336 // SIGINT/SIGTERM cancel cmd.Context() rather than killing the
337 // process, so every start gets a completion except on SIGKILL.
338 defer func() {
339 status, errText := jobOutcome(askErr, cmd.Context().Err() != nil,
340 errors.Is(callCtx.Err(), context.DeadlineExceeded), "timeout after "+timeout.String())
341 done := make(map[string]interface{}, len(data)+3)
342 for k, v := range data {
343 done[k] = v
344 }
345 done["duration_ms"] = time.Since(start).Milliseconds()
346 done["success"] = askErr == nil
347 if errText != "" {
348 done["error"] = errText
349 }
350 emitEvent(baseDir, consultID, event.ConsultCompleted, done)
351 finishConsultJob(jobStore, job, turn, result, status, errText, errOut)
352 }()
353 }
354 id := ""
355 if name != "" && t.Backend == backend.Claude && t.BackendSessionID == "" {
356 id = genUUIDv4()
357 }
358 if name != "" {
359 revision := t.Commit
360 if snap == nil {
361 out, _ := exec.CommandContext(callCtx, "git", "-C", t.Dir, "rev-parse", "--short", "HEAD").Output()
362 revision = strings.TrimSpace(string(out))
363 }
364 var err error
365 turn, err = store.BeginTurn(name, t, prompt, revision)
366 if err != nil {
367 return err
368 }
369 if job != nil {
370 job.Turn = turn.Number
371 warnJob(errOut, job, jobStore.Save(job))
372 }
373 }
374 result, askErr = consult.Ask(callCtx, t, prompt, name != "", id, out, errOut)
375 if name != "" {
376 if askErr != nil {
377 path, err := store.SaveRaw(name, turn.Number, result)
378 if err != nil {
379 askErr = errors.Join(askErr, fmt.Errorf("saving raw output %s: %w", path, err))
380 } else {
381 turn.RawOutput = path
382 askErr = fmt.Errorf("%w; raw output: %s", askErr, path)
383 }
384 }
385 if result.SessionID != "" && (askErr == nil || result.SessionIDSource != "assigned") {
386 t.BackendSessionID = result.SessionID
387 if askErr == nil {
388 t.Turns++
389 }
390 t.LastUsed = time.Now().UTC()
391 askErr = errors.Join(askErr, store.Save(name, t))
392 }
393 askErr = errors.Join(askErr, store.FinishTurn(name, turn, result, askErr))
394 }
395 return askErr
396 }
397
398 if !panel {
399 return ask(threads[0], cmd.OutOrStdout(), cmd.ErrOrStderr())
400 }
401 type result struct {
402 thread *consult.Thread
403 answer, stderr string
404 err error
405 }
406 results := make(chan result, len(threads))
407 for _, t := range threads {
408 go func() {
409 var out, errOut bytes.Buffer
410 err := ask(t, &out, &errOut)
411 results <- result{t, out.String(), errOut.String(), err}
412 }()
413 }
414 var errs []error
415 for range threads {
416 r := <-results
417 model := r.thread.Model
418 if model == "" {
419 model = "default"
420 }
421 if errors.Is(r.err, context.DeadlineExceeded) {
422 r.answer = "timed out"
423 }
424 fmt.Fprintf(cmd.OutOrStdout(), "## %s (%s)\n\n%s\n", r.thread.Backend, model, r.answer)
425 if r.stderr != "" {
426 fmt.Fprintf(cmd.ErrOrStderr(), "[%s]\n%s", r.thread.Backend, r.stderr)
427 }
428 if r.err != nil {
429 errs = append(errs, r.err)
430 }
431 }
432 return errors.Join(errs...)
433}
434
435// warnSnapshot reports a one-shot consult's snapshot that couldn't be
436// removed; the answer stands.
437func warnSnapshot(w io.Writer, err error) {
438 if err != nil {
439 fmt.Fprintf(w, "warning: %v\n", err)
440 }
441}
442
443// consultEventID identifies one backend call in events.jsonl and its job
444// record, using the run ID format with a consult- prefix so it never
445// collides with an agent run.
446func consultEventID() string { return eventID("consult") }
447
448// eventID is a run ID with a prefix, such as consult-, review- or panel-.
449func eventID(prefix string) string {
450 id, err := run.GenID()
451 if err != nil {
452 id = time.Now().Format("20060102-1504")
453 }
454 return prefix + "-" + id
455}
456
457// finishConsultJob records how a consult call ended, and where its answer
458// is: a threaded consult's turn already keeps it, and its raw output on
459// failure; a one-shot consult's answer, or on failure everything the backend
460// wrote, goes in a file beside the record.
461func finishConsultJob(store jobs.Store, job *jobs.Job, turn *consult.Turn, result consult.Result, status jobs.Status, errText string, warn io.Writer) {
462 switch {
463 case turn != nil:
464 job.RawOutput = turn.RawOutput
465 case job.Thread != "":
466 // The thread never began its turn: there is no output.
467 case status == jobs.Succeeded:
468 path, err := store.WriteFile(job.ID, ".answer", []byte(result.Answer))
469 warnJob(warn, job, err)
470 if err == nil {
471 job.AnswerFile = path
472 }
473 case result.Answer != "" || result.Stderr != "":
474 path, err := store.WriteFile(job.ID, ".raw", []byte(result.Raw()))
475 warnJob(warn, job, err)
476 if err == nil {
477 job.RawOutput = path
478 }
479 }
480 warnJob(warn, job, store.Finish(job, status, errText))
481}
482
483// promptExcerpt is the first non-blank line of the question, capped at 120
484// characters, so events identify a consult without carrying the full prompt.
485func promptExcerpt(prompt string) string {
486 for _, line := range strings.Split(prompt, "\n") {
487 if strings.TrimSpace(line) != "" {
488 return truncateLine(line, 120)
489 }
490 }
491 return ""
492}
493
494func init() { rootCmd.AddCommand(newConsultCmd()) }