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{
41 running: make(map[string]*SubagentRun),
49 workdir: agent.config.Workdir,
55 // Event tells the clients what the agent does as it happens. Kind is the kind
56 // of a logged message (user, reply, tool, echo, work), or one of ready, busy,
57 // idle, error, and subagent, which tells that the subagent Text starts a run. ID is the ID of a logged message. Source names the client that
58 // sent a user message, such as terminal or telegram, so that each client can
59 // show the messages of the others.
61 Kind string `json:"kind"`
62 ID int `json:"id,omitempty"`
63 Text string `json:"text,omitempty"`
64 Source string `json:"source,omitempty"`
67 // TurnLoop runs the turns of one agent. A user message goes to the log when it
68 // comes, and it wakes the loop. A turn waits until every message before it is
69 // summarized. Then the turn runs a Chain whose first request holds the prompt,
70 // the tools, and the input of turnInput.
72 // The view goes out as the messages of a ViewLayout, so the first request of a
73 // turn reads the view of the turn before from the prompt cache. User messages
74 // that come during a turn join the next request of its chain after the tool
75 // results, and so do the reports of the subagents. The subagents run until the
77 type TurnLoop struct {
84 clock func() time.Time
90 cancel context.CancelFunc
94 // Submit logs a user message from the client source and wakes the loop. The
95 // message joins the next request: the first one of a new turn, or the next one
97 func (l *TurnLoop) Submit(source, text string) (Message, error) {
98 message, err := l.record("user", source, text)
100 return Message{}, err
104 l.pending = append(l.pending, message)
108 case l.wake <- struct{}{}:
115 // Report logs the report text of a subagent as a work message and tells the
116 // clients. Unless the subagent was stopped, the report joins the waiting
117 // messages and wakes the loop, as a user message of Submit does. A failed write
118 // stops the loop, because the log refuses all writes after it.
119 func (l *TurnLoop) Report(text string, stopped bool) {
120 message, err := l.record("work", "", text)
125 l.failure = fmt.Errorf("%w: %w", errChainLogWrite, err)
127 l.pending = append(l.pending, message)
132 case l.wake <- struct{}{}:
137 // StopSubagent ends the run of the subagent name and tells if it ran. Its
138 // report is logged, but it starts no turn.
139 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
140 return l.runs.Stop(name)
143 // Interrupt ends the running turn. A running tool is killed, and the turn sends
144 // no further request.
145 func (l *TurnLoop) Interrupt() bool {
147 defer l.mutex.Unlock()
158 // Busy tells if a turn runs.
159 func (l *TurnLoop) Busy() bool {
161 defer l.mutex.Unlock()
163 return l.cancel != nil
166 // Append logs a message and tells the clients. The toolbox logs its calls and
167 // results through it.
168 func (l *TurnLoop) Append(kind, text string) (Message, error) {
169 return l.record(kind, "", text)
172 // Flush makes the log durable.
173 func (l *TurnLoop) Flush(ctx context.Context) error {
174 return l.memory.Flush(ctx)
177 // Run runs a turn each time user messages or reports wait, until ctx ends. It
178 // returns the error of a failed log write, which stops the agent. At its end
179 // it ends the runs of the subagents and waits for them.
180 func (l *TurnLoop) Run(ctx context.Context) error {
204 // note logs a note and tells the clients. A note starts no turn.
205 func (l *TurnLoop) note(text string) error {
206 _, err := l.record("note", "", text)
211 // record logs a message and tells the clients, with the client source of a user
213 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
214 message, err := l.memory.Append(kind, text)
216 return Message{}, err
229 // waiting tells if user messages or reports wait for a request.
230 func (l *TurnLoop) waiting() bool {
232 defer l.mutex.Unlock()
234 return len(l.pending) > 0
237 // failed returns the error of a failed write of a report.
238 func (l *TurnLoop) failed() error {
240 defer l.mutex.Unlock()
245 // turn runs one turn. A failed or interrupted model call ends the turn and
246 // tells the clients. The messages of the turn stay in the log and the view, and
247 // the next turn starts only with a new message, so a lasting failure such as a
248 // needed login does not repeat. Only a failed log write is an error of turn.
249 func (l *TurnLoop) turn(ctx context.Context) error {
250 ctx, cancel := context.WithCancel(ctx)
268 if err != nil && !errors.Is(err, errChainLogWrite) {
271 Text: turnError(ctx, err),
284 // chain runs the request chain of a turn until the final answer.
285 func (l *TurnLoop) chain(ctx context.Context) error {
287 if len(messages) == 0 {
291 err := l.memory.Wait(ctx)
296 instructions, err := l.agent.Prompt()
301 skip := make(map[int]bool, len(messages))
302 for _, message := range messages {
303 skip[message.ID] = true
306 view, err := l.layout.Split(l.memory.ViewLines(skip))
314 request: ModelRequest{
315 Model: l.agent.config.Model,
316 Effort: l.agent.config.Effort,
317 Instructions: instructions,
318 Tools: promptTools(),
323 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
328 // take returns the user messages that wait for a request, and removes them.
329 func (l *TurnLoop) take() []Message {
331 defer l.mutex.Unlock()
333 messages := l.pending
339 // state returns the per-turn state: the end of the view, and the date and time
341 func (l *TurnLoop) state() string {
342 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
345 // turnError returns the text of the error that ended a turn.
346 func turnError(ctx context.Context, err error) string {
347 if ctx.Err() != nil {
354 // turnInput returns the input of the first request of a turn, stable parts
355 // first: a user message for each view message, one with the per-turn state,
356 // and one for each new message, whole. The view leaves out the leaf lines of
358 func turnInput(view []string, state string, messages []Message) []any {
359 input := make([]any, 0, len(view)+1+len(messages))
360 for _, text := range view {
361 input = append(input, modelUserMessage(text))
364 input = append(input, modelUserMessage(state))
365 for _, message := range messages {
366 input = append(input, modelUserMessage(message.Text))