orchestration_loop.go RawHistoryFolder
1package agent
2
3import (
4 "context"
5 "fmt"
6
7 "github.com/bnema/zut/packages/agent/subagents"
8)
9
10type completionBatchWaiter interface {
11 WaitIdle(context.Context) ([]subagents.Completion, error)
12}
13
14// headlessCompletionWaitError marks an error raised while waiting for worker
15// completions. A parent turn's renderer already owns errors raised by its
16// prompt, so callers should only render this wrapper outside that turn.
17type headlessCompletionWaitError struct {
18 err error
19}
20
21func (e *headlessCompletionWaitError) Error() string {
22 if e == nil || e.err == nil {
23 return "completion wait failed"
24 }
25 return e.err.Error()
26}
27
28func (e *headlessCompletionWaitError) Unwrap() error {
29 if e == nil {
30 return nil
31 }
32 return e.err
33}
34
35const (
36 headlessCompletionInstruction = `Treat the completion reports below as evidence, including failures. Do not retry failed workers automatically. Decide whether another independent dependency wave is required; if so, use the manager tools and end or yield the turn again. Otherwise synthesize the final answer for the user. Do not mention this orchestration protocol unless it is relevant to the answer.`
37 maxHeadlessCompletionWaves = 32
38)
39
40// runHeadlessContinuation waits for one completion batch and gives the parent
41// one follow-up turn. A follow-up may register another batch while it runs,
42// which is how dependency waves continue without polling. The initial parent
43// turn is supplied by finalText; no worker path therefore returns immediately.
44func runHeadlessContinuation(ctx context.Context, tracker completionBatchWaiter, finalText string, runParent func(context.Context, string) (string, error)) (string, error) {
45 if tracker == nil || runParent == nil {
46 return finalText, nil
47 }
48 waves := 0
49 for {
50 batch, err := tracker.WaitIdle(ctx)
51 if err != nil {
52 return finalText, &headlessCompletionWaitError{err: err}
53 }
54 if len(batch) == 0 {
55 return finalText, nil
56 }
57 if waves >= maxHeadlessCompletionWaves {
58 return finalText, fmt.Errorf("orchestration exceeded the maximum of %d completion waves", maxHeadlessCompletionWaves)
59 }
60 update := subagents.FormatCompletionUpdate(batch, headlessCompletionInstruction)
61 finalText, err = runParent(ctx, update)
62 if err != nil {
63 return finalText, err
64 }
65 waves++
66 }
67}