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 // The statuses of the end of a run, in the work event of its report.
24 subagentFinished = "finished"
25 subagentStopped = "stopped"
26 subagentFailed = "failed"
29 // errSubagentClosed tells that the runs of the subagents ended with the loop.
30 var errSubagentClosed = errors.New("the daemon stops, so no subagent starts")
32 // SubagentRuns runs the subagents of one agent in the background. Each run is a
33 // goroutine with its own context, which only Stop and Close end. A run is one
34 // or more request chains. The first request of each chain holds the view of the
35 // agent at the start of the run, then the state of the turn, then the whole log
36 // of the subagent. A message of Tell that comes during a chain joins its next
37 // request after the tool results. One that comes after the final answer starts
38 // one more chain, which reads the log again. The report of the run goes to
39 // report: the final answer of each chain, or the error of a failed call. Stop
40 // ends one run, and its report says that it stopped. At the stop of the daemon
41 // the runs end with no report.
43 // Spawn and Tell split the view with the layout of the agent, which has no
44 // lock. They are tools, so they run in the goroutine of the turns, as each
45 // split of a turn does.
46 type SubagentRuns struct {
53 report func(name, text, status string)
54 note func(text string) error
58 running map[string]*SubagentRun
60 workers sync.WaitGroup
63 // Spawn starts one subagent for each task and returns their names at once. It
64 // waits until the view has no pending summary, and gives the view to each
65 // subagent. A nil effort is the effort of the agent.
66 func (r *SubagentRuns) Spawn(ctx context.Context, tasks []string, effort *string) (string, error) {
68 return "", errors.New("no tasks")
76 return "", errSubagentClosed
80 runEffort := r.agent.config.Effort
81 if effort != nil && !slices.Contains(promptEfforts, *effort) {
82 return "", fmt.Errorf("no effort %q: one of %s", *effort, strings.Join(promptEfforts, ", "))
85 if effort != nil && *effort != runEffort {
86 note += subagentNoteEffort + *effort
90 err := r.memory.Settle(ctx)
92 return "", fmt.Errorf("wait for the summaries: %w", err)
95 view, err := r.layout.Split(r.memory.ViewLines(nil))
100 names := make([]string, 0, len(tasks))
101 for _, task := range tasks {
102 name, err := r.create(ctx, note, task, view, runEffort)
103 if err != nil && len(names) > 0 {
104 return "", fmt.Errorf("started %s, then: %w", strings.Join(names, ", "), err)
111 names = append(names, name)
114 return "Started " + strings.Join(names, ", ") + ". Each one's report will reach you as a message when it finishes.", nil
117 // Tell sends message to the subagent name. A running subagent reads it between
118 // its tool calls, and its report answers it. A finished subagent goes on from
119 // its log with a new run, with the view of now and the effort of its note.
120 func (r *SubagentRuns) Tell(ctx context.Context, name, message string) (string, error) {
122 run, found := r.running[name]
124 defer r.mutex.Unlock()
126 told, err := run.subagent.Append("user", message)
131 run.pending = append(run.pending, told)
133 return "Sent. " + name + " reads it between its tool calls, and its report answers it.", nil
140 return "", errSubagentClosed
143 subagent, err := r.subagents.Get(ctx, name)
148 effort, err := r.effort(subagent)
153 err = r.memory.Settle(ctx)
155 return "", fmt.Errorf("wait for the summaries: %w", err)
158 view, err := r.layout.Split(r.memory.ViewLines(nil))
163 _, err = subagent.Append("user", message)
165 err = subagent.Flush(ctx)
172 err = r.start(ctx, &SubagentRun{
181 return "Sent. " + name + "'s reply will reach you as a message.", nil
184 // Stop ends the run of the subagent name and tells if it ran. The chat gets the
185 // note "Stopped by the user: NAME." under the mutex, so the note comes before
186 // the report of the run.
187 func (r *SubagentRuns) Stop(name string) (bool, error) {
189 defer r.mutex.Unlock()
191 run, found := r.running[name]
196 err := r.note("Stopped by the user: " + name + ".")
207 // Close ends every run and waits for them. No subagent starts after Close.
208 func (r *SubagentRuns) Close() {
211 for _, run := range r.running {
219 // create makes a new subagent with its note, its task, and its work directory,
220 // and starts its run.
221 func (r *SubagentRuns) create(ctx context.Context, note, task string, view []string, effort string) (string, error) {
222 subagent, err := r.subagents.Create(ctx)
227 for _, message := range [][2]string{{"note", note}, {"user", task}} {
228 _, err = subagent.Append(message[0], message[1])
234 err = subagent.Flush(ctx)
239 err = os.MkdirAll(subagent.WorkDir(), 0o700)
241 return "", fmt.Errorf("create work directory: %w", err)
244 return subagent.name, r.start(ctx, &SubagentRun{
251 // effort returns the effort of subagent from the note at the start of its log:
252 // the effort of the agent, or the effort that the note names.
253 func (r *SubagentRuns) effort(subagent *Subagent) (string, error) {
254 note, err := subagent.First()
259 effort, own := strings.CutPrefix(note.Text, subagentNote+subagentNoteEffort)
261 case note.Kind != "note":
264 case note.Text == subagentNote:
265 return r.agent.config.Effort, nil
268 return "", fmt.Errorf("the log of %s does not start with a subagent note", subagent.name)
271 // start runs run in the background. Its context keeps the values of ctx, but
272 // only Stop and Close end it.
273 func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
274 ctx, run.cancel = context.WithCancel(context.WithoutCancel(ctx))
277 _, found := r.running[run.subagent.name]
278 if r.closed || found {
283 return fmt.Errorf("%s runs already", run.subagent.name)
286 return errSubagentClosed
289 r.running[run.subagent.name] = run
295 Text: run.subagent.name,
303 // run runs the chains of run and reports its end, unless Close ended it. A
304 // chain follows while messages wait after the final answer of the chain before
305 // it, and no chain failed. A chain that Stop ends gives the reply "stopped".
306 func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
307 defer r.workers.Done()
312 status := subagentFinished
313 for more := true; more; {
314 reply, err := r.chain(ctx, run)
317 stopped = run.stopped
319 case err != nil && stopped:
322 reply = "failed: " + err.Error()
323 status = subagentFailed
326 more = err == nil && ctx.Err() == nil && len(run.pending) > 0
329 delete(r.running, run.subagent.name)
333 replies = append(replies, reply)
336 if ctx.Err() != nil && !stopped {
341 status = subagentStopped
344 r.report(run.subagent.name, subagentReport(run.subagent.name, replies), status)
347 // chain runs one request chain of run and returns its final answer.
348 func (r *SubagentRuns) chain(ctx context.Context, run *SubagentRun) (string, error) {
349 instructions, err := r.agent.SubagentPrompt()
354 log, err := run.subagent.Show()
359 input := make([]any, 0, len(run.view)+2)
360 for _, text := range run.view {
361 input = append(input, modelUserMessage(text))
364 input = append(input, modelUserMessage(r.state()), modelUserMessage(log))
370 subagents: r.subagents,
371 workdir: run.subagent.WorkDir(),
373 request: ModelRequest{
374 Model: r.agent.config.Model,
376 Instructions: instructions,
377 Tools: promptSubagentTools(),
378 Agent: run.subagent.name,
380 take: func() []Message {
385 return chain.Run(ctx, input)
388 // take returns the messages of Tell that wait for a request of run, and
390 func (r *SubagentRuns) take(run *SubagentRun) []Message {
392 defer r.mutex.Unlock()
394 messages := run.pending
400 // SubagentRun is one run of a subagent: the view that its requests get, its
401 // effort, the end of its context, the messages of Tell that wait for a request,
402 // and whether Stop ended it. The mutex of SubagentRuns protects the messages
404 type SubagentRun struct {
408 cancel context.CancelFunc
413 // subagentReport returns the report of the subagent name with its replies: the
414 // name in brackets, a new line, the replies, and the zoom that gives its whole
416 func subagentReport(name string, replies []string) string {
417 return "[" + name + "]\n" + strings.Join(replies, "\n\n") + "\n\nFull chat: zoom(\"" + name + "\")"