12 // newTurnLoop returns the loop of agent with its memory, its subagents, and the
13 // WhatsApp link of its tools. Its calls go through client, and notify gets each
14 // event. The clock gives the date of a turn.
15 func newTurnLoop(agent *Agent, memory *Memory, subagents *Subagents, whatsapp *WhatsApp, client ChainClient, clock func() time.Time, notify func(Event)) (*TurnLoop, error) {
16 layout, err := loadViewLayout(filepath.Join(agent.dir, viewLayoutFileName))
28 wake: make(chan struct{}, 1),
31 l.runs = &SubagentRuns{
42 running: make(map[string]*SubagentRun),
51 workdir: agent.config.Workdir,
57 // Event tells the clients what the agent does as it happens. Kind is the kind
58 // of a logged message (user, reply, tool, echo, note, work), or one of ready,
59 // busy, idle, error, and subagent, which tells that the subagent Text starts a
60 // run. ID is the ID of a logged message. Source names the client that sent a
61 // user message, such as terminal or telegram, so that each client can show the
62 // messages of the others, or the subagent of a report. Status tells how the run
63 // of a report ended: finished, stopped, or failed.
65 Kind string `json:"kind"`
66 ID int `json:"id,omitempty"`
67 Text string `json:"text,omitempty"`
68 Source string `json:"source,omitempty"`
69 Status string `json:"status,omitempty"`
72 // TurnLoop runs the turns of one agent. A user message goes to the log when it
73 // comes, and it wakes the loop. A turn waits until every message before it is
74 // summarized. Then the turn runs a Chain whose first request holds the prompt,
75 // the tools, and the input of turnInput.
77 // The view goes out as the messages of a ViewLayout, so the first request of a
78 // turn reads the view of the turn before from the prompt cache. User messages
79 // that come during a turn join the next request of its chain after the tool
80 // results, and so do the reports of the subagents. The subagents run until the
82 type TurnLoop struct {
89 clock func() time.Time
95 cancel context.CancelFunc
99 // Submit logs a user message from the client source and wakes the loop. The
100 // message joins the next request: the first one of a new turn, or the next one
101 // of a running turn.
102 func (l *TurnLoop) Submit(source, text string) (Message, error) {
103 message, err := l.record("user", source, text)
105 return Message{}, err
109 l.pending = append(l.pending, message)
113 case l.wake <- struct{}{}:
120 // Report logs the report text of the subagent name as a work message and tells
121 // the clients, with the status of the run. Unless the subagent was stopped, the
122 // report joins the waiting messages and wakes the loop, as a user message of
123 // Submit does. A failed write stops the loop, because the log refuses all
125 func (l *TurnLoop) Report(name, text, status string) {
126 message, err := l.Work(name, text, status)
129 l.fail(fmt.Errorf("%w: %w", errChainLogWrite, err))
130 case status != subagentStopped:
135 // Work logs text as a work message of source, such as the name of a subagent,
136 // and tells the clients, with status. The message starts no turn until it goes
138 func (l *TurnLoop) Work(source, text, status string) (Message, error) {
139 message, err := l.memory.Append("work", text)
141 return Message{}, err
155 // Wake adds the logged messages to the waiting messages and wakes the loop
156 // once, as a user message of Submit does. They join the first request of a new
157 // turn together, or the next request of a running turn after the tool results.
158 func (l *TurnLoop) Wake(messages ...Message) {
159 if len(messages) == 0 {
164 l.pending = append(l.pending, messages...)
168 case l.wake <- struct{}{}:
173 // StopSubagent ends the run of the subagent name and tells if it ran. Its
174 // report is logged, but it starts no turn.
175 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
176 return l.runs.Stop(name)
179 // Interrupt ends the running turn. A running tool is killed, and the turn sends
180 // no further request.
181 func (l *TurnLoop) Interrupt() bool {
183 defer l.mutex.Unlock()
194 // Busy tells if a turn runs.
195 func (l *TurnLoop) Busy() bool {
197 defer l.mutex.Unlock()
199 return l.cancel != nil
202 // Append logs a message and tells the clients. The toolbox logs its calls and
203 // results through it.
204 func (l *TurnLoop) Append(kind, text string) (Message, error) {
205 return l.record(kind, "", text)
208 // Flush makes the log durable.
209 func (l *TurnLoop) Flush(ctx context.Context) error {
210 return l.memory.Flush(ctx)
213 // Run runs a turn each time user messages or reports wait, until ctx ends. It
214 // returns the error of a failed log write, which stops the agent. At its start
215 // it resumes the subagents that a stop of the daemon cut, and at its end it
216 // ends the runs of the subagents and waits for them.
217 func (l *TurnLoop) Run(ctx context.Context) error {
220 err := l.runs.Resume(ctx)
222 return fmt.Errorf("resume subagents: %w", err)
246 // note logs a note and tells the clients. A note starts no turn.
247 func (l *TurnLoop) note(text string) error {
248 _, err := l.record("note", "", text)
253 // record logs a message and tells the clients, with the client source of a user
255 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
256 message, err := l.memory.Append(kind, text)
258 return Message{}, err
271 // waiting tells if user messages or reports wait for a request.
272 func (l *TurnLoop) waiting() bool {
274 defer l.mutex.Unlock()
276 return len(l.pending) > 0
279 // fail stops the loop with err.
280 func (l *TurnLoop) fail(err error) {
282 l.failure = errors.Join(l.failure, err)
286 case l.wake <- struct{}{}:
291 // failed returns the error of a failed write of a report.
292 func (l *TurnLoop) failed() error {
294 defer l.mutex.Unlock()
299 // turn runs one turn. A failed or interrupted model call ends the turn and
300 // tells the clients. The messages of the turn stay in the log and the view, and
301 // the next turn starts only with a new message, so a lasting failure such as a
302 // needed login does not repeat. Only a failed log write is an error of turn.
303 func (l *TurnLoop) turn(ctx context.Context) error {
304 ctx, cancel := context.WithCancel(ctx)
322 if err != nil && !errors.Is(err, errChainLogWrite) {
325 Text: turnError(ctx, err),
338 // chain runs the request chain of a turn until the final answer.
339 func (l *TurnLoop) chain(ctx context.Context) error {
341 if len(messages) == 0 {
345 err := l.memory.Wait(ctx)
350 instructions, err := l.agent.Prompt()
355 skip := make(map[int]bool, len(messages))
356 for _, message := range messages {
357 skip[message.ID] = true
360 view, err := l.layout.Split(l.memory.ViewLines(skip))
368 request: ModelRequest{
369 Model: l.agent.config.Model,
370 Effort: l.agent.config.Effort,
371 Instructions: instructions,
372 Tools: promptTools(),
377 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
382 // take returns the user messages that wait for a request, and removes them.
383 func (l *TurnLoop) take() []Message {
385 defer l.mutex.Unlock()
387 messages := l.pending
393 // state returns the per-turn state: the end of the view, and the date and time
395 func (l *TurnLoop) state() string {
396 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
399 // turnError returns the text of the error that ended a turn.
400 func turnError(ctx context.Context, err error) string {
401 if ctx.Err() != nil {
408 // turnInput returns the input of the first request of a turn, stable parts
409 // first: a user message for each view message, one with the per-turn state,
410 // and one for each new message, whole. The view leaves out the leaf lines of
412 func turnInput(view []string, state string, messages []Message) []any {
413 input := make([]any, 0, len(view)+1+len(messages))
414 for _, text := range view {
415 input = append(input, modelUserMessage(text))
418 input = append(input, modelUserMessage(state))
419 for _, message := range messages {
420 input = append(input, modelUserMessage(message.Text))