13 // newTurnLoop returns the loop of agent with its memory, its subagents, and the
14 // WhatsApp link and the schedules of its tools. Its calls go through client,
15 // and notify gets each event. The clock gives the date of a turn. logger gets
16 // the failed turns and the ends of the subagents.
17 func newTurnLoop(agent *Agent, memory *Memory, subagents *Subagents, whatsapp *WhatsApp, schedules *Schedules, client ChainClient, clock func() time.Time, logger *log.Logger, notify func(Event)) (*TurnLoop, error) {
18 layout, err := loadViewLayout(filepath.Join(agent.dir, viewLayoutFileName))
31 wake: make(chan struct{}, 1),
34 l.runs = &SubagentRuns{
46 running: make(map[string]*SubagentRun),
56 workdir: agent.config.Workdir,
62 // Event tells the clients what the agent does as it happens. Kind is the kind
63 // of a logged message (user, reply, tool, echo, note, work), or one of ready,
64 // busy, idle, error, and subagent, which tells that the subagent Text starts a
65 // run. ID is the ID of a logged message. Source names the client that sent a
66 // user message, such as terminal or telegram, so that each client can show the
67 // messages of the others, or the subagent of a report. Status tells how the run
68 // of a report ended: finished, stopped, or failed.
70 Kind string `json:"kind"`
71 ID int `json:"id,omitempty"`
72 Text string `json:"text,omitempty"`
73 Source string `json:"source,omitempty"`
74 Status string `json:"status,omitempty"`
77 // TurnLoop runs the turns of one agent. A user message goes to the log when it
78 // comes, and it wakes the loop. A turn waits until every message before it is
79 // summarized. Then the turn runs a Chain whose first request holds the prompt,
80 // the tools, and the input of turnInput.
82 // The view goes out as the messages of a ViewLayout, so the first request of a
83 // turn reads the view of the turn before from the prompt cache. User messages
84 // that come during a turn join the next request of its chain after the tool
85 // results, and so do the reports of the subagents. The subagents run until the
87 type TurnLoop struct {
94 clock func() time.Time
101 cancel context.CancelFunc
105 // Submit logs a user message from the client source and wakes the loop. The
106 // message joins the next request: the first one of a new turn, or the next one
107 // of a running turn.
108 func (l *TurnLoop) Submit(source, text string) (Message, error) {
109 message, err := l.record("user", source, text)
111 return Message{}, err
115 l.pending = append(l.pending, message)
119 case l.wake <- struct{}{}:
126 // Report logs the report text of the subagent name as a work message and tells
127 // the clients, with the status of the run. Unless the subagent was stopped, the
128 // report joins the waiting messages and wakes the loop, as a user message of
129 // Submit does. A failed write stops the loop, because the log refuses all
131 func (l *TurnLoop) Report(name, text, status string) {
132 message, err := l.Work(name, text, status)
135 l.fail(fmt.Errorf("%w: %w", errChainLogWrite, err))
136 case status != subagentStopped:
141 // Work logs text as a work message of source, such as the name of a subagent,
142 // and tells the clients, with status. The message starts no turn until it goes
144 func (l *TurnLoop) Work(source, text, status string) (Message, error) {
145 message, err := l.memory.Append("work", text)
147 return Message{}, err
161 // Wake adds the logged messages to the waiting messages and wakes the loop
162 // once, as a user message of Submit does. They join the first request of a new
163 // turn together, or the next request of a running turn after the tool results.
164 func (l *TurnLoop) Wake(messages ...Message) {
165 if len(messages) == 0 {
170 l.pending = append(l.pending, messages...)
174 case l.wake <- struct{}{}:
179 // StopSubagent ends the run of the subagent name and tells if it ran. Its
180 // report is logged, but it starts no turn.
181 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
182 return l.runs.Stop(name)
185 // Interrupt ends the running turn. A running tool is killed, and the turn sends
186 // no further request.
187 func (l *TurnLoop) Interrupt() bool {
189 defer l.mutex.Unlock()
200 // Busy tells if a turn runs.
201 func (l *TurnLoop) Busy() bool {
203 defer l.mutex.Unlock()
205 return l.cancel != nil
208 // Append logs a message and tells the clients. The toolbox logs its calls and
209 // results through it.
210 func (l *TurnLoop) Append(kind, text string) (Message, error) {
211 return l.record(kind, "", text)
214 // Flush makes the log durable.
215 func (l *TurnLoop) Flush(ctx context.Context) error {
216 return l.memory.Flush(ctx)
219 // Run runs a turn each time user messages or reports wait, until ctx ends. It
220 // returns the error of a failed log write, which stops the agent. At its start
221 // it resumes the subagents that a stop of the daemon cut, and at its end it
222 // ends the runs of the subagents and waits for them.
223 func (l *TurnLoop) Run(ctx context.Context) error {
226 err := l.runs.Resume(ctx)
228 return fmt.Errorf("resume subagents: %w", err)
252 // note logs a note and tells the clients. A note starts no turn.
253 func (l *TurnLoop) note(text string) error {
254 _, err := l.record("note", "", text)
259 // record logs a message and tells the clients, with the client source of a user
261 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
262 message, err := l.memory.Append(kind, text)
264 return Message{}, err
277 // waiting tells if user messages or reports wait for a request.
278 func (l *TurnLoop) waiting() bool {
280 defer l.mutex.Unlock()
282 return len(l.pending) > 0
285 // fail stops the loop with err.
286 func (l *TurnLoop) fail(err error) {
288 l.failure = errors.Join(l.failure, err)
292 case l.wake <- struct{}{}:
297 // failed returns the error of a failed write of a report.
298 func (l *TurnLoop) failed() error {
300 defer l.mutex.Unlock()
305 // turn runs one turn. A failed or interrupted model call ends the turn and
306 // tells the clients. A failure also goes to the logger, so that it is not lost
307 // when no client is connected, but an interrupt does not. The messages of the
308 // turn stay in the log and the view, and the next turn starts only with a new
309 // message, so a lasting failure such as a needed login does not repeat. Only a
310 // failed log write is an error of turn.
311 func (l *TurnLoop) turn(ctx context.Context) error {
312 ctx, cancel := context.WithCancel(ctx)
330 if err != nil && !errors.Is(err, errChainLogWrite) {
331 if ctx.Err() == nil {
332 l.logger.Printf("turn failed: %v", err)
337 Text: turnError(ctx, err),
350 // chain runs the request chain of a turn until the final answer.
351 func (l *TurnLoop) chain(ctx context.Context) error {
353 if len(messages) == 0 {
357 err := l.memory.Wait(ctx)
362 instructions, err := l.agent.Prompt()
367 skip := make(map[int]bool, len(messages))
368 for _, message := range messages {
369 skip[message.ID] = true
372 view, err := l.layout.Split(l.memory.ViewLines(skip))
380 request: ModelRequest{
381 Model: l.agent.config.Model,
382 Effort: l.agent.config.Effort,
383 Instructions: instructions,
384 Tools: promptTools(),
389 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
394 // take returns the user messages that wait for a request, and removes them.
395 func (l *TurnLoop) take() []Message {
397 defer l.mutex.Unlock()
399 messages := l.pending
405 // state returns the per-turn state: the end of the view, and the date and time
407 func (l *TurnLoop) state() string {
408 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
411 // turnError returns the text of the error that ended a turn.
412 func turnError(ctx context.Context, err error) string {
413 if ctx.Err() != nil {
420 // turnInput returns the input of the first request of a turn, stable parts
421 // first: a user message for each view message, one with the per-turn state,
422 // and one for each new message, whole. The view leaves out the leaf lines of
424 func turnInput(view []string, state string, messages []Message) []any {
425 input := make([]any, 0, len(view)+1+len(messages))
426 for _, text := range view {
427 input = append(input, modelUserMessage(text))
430 input = append(input, modelUserMessage(state))
431 for _, message := range messages {
432 input = append(input, modelUserMessage(message.Text))