17 // subagentNote is the first message of the log of a subagent.
18 subagentNote = "subagent"
20 // subagentNoteEffort follows subagentNote when the subagent has its own
22 subagentNoteEffort = " at effort "
24 // subagentWorkFileName is the file of the names of the running
25 // subagents in the directory of an agent.
26 subagentWorkFileName = "work.json"
29 // The statuses of the end of a run, in the work event of its report.
31 subagentFinished = "finished"
32 subagentStopped = "stopped"
33 subagentFailed = "failed"
36 // errSubagentClosed tells that the runs of the subagents ended with the loop.
37 var errSubagentClosed = errors.New("the daemon stops, so no subagent starts")
39 // SubagentRuns runs the subagents of one agent in the background. Each run is a
40 // goroutine with its own context, which only Stop and Close end. A run is one
41 // or more request chains. The first request of each chain holds the view of the
42 // agent at the start of the run, then the state of the turn, then the whole log
43 // of the subagent. A message of Tell that comes during a chain joins its next
44 // request after the tool results. One that comes after the final answer starts
45 // one more chain, which reads the log again. The report of the run goes to
46 // report: the final answer of each chain, or the error of a failed call. Stop
47 // ends one run, and its report says that it stopped. At the stop of the daemon
48 // the runs end with no report.
50 // work.json in the directory of the agent holds the names of the running
51 // subagents. Each start and each end of a run writes it whole, but Close does
52 // not, so after a stop of the daemon it names the runs that the stop cut, and
53 // Resume goes on with them. The logs alone cannot tell this, because a stop
54 // can cut a run just after its final reply.
56 // Spawn and Tell split the view with the layout of the agent, which has no
57 // lock. They are tools, so they run in the goroutine of the turns, as each
58 // split of a turn does.
59 type SubagentRuns struct {
66 report func(name, text, status string)
67 note func(text string) error
72 running map[string]*SubagentRun
74 workers sync.WaitGroup
77 // Spawn starts one subagent for each task and returns their names at once. It
78 // waits until the view has no pending summary, and gives the view to each
79 // subagent. A nil effort is the effort of the agent.
80 func (r *SubagentRuns) Spawn(ctx context.Context, tasks []string, effort *string) (string, error) {
82 return "", errors.New("no tasks")
90 return "", errSubagentClosed
94 runEffort := r.agent.config.Effort
95 if effort != nil && !slices.Contains(promptEfforts, *effort) {
96 return "", fmt.Errorf("no effort %q: one of %s", *effort, strings.Join(promptEfforts, ", "))
99 if effort != nil && *effort != runEffort {
100 note += subagentNoteEffort + *effort
104 err := r.memory.Settle(ctx)
106 return "", fmt.Errorf("wait for the summaries: %w", err)
109 view, err := r.layout.Split(r.memory.ViewLines(nil))
114 names := make([]string, 0, len(tasks))
115 for _, task := range tasks {
116 name, err := r.create(ctx, note, task, view, runEffort)
117 if err != nil && len(names) > 0 {
118 return "", fmt.Errorf("started %s, then: %w", strings.Join(names, ", "), err)
125 names = append(names, name)
128 return "Started " + strings.Join(names, ", ") + ". Each one's report will reach you as a message when it finishes.", nil
131 // Tell sends message to the subagent name. A running subagent reads it between
132 // its tool calls, and its report answers it. A finished subagent goes on from
133 // its log with a new run, with the view of now and the effort of its note.
134 func (r *SubagentRuns) Tell(ctx context.Context, name, message string) (string, error) {
136 run, found := r.running[name]
138 defer r.mutex.Unlock()
140 told, err := run.subagent.Append("user", message)
145 run.pending = append(run.pending, told)
147 return "Sent. " + name + " reads it between its tool calls, and its report answers it.", nil
154 return "", errSubagentClosed
157 subagent, err := r.subagents.Get(ctx, name)
162 effort, err := r.effort(subagent)
167 err = r.memory.Settle(ctx)
169 return "", fmt.Errorf("wait for the summaries: %w", err)
172 view, err := r.layout.Split(r.memory.ViewLines(nil))
177 _, err = subagent.Append("user", message)
179 err = subagent.Flush(ctx)
186 err = r.start(ctx, &SubagentRun{
195 return "Sent. " + name + "'s reply will reach you as a message.", nil
198 // Stop ends the run of the subagent name and tells if it ran. The chat gets the
199 // note "Stopped by the user: NAME." under the mutex, so the note comes before
200 // the report of the run.
201 func (r *SubagentRuns) Stop(name string) (bool, error) {
203 defer r.mutex.Unlock()
205 run, found := r.running[name]
210 err := r.note("Stopped by the user: " + name + ".")
221 // Resume goes on with the runs that a stop of the daemon cut, as work.json
222 // names them. The chat gets the note "The daemon restarted, cutting NAMES;
223 // nothing was lost: go on.", and each cut subagent gets the same text as a
224 // message of Tell. A subagent that cannot go on gets a failed report.
225 func (r *SubagentRuns) Resume(ctx context.Context) error {
226 names, err := r.load()
227 if err != nil || len(names) == 0 {
231 text := "The daemon restarted, cutting " + strings.Join(names, ", ") + "; nothing was lost: go on."
237 for _, name := range names {
238 _, err = r.Tell(ctx, name, text)
240 r.report(name, subagentReport(name, []string{"failed: " + err.Error()}), subagentFailed)
244 // A subagent that cannot go on does not run, so work.json no longer
245 // names it, and the next start does not try it again.
247 defer r.mutex.Unlock()
252 // Close ends every run and waits for them. No subagent starts after Close.
253 func (r *SubagentRuns) Close() {
256 for _, run := range r.running {
264 // create makes a new subagent with its note, its task, and its work directory,
265 // and starts its run.
266 func (r *SubagentRuns) create(ctx context.Context, note, task string, view []string, effort string) (string, error) {
267 subagent, err := r.subagents.Create(ctx)
272 for _, message := range [][2]string{{"note", note}, {"user", task}} {
273 _, err = subagent.Append(message[0], message[1])
279 err = subagent.Flush(ctx)
284 err = os.MkdirAll(subagent.WorkDir(), 0o700)
286 return "", fmt.Errorf("create work directory: %w", err)
289 return subagent.name, r.start(ctx, &SubagentRun{
296 // effort returns the effort of subagent from the note at the start of its log:
297 // the effort of the agent, or the effort that the note names.
298 func (r *SubagentRuns) effort(subagent *Subagent) (string, error) {
299 note, err := subagent.First()
304 effort, own := strings.CutPrefix(note.Text, subagentNote+subagentNoteEffort)
306 case note.Kind != "note":
309 case note.Text == subagentNote:
310 return r.agent.config.Effort, nil
313 return "", fmt.Errorf("the log of %s does not start with a subagent note", subagent.name)
316 // start runs run in the background. Its context keeps the values of ctx, but
317 // only Stop and Close end it.
318 func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
319 ctx, run.cancel = context.WithCancel(context.WithoutCancel(ctx))
322 _, found := r.running[run.subagent.name]
323 if r.closed || found {
328 return fmt.Errorf("%s runs already", run.subagent.name)
331 return errSubagentClosed
334 r.running[run.subagent.name] = run
337 delete(r.running, run.subagent.name)
349 Text: run.subagent.name,
357 // load reads the names of work.json. A missing file names none.
358 func (r *SubagentRuns) load() ([]string, error) {
359 data, err := os.ReadFile(r.workPath())
360 if errors.Is(err, os.ErrNotExist) {
365 return nil, fmt.Errorf("read running subagents: %w", err)
368 var file SubagentWorkFile
369 err = json.Unmarshal(data, &file)
371 return nil, fmt.Errorf("decode running subagents: %w", err)
374 return file.Running, nil
377 // save writes the names of the running subagents to work.json. The caller
379 func (r *SubagentRuns) save() error {
380 file := SubagentWorkFile{
381 Running: append([]string{}, slices.Sorted(maps.Keys(r.running))...),
384 data, err := json.Marshal(file)
386 return fmt.Errorf("encode running subagents: %w", err)
389 err = writeFileAtomic(r.workPath(), append(data, '\n'))
391 return fmt.Errorf("save running subagents: %w", err)
397 func (r *SubagentRuns) workPath() string {
398 return filepath.Join(r.agent.dir, subagentWorkFileName)
401 // run runs the chains of run and reports its end, unless Close ended it. A
402 // chain follows while messages wait after the final answer of the chain before
403 // it, and no chain failed. A chain that Stop ends gives the reply "stopped".
404 func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
405 defer r.workers.Done()
410 status := subagentFinished
411 for more := true; more; {
412 reply, err := r.chain(ctx, run)
415 stopped = run.stopped
417 case err != nil && stopped:
420 reply = "failed: " + err.Error()
421 status = subagentFailed
424 more = err == nil && ctx.Err() == nil && len(run.pending) > 0
428 delete(r.running, run.subagent.name)
439 replies = append(replies, reply)
442 if ctx.Err() != nil && !stopped {
447 status = subagentStopped
450 r.report(run.subagent.name, subagentReport(run.subagent.name, replies), status)
453 // chain runs one request chain of run and returns its final answer.
454 func (r *SubagentRuns) chain(ctx context.Context, run *SubagentRun) (string, error) {
455 instructions, err := r.agent.SubagentPrompt()
460 log, err := run.subagent.Show()
465 input := make([]any, 0, len(run.view)+2)
466 for _, text := range run.view {
467 input = append(input, modelUserMessage(text))
470 input = append(input, modelUserMessage(r.state()), modelUserMessage(log))
476 subagents: r.subagents,
477 workdir: run.subagent.WorkDir(),
479 request: ModelRequest{
480 Model: r.agent.config.Model,
482 Instructions: instructions,
483 Tools: promptSubagentTools(),
484 Agent: run.subagent.name,
486 take: func() []Message {
491 return chain.Run(ctx, input)
494 // take returns the messages of Tell that wait for a request of run, and
496 func (r *SubagentRuns) take(run *SubagentRun) []Message {
498 defer r.mutex.Unlock()
500 messages := run.pending
506 // SubagentRun is one run of a subagent: the view that its requests get, its
507 // effort, the end of its context, the messages of Tell that wait for a request,
508 // and whether Stop ended it. The mutex of SubagentRuns protects the messages
510 type SubagentRun struct {
514 cancel context.CancelFunc
519 // SubagentWorkFile is the content of work.json.
520 type SubagentWorkFile struct {
521 Running []string `json:"running"`
524 // subagentReport returns the report of the subagent name with its replies: the
525 // name in brackets, a new line, the replies, and the zoom that gives its whole
527 func subagentReport(name string, replies []string) string {
528 return "[" + name + "]\n" + strings.Join(replies, "\n\n") + "\n\nFull chat: zoom(\"" + name + "\")"