19 // subagentNote is the first message of the log of a subagent.
20 subagentNote = "subagent"
22 // subagentNoteEffort follows subagentNote when the subagent has its own
24 subagentNoteEffort = " at effort "
26 // subagentWorkFileName is the file of the names of the running
27 // subagents in the directory of an agent.
28 subagentWorkFileName = "work.json"
31 // The statuses of the end of a run, in the work event of its report.
33 subagentFinished = "finished"
34 subagentStopped = "stopped"
35 subagentFailed = "failed"
38 // errSubagentClosed tells that the runs of the subagents ended with the loop.
39 var errSubagentClosed = errors.New("the daemon stops, so no subagent starts")
41 // SubagentRuns runs the subagents of one agent in the background. Each run is a
42 // goroutine with its own context, which only Stop and Close end. A run is one
43 // or more request chains. The first request of each chain holds the view of the
44 // agent at the start of the run, then the state of the turn, then the whole log
45 // of the subagent. A message of Tell that comes during a chain joins its next
46 // request after the tool results. One that comes after the final answer starts
47 // one more chain, which reads the log again. The report of the run goes to
48 // report: the final answer of each chain, or the error of a failed call. The
49 // logger gets one line at the end of a run: done, failed with the cause, or
50 // stopped. Stop ends one run, and its report says that it stopped. At the stop
51 // of the daemon the runs end with no report.
53 // work.json in the directory of the agent holds the names of the running
54 // subagents. Each start and each end of a run writes it whole, but Close does
55 // not, so after a stop of the daemon it names the runs that the stop cut, and
56 // Resume goes on with them. The logs alone cannot tell this, because a stop
57 // can cut a run just after its final reply.
59 // Spawn and Tell split the view with the layout of the agent, which has no
60 // lock. They are tools, so they run in the goroutine of the turns, as each
61 // split of a turn does.
62 type SubagentRuns struct {
69 report func(name, text, status string)
70 note func(text string) error
76 running map[string]*SubagentRun
78 workers sync.WaitGroup
81 // Spawn starts one subagent for each task and returns their names at once. It
82 // waits until the view has no pending summary, and gives the view to each
83 // subagent. A nil effort is the effort of the agent.
84 func (r *SubagentRuns) Spawn(ctx context.Context, tasks []string, effort *string) (string, error) {
86 return "", errors.New("no tasks")
95 return "", errSubagentClosed
99 runEffort := r.agent.config.Effort
100 if effort != nil && !slices.Contains(promptEfforts, *effort) {
101 return "", fmt.Errorf("no effort %q: one of %s", *effort, strings.Join(promptEfforts, ", "))
104 if effort != nil && *effort != runEffort {
105 note += subagentNoteEffort + *effort
109 err := r.memory.Settle(ctx)
111 return "", fmt.Errorf("wait for the summaries: %w", err)
114 view, err := r.layout.Split(r.memory.ViewLines(nil))
119 names := make([]string, 0, len(tasks))
120 for _, task := range tasks {
121 name, err := r.create(ctx, note, task, view, runEffort)
122 if err != nil && len(names) > 0 {
123 return "", fmt.Errorf("started %s, then: %w", strings.Join(names, ", "), err)
130 names = append(names, name)
133 return "Started " + strings.Join(names, ", ") + ". Each one's report will reach you as a message when it finishes.", nil
136 // Tell sends message to the subagent name. A running subagent reads it between
137 // its tool calls, and its report answers it. A finished subagent goes on from
138 // its log with a new run, with the view of now and the effort of its note.
139 func (r *SubagentRuns) Tell(ctx context.Context, name, message string) (string, error) {
142 run, found := r.running[name]
144 defer r.mutex.Unlock()
146 told, err := run.subagent.Append("user", message)
151 run.pending = append(run.pending, told)
153 return "Sent. " + name + " reads it between its tool calls, and its report answers it.", nil
160 return "", errSubagentClosed
163 subagent, err := r.subagents.Get(ctx, name)
168 effort, err := r.effort(subagent)
173 err = r.memory.Settle(ctx)
175 return "", fmt.Errorf("wait for the summaries: %w", err)
178 view, err := r.layout.Split(r.memory.ViewLines(nil))
183 _, err = subagent.Append("user", message)
185 err = subagent.Flush(ctx)
192 err = r.start(ctx, &SubagentRun{
201 return "Sent. " + name + "'s reply will reach you as a message.", nil
204 // Stop ends the run of the subagent name and tells if it ran. The chat gets the
205 // note "Stopped by the user: NAME." under the mutex, so the note comes before
206 // the report of the run.
207 func (r *SubagentRuns) Stop(name string) (bool, error) {
209 defer r.mutex.Unlock()
211 run, found := r.running[name]
216 err := r.note("Stopped by the user: " + name + ".")
227 // Resume goes on with the runs that a stop of the daemon cut, as work.json
228 // names them. The chat gets the note "The daemon restarted, cutting NAMES;
229 // nothing was lost: go on.", and each cut subagent gets the same text as a
230 // message of Tell. A subagent that cannot go on gets a failed report.
231 func (r *SubagentRuns) Resume(ctx context.Context) error {
232 names, err := r.load()
233 if err != nil || len(names) == 0 {
237 text := "The daemon restarted, cutting " + strings.Join(names, ", ") + "; nothing was lost: go on."
243 for _, name := range names {
244 _, err = r.Tell(ctx, name, text)
246 r.logger.Printf("subagent %s lost at restart: %v", name, err)
247 r.report(name, subagentReport(name, []string{"failed: " + err.Error()}), subagentFailed)
251 // A subagent that cannot go on does not run, so work.json no longer
252 // names it, and the next start does not try it again.
254 defer r.mutex.Unlock()
259 // Close ends every run and waits for them. No subagent starts after Close.
260 func (r *SubagentRuns) Close() {
264 for _, run := range r.running {
273 // create makes a new subagent with its note, its task, and its work directory,
274 // and starts its run.
275 func (r *SubagentRuns) create(ctx context.Context, note, task string, view []string, effort string) (string, error) {
276 subagent, err := r.subagents.Create(ctx)
281 for _, message := range [][2]string{{"note", note}, {"user", task}} {
282 _, err = subagent.Append(message[0], message[1])
288 err = subagent.Flush(ctx)
293 err = os.MkdirAll(subagent.WorkDir(), 0o700)
295 return "", fmt.Errorf("create work directory: %w", err)
298 return subagent.name, r.start(ctx, &SubagentRun{
305 // effort returns the effort of subagent from the note at the start of its log:
306 // the effort of the agent, or the effort that the note names.
307 func (r *SubagentRuns) effort(subagent *Subagent) (string, error) {
308 note, err := subagent.First()
313 effort, own := strings.CutPrefix(note.Text, subagentNote+subagentNoteEffort)
315 case note.Kind != "note":
318 case note.Text == subagentNote:
319 return r.agent.config.Effort, nil
322 return "", fmt.Errorf("the log of %s does not start with a subagent note", subagent.name)
325 // start runs run in the background and logs its start. Its context keeps the
326 // values of ctx, but only Stop and Close end it.
327 func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
328 ctx, run.cancel = context.WithCancel(context.WithoutCancel(ctx))
332 _, found := r.running[run.subagent.name]
333 if r.closed || found {
338 return fmt.Errorf("%s runs already", run.subagent.name)
341 return errSubagentClosed
344 r.running[run.subagent.name] = run
347 delete(r.running, run.subagent.name)
357 run.started = r.subagents.clock()
358 r.logger.Printf("subagent %s started", run.subagent.name)
361 Text: run.subagent.name,
369 // load reads the names of work.json. A missing file names none.
370 func (r *SubagentRuns) load() ([]string, error) {
371 data, err := os.ReadFile(r.workPath())
372 if errors.Is(err, os.ErrNotExist) {
377 return nil, fmt.Errorf("read running subagents: %w", err)
380 var file SubagentWorkFile
382 err = json.Unmarshal(data, &file)
384 return nil, fmt.Errorf("decode running subagents: %w", err)
387 return file.Running, nil
390 // save writes the names of the running subagents to work.json. The caller
392 func (r *SubagentRuns) save() error {
393 file := SubagentWorkFile{
394 Running: append([]string{}, slices.Sorted(maps.Keys(r.running))...),
397 data, err := json.Marshal(file)
399 return fmt.Errorf("encode running subagents: %w", err)
402 err = writeFileAtomic(r.workPath(), append(data, '\n'))
404 return fmt.Errorf("save running subagents: %w", err)
410 func (r *SubagentRuns) workPath() string {
411 return filepath.Join(r.agent.dir, subagentWorkFileName)
414 // run runs the chains of run and reports and logs its end with the length of
415 // the run, unless Close ended it. A chain follows while messages wait after the final answer of the chain before
416 // it, and no chain failed. A chain that Stop ends gives the reply "stopped".
417 func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
418 defer r.workers.Done()
427 status := subagentFinished
428 for more := true; more; {
429 reply, err := r.chain(ctx, run)
433 stopped = run.stopped
435 case err != nil && stopped:
438 reply = "failed: " + err.Error()
439 status = subagentFailed
443 more = err == nil && ctx.Err() == nil && len(run.pending) > 0
449 delete(r.running, run.subagent.name)
462 replies = append(replies, reply)
465 if ctx.Err() != nil && !stopped {
470 status = subagentStopped
473 length := durationText(r.subagents.clock().Sub(run.started))
475 case subagentStopped:
476 r.logger.Printf("subagent %s stopped after %s", run.subagent.name, length)
478 r.logger.Printf("subagent %s failed after %s: %v", run.subagent.name, length, failure)
480 r.logger.Printf("subagent %s done after %s", run.subagent.name, length)
483 r.report(run.subagent.name, subagentReport(run.subagent.name, replies), status)
486 // chain runs one request chain of run and returns its final answer.
487 func (r *SubagentRuns) chain(ctx context.Context, run *SubagentRun) (string, error) {
488 instructions, err := r.agent.SubagentPrompt()
493 log, err := run.subagent.Show()
498 input := make([]any, 0, len(run.view)+2)
499 for _, text := range run.view {
500 input = append(input, modelUserMessage(text))
503 input = append(input, modelUserMessage(r.state()), modelUserMessage(log))
509 subagents: r.subagents,
510 workdir: run.subagent.WorkDir(),
512 request: ModelRequest{
513 Model: r.agent.config.Model,
515 Instructions: instructions,
516 Tools: promptSubagentTools(),
517 Agent: run.subagent.name,
519 take: func() []Message {
524 return chain.Run(ctx, input)
527 // take returns the messages of Tell that wait for a request of run, and
529 func (r *SubagentRuns) take(run *SubagentRun) []Message {
531 defer r.mutex.Unlock()
533 messages := run.pending
539 // SubagentRun is one run of a subagent: the view that its requests get, its
540 // effort, the end of its context, the messages of Tell that wait for a request,
541 // whether Stop ended it, and the time it started. The mutex of SubagentRuns protects the messages
543 type SubagentRun struct {
547 cancel context.CancelFunc
553 // SubagentWorkFile is the content of work.json.
554 type SubagentWorkFile struct {
555 Running []string `json:"running"`
558 // subagentReport returns the report of the subagent name with its replies: the
559 // name in brackets, a new line, the replies, and the zoom that gives its whole
561 func subagentReport(name string, replies []string) string {
562 return "[" + name + "]\n" + strings.Join(replies, "\n\n") + "\n\nFull chat: zoom(\"" + name + "\")"