13 // Event tells the clients what the agent does as it happens. Kind is the kind
14 // of a logged message (user, reply, tool, echo, note, work), or one of ready,
15 // busy, idle, error, and subagent, which tells that the subagent Text starts a
16 // run. ID is the ID of a logged message. Source names the client that sent a
17 // user message, such as terminal or telegram, so that each client can show the
18 // messages of the others, or the subagent of a report. Status tells how the run
19 // of a report ended: finished, stopped, or failed. A private notify receipt
20 // uses ID for its queue sequence and Status for accepted or duplicate, not
23 Kind string `json:"kind"`
24 ID int `json:"id,omitempty"`
25 Text string `json:"text,omitempty"`
26 Source string `json:"source,omitempty"`
27 Status string `json:"status,omitempty"`
30 // TurnLoop runs the turns of one agent. A user message goes to the log when it
31 // comes, and it wakes the loop. A turn waits until every message before it is
32 // summarized. Then the turn runs a Chain whose first request holds the prompt,
33 // the tools, and the input of turnInput.
35 // The view goes out as the messages of a ViewLayout, so the first request of a
36 // turn reads the view of the turn before from the prompt cache. User messages
37 // that come during a turn join the next request of its chain after the tool
38 // results, and so do the reports of the subagents. The subagents run until the
39 // loop ends. Parent and child messages stay queued until the turn finishes.
40 // active belongs to the running turn. The mutex protects pending, cancel, and
42 type TurnLoop struct {
49 clock func() time.Time
53 messages *DaemonMessages
54 openChild func(context.Context, *Agent) (*DaemonAgent, error)
59 cancel context.CancelFunc
63 // newTurnLoop returns the loop of agent with its memory, its subagents, and the
64 // WhatsApp link and the schedules of its tools. Its calls go through client,
65 // and notify gets each event. The clock gives the date of a turn. logger gets
66 // the failed turns and the ends of the subagents. A child has no WhatsApp
67 // tools, even when the caller supplies a link.
68 func newTurnLoop(agent *Agent, memory *Memory, subagents *Subagents, whatsapp *WhatsApp, schedules *Schedules, client ChainClient, clock func() time.Time, logger *slog.Logger, notify func(Event)) (*TurnLoop, error) {
69 layout, err := loadViewLayout(filepath.Join(agent.dir, viewLayoutFileName))
82 wake: make(chan struct{}, 1),
85 l.runs = &SubagentRuns{
97 running: make(map[string]*SubagentRun),
100 if agent.config.Parent != "" {
107 subagents: subagents,
110 schedules: schedules,
111 workdir: agent.config.Workdir,
112 agentName: agent.config.Name,
113 images: agent.Images(),
116 if agent.config.Parent == "" {
117 l.tools.imageShow = &ImageShow{store: agent.Images()}
123 // state returns the per-turn state: the end of the view, and the date and time
124 // of the turn, then the names and responsibilities of its children.
125 func (l *TurnLoop) state() string {
126 state := "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
127 if l.messages != nil {
128 state += l.messages.ChildState(l.agent.config.Name)
134 // Report logs the report text of the subagent name as a work message and tells
135 // the clients, with the status of the run. Unless the subagent was stopped, the
136 // report joins the waiting messages and wakes the loop, as a user message of
137 // Submit does. A failed write stops the loop, because the log refuses all
139 func (l *TurnLoop) Report(name, text, status string) {
140 message, err := l.Work(name, text, status)
143 l.fail(fmt.Errorf("%w: %w", errChainLogWrite, err))
144 case status != subagentStopped:
149 // note logs a note and tells the clients. A note starts no turn.
150 func (l *TurnLoop) note(text string) error {
151 _, err := l.record("note", "", text)
156 // fail stops the loop with err.
157 func (l *TurnLoop) fail(err error) {
160 l.failure = errors.Join(l.failure, err)
164 case l.wake <- struct{}{}:
169 // Work logs text as a work message of source, such as the name of a subagent,
170 // and tells the clients, with status. The message starts no turn until it goes
172 func (l *TurnLoop) Work(source, text, status string) (Message, error) {
173 message, err := l.memory.Append("work", text)
175 return Message{}, err
189 // Wake adds the logged messages to the waiting messages and wakes the loop
190 // once, as a user message of Submit does. They join the first request of a new
191 // turn together, or the next request of a running turn after the tool results.
192 func (l *TurnLoop) Wake(messages ...Message) {
193 if len(messages) == 0 {
199 l.pending = append(l.pending, messages...)
203 case l.wake <- struct{}{}:
208 // record logs a message and tells the clients, with the client source of a user
210 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
211 message, err := l.memory.Append(kind, text)
213 return Message{}, err
226 // Submit logs a user message from the client source and wakes the loop. The
227 // message joins the next request: the first one of a new turn, or the next one
228 // of a running turn.
229 func (l *TurnLoop) Submit(source, text string) (Message, error) {
230 message, err := l.record("user", source, text)
232 return Message{}, err
237 l.pending = append(l.pending, message)
241 case l.wake <- struct{}{}:
248 // StopSubagent ends the run of the subagent name and tells if it ran. Its
249 // report is logged, but it starts no turn.
250 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
251 return l.runs.Stop(name)
254 // Interrupt ends the running turn. A running tool is killed, and the turn sends
255 // no further request.
256 func (l *TurnLoop) Interrupt() bool {
258 defer l.mutex.Unlock()
269 // Busy tells if a turn runs.
270 func (l *TurnLoop) Busy() bool {
272 defer l.mutex.Unlock()
274 return l.cancel != nil
277 // Append logs a message and tells the clients. The toolbox logs its calls and
278 // results through it.
279 func (l *TurnLoop) Append(kind, text string) (Message, error) {
280 return l.record(kind, "", text)
283 // Flush makes the log durable.
284 func (l *TurnLoop) Flush(ctx context.Context) error {
285 return l.memory.Flush(ctx)
288 // Run starts a turn when user messages, reports, or queued external events
289 // wait, until ctx ends. It returns the error of a failed log write, which stops
290 // the agent. External events enter memory only between chains. At its start it
291 // resumes the subagents that a stop of the daemon cut, and at its end it ends
292 // the runs of the subagents and waits for them.
293 func (l *TurnLoop) Run(ctx context.Context) error {
296 err := l.runs.Resume(ctx)
298 return fmt.Errorf("resume subagents: %w", err)
302 for ctx.Err() == nil {
305 return fmt.Errorf("check turn loop failure: %w", err)
308 if l.messages != nil {
309 err = l.messages.Notifications(l)
311 return fmt.Errorf("prepare external events: %w", err)
321 return fmt.Errorf("run turn: %w", err)
333 return fmt.Errorf("check turn loop failure: %w", err)
338 // waiting tells if user messages or reports wait for a request.
339 func (l *TurnLoop) waiting() bool {
341 defer l.mutex.Unlock()
343 return len(l.pending) > 0
346 // failed returns the error of a failed write of a report.
347 func (l *TurnLoop) failed() error {
349 defer l.mutex.Unlock()
354 // turn runs one turn. A failed or interrupted model call ends the turn and
355 // tells the clients. A failure also goes to the logger, so that it is not lost
356 // when no client is connected, but an interrupt does not. The messages of the
357 // turn stay in the log and the view, and the next turn starts only with a new
358 // message, so a lasting failure such as a needed login does not repeat. Only a
359 // failed log or queue write is an error of turn. A daemon stop leaves taken
360 // parent and child messages queued for restart. A user interrupt completes them
362 func (l *TurnLoop) turn(ctx context.Context) error {
364 ctx, cancel := context.WithCancel(ctx)
383 if l.messages != nil {
384 l.logger.Info("turn started")
387 reply, err := l.chain(ctx)
388 if l.messages != nil && !errors.Is(err, errChainLogWrite) && (err == nil || runCtx.Err() == nil) {
389 finishErr := l.messages.Finish(l, l.active, reply)
390 if finishErr != nil {
391 err = errors.Join(err, fmt.Errorf("%w: finish agent messages: %w", errChainLogWrite, finishErr))
396 if err != nil && !errors.Is(err, errChainLogWrite) {
397 if ctx.Err() == nil {
398 l.logger.Error("turn failed", "err", err)
403 Text: turnError(ctx, err),
409 if l.messages != nil {
410 l.logger.Info("turn done")
420 // chain runs the request chain of a turn until the final answer.
421 func (l *TurnLoop) chain(ctx context.Context) (string, error) {
423 if len(messages) == 0 {
427 err := l.memory.Wait(ctx)
429 return "", fmt.Errorf("wait for turn memory: %w", err)
432 instructions, err := l.agent.Prompt()
434 return "", fmt.Errorf("read turn prompt: %w", err)
437 skip := make(map[int]bool, len(messages))
438 for _, message := range messages {
439 skip[message.ID] = true
442 view, err := l.layout.Split(l.memory.ViewLines(skip))
444 return "", fmt.Errorf("split turn view: %w", err)
450 request: ModelRequest{
451 Model: l.agent.config.Model,
452 Effort: l.agent.config.Effort,
453 Instructions: instructions,
454 Tools: l.agent.Tools(),
457 images: l.agent.Images(),
460 input := turnInput(view, l.state(), messages)
461 for n, message := range messages {
462 input[len(input)-len(messages)+n], err = imageUserMessage(l.agent.Images(), message.Text)
464 return "", fmt.Errorf("read turn images: %w", err)
468 reply, err := chain.Run(ctx, input)
470 return "", fmt.Errorf("run turn chain: %w", err)
476 // take returns the user messages that wait for a request, and removes them.
477 func (l *TurnLoop) take() []Message {
479 defer l.mutex.Unlock()
481 messages := l.pending
483 if l.messages != nil {
484 l.active = append(l.active, messages...)
490 // turnError returns the text of the error that ended a turn.
491 func turnError(ctx context.Context, err error) string {
492 if ctx.Err() != nil {
499 // turnInput returns the input of the first request of a turn, stable parts
500 // first: a user message for each view message, one with the per-turn state,
501 // and one for each new message, whole. The view leaves out the leaf lines of
503 func turnInput(view []string, state string, messages []Message) []any {
504 input := make([]any, 0, len(view)+1+len(messages))
505 for _, text := range view {
506 input = append(input, modelUserMessage(text))
509 input = append(input, modelUserMessage(state))
510 for _, message := range messages {
511 input = append(input, modelUserMessage(message.Text))