14 // subagentNote is the first message of the log of a subagent.
15 subagentNote = "subagent"
17 // subagentNoteEffort follows subagentNote when the subagent has its own
19 subagentNoteEffort = " at effort "
22 // errSubagentClosed tells that the runs of the subagents ended with the loop.
23 var errSubagentClosed = errors.New("the daemon stops, so no subagent starts")
25 // SubagentRuns runs the subagents of one agent in the background. Each run is a
26 // goroutine with its own context, which only Stop and Close end. A run is one
27 // or more request chains. The first request of each chain holds the view of the
28 // agent at the start of the run, then the state of the turn, then the whole log
29 // of the subagent. A message of Tell that comes during a chain joins its next
30 // request after the tool results. One that comes after the final answer starts
31 // one more chain, which reads the log again. The report of the run goes to
32 // report: the final answer of each chain, or the error of a failed call. Stop
33 // ends one run, and its report says that it stopped. At the stop of the daemon
34 // the runs end with no report.
36 // Spawn and Tell split the view with the layout of the agent, which has no
37 // lock. They are tools, so they run in the goroutine of the turns, as each
38 // split of a turn does.
39 type SubagentRuns struct {
46 report func(text string, stopped bool)
47 note func(text string) error
51 running map[string]*SubagentRun
53 workers sync.WaitGroup
56 // Spawn starts one subagent for each task and returns their names at once. It
57 // waits until the view has no pending summary, and gives the view to each
58 // subagent. A nil effort is the effort of the agent.
59 func (r *SubagentRuns) Spawn(ctx context.Context, tasks []string, effort *string) (string, error) {
61 return "", errors.New("no tasks")
69 return "", errSubagentClosed
73 runEffort := r.agent.config.Effort
74 if effort != nil && !slices.Contains(promptEfforts, *effort) {
75 return "", fmt.Errorf("no effort %q: one of %s", *effort, strings.Join(promptEfforts, ", "))
78 if effort != nil && *effort != runEffort {
79 note += subagentNoteEffort + *effort
83 err := r.memory.Settle(ctx)
85 return "", fmt.Errorf("wait for the summaries: %w", err)
88 view, err := r.layout.Split(r.memory.ViewLines(nil))
93 names := make([]string, 0, len(tasks))
94 for _, task := range tasks {
95 name, err := r.create(ctx, note, task, view, runEffort)
96 if err != nil && len(names) > 0 {
97 return "", fmt.Errorf("started %s, then: %w", strings.Join(names, ", "), err)
104 names = append(names, name)
107 return "Started " + strings.Join(names, ", ") + ". Each one's report will reach you as a message when it finishes.", nil
110 // Tell sends message to the subagent name. A running subagent reads it between
111 // its tool calls, and its report answers it. A finished subagent goes on from
112 // its log with a new run, with the view of now and the effort of its note.
113 func (r *SubagentRuns) Tell(ctx context.Context, name, message string) (string, error) {
115 run, found := r.running[name]
117 defer r.mutex.Unlock()
119 told, err := run.subagent.Append("user", message)
124 run.pending = append(run.pending, told)
126 return "Sent. " + name + " reads it between its tool calls, and its report answers it.", nil
133 return "", errSubagentClosed
136 subagent, err := r.subagents.Get(ctx, name)
141 effort, err := r.effort(subagent)
146 err = r.memory.Settle(ctx)
148 return "", fmt.Errorf("wait for the summaries: %w", err)
151 view, err := r.layout.Split(r.memory.ViewLines(nil))
156 _, err = subagent.Append("user", message)
158 err = subagent.Flush(ctx)
165 err = r.start(ctx, &SubagentRun{
174 return "Sent. " + name + "'s reply will reach you as a message.", nil
177 // Stop ends the run of the subagent name and tells if it ran. The chat gets the
178 // note "Stopped by the user: NAME." under the mutex, so the note comes before
179 // the report of the run.
180 func (r *SubagentRuns) Stop(name string) (bool, error) {
182 defer r.mutex.Unlock()
184 run, found := r.running[name]
189 err := r.note("Stopped by the user: " + name + ".")
200 // Close ends every run and waits for them. No subagent starts after Close.
201 func (r *SubagentRuns) Close() {
204 for _, run := range r.running {
212 // create makes a new subagent with its note, its task, and its work directory,
213 // and starts its run.
214 func (r *SubagentRuns) create(ctx context.Context, note, task string, view []string, effort string) (string, error) {
215 subagent, err := r.subagents.Create(ctx)
220 for _, message := range [][2]string{{"note", note}, {"user", task}} {
221 _, err = subagent.Append(message[0], message[1])
227 err = subagent.Flush(ctx)
232 err = os.MkdirAll(subagent.WorkDir(), 0o700)
234 return "", fmt.Errorf("create work directory: %w", err)
237 return subagent.name, r.start(ctx, &SubagentRun{
244 // effort returns the effort of subagent from the note at the start of its log:
245 // the effort of the agent, or the effort that the note names.
246 func (r *SubagentRuns) effort(subagent *Subagent) (string, error) {
247 note, err := subagent.First()
252 effort, own := strings.CutPrefix(note.Text, subagentNote+subagentNoteEffort)
254 case note.Kind != "note":
257 case note.Text == subagentNote:
258 return r.agent.config.Effort, nil
261 return "", fmt.Errorf("the log of %s does not start with a subagent note", subagent.name)
264 // start runs run in the background. Its context keeps the values of ctx, but
265 // only Stop and Close end it.
266 func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
267 ctx, run.cancel = context.WithCancel(context.WithoutCancel(ctx))
270 _, found := r.running[run.subagent.name]
271 if r.closed || found {
276 return fmt.Errorf("%s runs already", run.subagent.name)
279 return errSubagentClosed
282 r.running[run.subagent.name] = run
288 Text: run.subagent.name,
296 // run runs the chains of run and reports its end, unless Close ended it. A
297 // chain follows while messages wait after the final answer of the chain before
298 // it, and no chain failed. A chain that Stop ends gives the reply "stopped".
299 func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
300 defer r.workers.Done()
305 for more := true; more; {
306 reply, err := r.chain(ctx, run)
309 stopped = run.stopped
311 case err != nil && stopped:
314 reply = "failed: " + err.Error()
317 more = err == nil && ctx.Err() == nil && len(run.pending) > 0
320 delete(r.running, run.subagent.name)
324 replies = append(replies, reply)
327 if ctx.Err() != nil && !stopped {
331 r.report(subagentReport(run.subagent.name, replies), stopped)
334 // chain runs one request chain of run and returns its final answer.
335 func (r *SubagentRuns) chain(ctx context.Context, run *SubagentRun) (string, error) {
336 instructions, err := r.agent.SubagentPrompt()
341 log, err := run.subagent.Show()
346 input := make([]any, 0, len(run.view)+2)
347 for _, text := range run.view {
348 input = append(input, modelUserMessage(text))
351 input = append(input, modelUserMessage(r.state()), modelUserMessage(log))
357 subagents: r.subagents,
358 workdir: run.subagent.WorkDir(),
360 request: ModelRequest{
361 Model: r.agent.config.Model,
363 Instructions: instructions,
364 Tools: promptSubagentTools(),
365 Agent: run.subagent.name,
367 take: func() []Message {
372 return chain.Run(ctx, input)
375 // take returns the messages of Tell that wait for a request of run, and
377 func (r *SubagentRuns) take(run *SubagentRun) []Message {
379 defer r.mutex.Unlock()
381 messages := run.pending
387 // SubagentRun is one run of a subagent: the view that its requests get, its
388 // effort, the end of its context, the messages of Tell that wait for a request,
389 // and whether Stop ended it. The mutex of SubagentRuns protects the messages
391 type SubagentRun struct {
395 cancel context.CancelFunc
400 // subagentReport returns the report of the subagent name with its replies: the
401 // name in brackets, a new line, the replies, and the zoom that gives its whole
403 func subagentReport(name string, replies []string) string {
404 return "[" + name + "]\n" + strings.Join(replies, "\n\n") + "\n\nFull chat: zoom(\"" + name + "\")"