12 // newTurnLoop returns the loop of agent with its memory and its subagents. Its
13 // calls go through client, and notify gets each event. The clock gives the date
15 func newTurnLoop(agent *Agent, memory *Memory, subagents *Subagents, 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),
50 workdir: agent.config.Workdir,
56 // Event tells the clients what the agent does as it happens. Kind is the kind
57 // of a logged message (user, reply, tool, echo, note, work), or one of ready,
58 // busy, idle, error, and subagent, which tells that the subagent Text starts a
59 // run. ID is the ID of a logged message. Source names the client that sent a
60 // user message, such as terminal or telegram, so that each client can show the
61 // messages of the others, or the subagent of a report. Status tells how the run
62 // of a report ended: finished, stopped, or failed.
64 Kind string `json:"kind"`
65 ID int `json:"id,omitempty"`
66 Text string `json:"text,omitempty"`
67 Source string `json:"source,omitempty"`
68 Status string `json:"status,omitempty"`
71 // TurnLoop runs the turns of one agent. A user message goes to the log when it
72 // comes, and it wakes the loop. A turn waits until every message before it is
73 // summarized. Then the turn runs a Chain whose first request holds the prompt,
74 // the tools, and the input of turnInput.
76 // The view goes out as the messages of a ViewLayout, so the first request of a
77 // turn reads the view of the turn before from the prompt cache. User messages
78 // that come during a turn join the next request of its chain after the tool
79 // results, and so do the reports of the subagents. The subagents run until the
81 type TurnLoop struct {
88 clock func() time.Time
94 cancel context.CancelFunc
98 // Submit logs a user message from the client source and wakes the loop. The
99 // message joins the next request: the first one of a new turn, or the next one
100 // of a running turn.
101 func (l *TurnLoop) Submit(source, text string) (Message, error) {
102 message, err := l.record("user", source, text)
104 return Message{}, err
108 l.pending = append(l.pending, message)
112 case l.wake <- struct{}{}:
119 // Report logs the report text of the subagent name as a work message and tells
120 // the clients, with the status of the run. Unless the subagent was stopped, the
121 // report joins the waiting messages and wakes the loop, as a user message of
122 // Submit does. A failed write stops the loop, because the log refuses all
124 func (l *TurnLoop) Report(name, text, status string) {
125 message, err := l.memory.Append("work", text)
139 l.failure = fmt.Errorf("%w: %w", errChainLogWrite, err)
140 case status != subagentStopped:
141 l.pending = append(l.pending, message)
146 case l.wake <- struct{}{}:
151 // StopSubagent ends the run of the subagent name and tells if it ran. Its
152 // report is logged, but it starts no turn.
153 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
154 return l.runs.Stop(name)
157 // Interrupt ends the running turn. A running tool is killed, and the turn sends
158 // no further request.
159 func (l *TurnLoop) Interrupt() bool {
161 defer l.mutex.Unlock()
172 // Busy tells if a turn runs.
173 func (l *TurnLoop) Busy() bool {
175 defer l.mutex.Unlock()
177 return l.cancel != nil
180 // Append logs a message and tells the clients. The toolbox logs its calls and
181 // results through it.
182 func (l *TurnLoop) Append(kind, text string) (Message, error) {
183 return l.record(kind, "", text)
186 // Flush makes the log durable.
187 func (l *TurnLoop) Flush(ctx context.Context) error {
188 return l.memory.Flush(ctx)
191 // Run runs a turn each time user messages or reports wait, until ctx ends. It
192 // returns the error of a failed log write, which stops the agent. At its start
193 // it resumes the subagents that a stop of the daemon cut, and at its end it
194 // ends the runs of the subagents and waits for them.
195 func (l *TurnLoop) Run(ctx context.Context) error {
198 err := l.runs.Resume(ctx)
200 return fmt.Errorf("resume subagents: %w", err)
224 // note logs a note and tells the clients. A note starts no turn.
225 func (l *TurnLoop) note(text string) error {
226 _, err := l.record("note", "", text)
231 // record logs a message and tells the clients, with the client source of a user
233 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
234 message, err := l.memory.Append(kind, text)
236 return Message{}, err
249 // waiting tells if user messages or reports wait for a request.
250 func (l *TurnLoop) waiting() bool {
252 defer l.mutex.Unlock()
254 return len(l.pending) > 0
257 // fail stops the loop with err.
258 func (l *TurnLoop) fail(err error) {
260 l.failure = errors.Join(l.failure, err)
264 case l.wake <- struct{}{}:
269 // failed returns the error of a failed write of a report.
270 func (l *TurnLoop) failed() error {
272 defer l.mutex.Unlock()
277 // turn runs one turn. A failed or interrupted model call ends the turn and
278 // tells the clients. The messages of the turn stay in the log and the view, and
279 // the next turn starts only with a new message, so a lasting failure such as a
280 // needed login does not repeat. Only a failed log write is an error of turn.
281 func (l *TurnLoop) turn(ctx context.Context) error {
282 ctx, cancel := context.WithCancel(ctx)
300 if err != nil && !errors.Is(err, errChainLogWrite) {
303 Text: turnError(ctx, err),
316 // chain runs the request chain of a turn until the final answer.
317 func (l *TurnLoop) chain(ctx context.Context) error {
319 if len(messages) == 0 {
323 err := l.memory.Wait(ctx)
328 instructions, err := l.agent.Prompt()
333 skip := make(map[int]bool, len(messages))
334 for _, message := range messages {
335 skip[message.ID] = true
338 view, err := l.layout.Split(l.memory.ViewLines(skip))
346 request: ModelRequest{
347 Model: l.agent.config.Model,
348 Effort: l.agent.config.Effort,
349 Instructions: instructions,
350 Tools: promptTools(),
355 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
360 // take returns the user messages that wait for a request, and removes them.
361 func (l *TurnLoop) take() []Message {
363 defer l.mutex.Unlock()
365 messages := l.pending
371 // state returns the per-turn state: the end of the view, and the date and time
373 func (l *TurnLoop) state() string {
374 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
377 // turnError returns the text of the error that ended a turn.
378 func turnError(ctx context.Context, err error) string {
379 if ctx.Err() != nil {
386 // turnInput returns the input of the first request of a turn, stable parts
387 // first: a user message for each view message, one with the per-turn state,
388 // and one for each new message, whole. The view leaves out the leaf lines of
390 func turnInput(view []string, state string, messages []Message) []any {
391 input := make([]any, 0, len(view)+1+len(messages))
392 for _, text := range view {
393 input = append(input, modelUserMessage(text))
396 input = append(input, modelUserMessage(state))
397 for _, message := range messages {
398 input = append(input, modelUserMessage(message.Text))