11 // newTurnLoop returns the loop of agent with its memory and its subagents. Its
12 // calls go through client, and notify gets each event. The clock gives the date
14 func newTurnLoop(agent *Agent, memory *Memory, subagents *Subagents, client ChainClient, clock func() time.Time, notify func(Event)) (*TurnLoop, error) {
15 layout, err := loadViewLayout(filepath.Join(agent.dir, viewLayoutFileName))
27 wake: make(chan struct{}, 1),
34 workdir: agent.config.Workdir,
40 // Event tells the clients what the agent does as it happens. Kind is the kind
41 // of a logged message (user, reply, tool, echo), or one of ready, busy, idle,
42 // and error. ID is the ID of a logged message. Source names the client that
43 // sent a user message, such as terminal or telegram, so that each client can
44 // show the messages of the others.
46 Kind string `json:"kind"`
47 ID int `json:"id,omitempty"`
48 Text string `json:"text,omitempty"`
49 Source string `json:"source,omitempty"`
52 // TurnLoop runs the turns of one agent. A user message goes to the log when it
53 // comes, and it wakes the loop. A turn waits until every message before it is
54 // summarized. Then the turn runs a Chain whose first request holds the prompt,
55 // the tools, and the input of turnInput.
57 // The view goes out as the messages of a ViewLayout, so the first request of a
58 // turn reads the view of the turn before from the prompt cache. User messages
59 // that come during a turn join the next request of its chain after the tool
61 type TurnLoop struct {
67 clock func() time.Time
73 cancel context.CancelFunc
76 // Submit logs a user message from the client source and wakes the loop. The
77 // message joins the next request: the first one of a new turn, or the next one
79 func (l *TurnLoop) Submit(source, text string) (Message, error) {
80 message, err := l.record("user", source, text)
86 l.pending = append(l.pending, message)
90 case l.wake <- struct{}{}:
97 // Interrupt ends the running turn. A running tool is killed, and the turn sends
98 // no further request.
99 func (l *TurnLoop) Interrupt() bool {
101 defer l.mutex.Unlock()
112 // Busy tells if a turn runs.
113 func (l *TurnLoop) Busy() bool {
115 defer l.mutex.Unlock()
117 return l.cancel != nil
120 // Append logs a message and tells the clients. The toolbox logs its calls and
121 // results through it.
122 func (l *TurnLoop) Append(kind, text string) (Message, error) {
123 return l.record(kind, "", text)
126 // Flush makes the log durable.
127 func (l *TurnLoop) Flush(ctx context.Context) error {
128 return l.memory.Flush(ctx)
131 // Run runs a turn each time user messages wait, until ctx ends. It returns the
132 // error of a failed log write, which stops the agent.
133 func (l *TurnLoop) Run(ctx context.Context) error {
150 // record logs a message and tells the clients, with the client source of a user
152 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
153 message, err := l.memory.Append(kind, text)
155 return Message{}, err
168 // waiting tells if user messages wait for a request.
169 func (l *TurnLoop) waiting() bool {
171 defer l.mutex.Unlock()
173 return len(l.pending) > 0
176 // turn runs one turn. A failed or interrupted model call ends the turn and
177 // tells the clients. The messages of the turn stay in the log and the view, and
178 // the next turn starts only with a new message, so a lasting failure such as a
179 // needed login does not repeat. Only a failed log write is an error of turn.
180 func (l *TurnLoop) turn(ctx context.Context) error {
181 ctx, cancel := context.WithCancel(ctx)
199 if err != nil && !errors.Is(err, errChainLogWrite) {
202 Text: turnError(ctx, err),
215 // chain runs the request chain of a turn until the final answer.
216 func (l *TurnLoop) chain(ctx context.Context) error {
218 if len(messages) == 0 {
222 err := l.memory.Wait(ctx)
227 instructions, err := l.agent.Prompt()
232 skip := make(map[int]bool, len(messages))
233 for _, message := range messages {
234 skip[message.ID] = true
237 view, err := l.layout.Split(l.memory.ViewLines(skip))
245 request: ModelRequest{
246 Model: l.agent.config.Model,
247 Effort: l.agent.config.Effort,
248 Instructions: instructions,
249 Tools: promptTools(),
254 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
259 // take returns the user messages that wait for a request, and removes them.
260 func (l *TurnLoop) take() []Message {
262 defer l.mutex.Unlock()
264 messages := l.pending
270 // state returns the per-turn state: the end of the view, and the date and time
272 func (l *TurnLoop) state() string {
273 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
276 // turnError returns the text of the error that ended a turn.
277 func turnError(ctx context.Context, err error) string {
278 if ctx.Err() != nil {
285 // turnInput returns the input of the first request of a turn, stable parts
286 // first: a user message for each view message, one with the per-turn state,
287 // and one for each new message, whole. The view leaves out the leaf lines of
289 func turnInput(view []string, state string, messages []Message) []any {
290 input := make([]any, 0, len(view)+1+len(messages))
291 for _, text := range view {
292 input = append(input, modelUserMessage(text))
295 input = append(input, modelUserMessage(state))
296 for _, message := range messages {
297 input = append(input, modelUserMessage(message.Text))