11 // newTurnLoop returns the loop of agent with its memory. Its calls go through
12 // client, and notify gets each event. The clock gives the date of a turn.
13 func newTurnLoop(agent *Agent, memory *Memory, client ChainClient, clock func() time.Time, notify func(Event)) (*TurnLoop, error) {
14 layout, err := loadViewLayout(filepath.Join(agent.dir, viewLayoutFileName))
26 wake: make(chan struct{}, 1),
32 workdir: agent.config.Workdir,
38 // Event tells the clients what the agent does as it happens. Kind is the kind
39 // of a logged message (user, reply, tool, echo), or one of ready, busy, idle,
40 // and error. ID is the ID of a logged message. Source names the client that
41 // sent a user message, such as terminal or telegram, so that each client can
42 // show the messages of the others.
44 Kind string `json:"kind"`
45 ID int `json:"id,omitempty"`
46 Text string `json:"text,omitempty"`
47 Source string `json:"source,omitempty"`
50 // TurnLoop runs the turns of one agent. A user message goes to the log when it
51 // comes, and it wakes the loop. A turn waits until every message before it is
52 // summarized. Then the turn runs a Chain whose first request holds the prompt,
53 // the tools, and the input of turnInput.
55 // The view goes out as the messages of a ViewLayout, so the first request of a
56 // turn reads the view of the turn before from the prompt cache. User messages
57 // that come during a turn join the next request of its chain after the tool
59 type TurnLoop struct {
65 clock func() time.Time
71 cancel context.CancelFunc
74 // Submit logs a user message from the client source and wakes the loop. The
75 // message joins the next request: the first one of a new turn, or the next one
77 func (l *TurnLoop) Submit(source, text string) (Message, error) {
78 message, err := l.record("user", source, text)
84 l.pending = append(l.pending, message)
88 case l.wake <- struct{}{}:
95 // Interrupt ends the running turn. A running tool is killed, and the turn sends
96 // no further request.
97 func (l *TurnLoop) Interrupt() bool {
99 defer l.mutex.Unlock()
110 // Busy tells if a turn runs.
111 func (l *TurnLoop) Busy() bool {
113 defer l.mutex.Unlock()
115 return l.cancel != nil
118 // Append logs a message and tells the clients. The toolbox logs its calls and
119 // results through it.
120 func (l *TurnLoop) Append(kind, text string) (Message, error) {
121 return l.record(kind, "", text)
124 // Flush makes the log durable.
125 func (l *TurnLoop) Flush(ctx context.Context) error {
126 return l.memory.Flush(ctx)
129 // Run runs a turn each time user messages wait, until ctx ends. It returns the
130 // error of a failed log write, which stops the agent.
131 func (l *TurnLoop) Run(ctx context.Context) error {
148 // record logs a message and tells the clients, with the client source of a user
150 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
151 message, err := l.memory.Append(kind, text)
153 return Message{}, err
166 // waiting tells if user messages wait for a request.
167 func (l *TurnLoop) waiting() bool {
169 defer l.mutex.Unlock()
171 return len(l.pending) > 0
174 // turn runs one turn. A failed or interrupted model call ends the turn and
175 // tells the clients. The messages of the turn stay in the log and the view, and
176 // the next turn starts only with a new message, so a lasting failure such as a
177 // needed login does not repeat. Only a failed log write is an error of turn.
178 func (l *TurnLoop) turn(ctx context.Context) error {
179 ctx, cancel := context.WithCancel(ctx)
197 if err != nil && !errors.Is(err, errChainLogWrite) {
200 Text: turnError(ctx, err),
213 // chain runs the request chain of a turn until the final answer.
214 func (l *TurnLoop) chain(ctx context.Context) error {
216 if len(messages) == 0 {
220 err := l.memory.Wait(ctx)
225 instructions, err := l.agent.Prompt()
230 skip := make(map[int]bool, len(messages))
231 for _, message := range messages {
232 skip[message.ID] = true
235 view, err := l.layout.Split(l.memory.ViewLines(skip))
243 request: ModelRequest{
244 Model: l.agent.config.Model,
245 Effort: l.agent.config.Effort,
246 Instructions: instructions,
247 Tools: promptTools(),
252 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
257 // take returns the user messages that wait for a request, and removes them.
258 func (l *TurnLoop) take() []Message {
260 defer l.mutex.Unlock()
262 messages := l.pending
268 // state returns the per-turn state: the end of the view, and the date and time
270 func (l *TurnLoop) state() string {
271 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
274 // turnError returns the text of the error that ended a turn.
275 func turnError(ctx context.Context, err error) string {
276 if ctx.Err() != nil {
283 // turnInput returns the input of the first request of a turn, stable parts
284 // first: a user message for each view message, one with the per-turn state,
285 // and one for each new message, whole. The view leaves out the leaf lines of
287 func turnInput(view []string, state string, messages []Message) []any {
288 input := make([]any, 0, len(view)+1+len(messages))
289 for _, text := range view {
290 input = append(input, modelUserMessage(text))
293 input = append(input, modelUserMessage(state))
294 for _, message := range messages {
295 input = append(input, modelUserMessage(message.Text))