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{
40 running: make(map[string]*SubagentRun),
48 workdir: agent.config.Workdir,
54 // Event tells the clients what the agent does as it happens. Kind is the kind
55 // of a logged message (user, reply, tool, echo, work), or one of ready, busy,
56 // 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
57 // sent a user message, such as terminal or telegram, so that each client can
58 // show the messages of the others.
60 Kind string `json:"kind"`
61 ID int `json:"id,omitempty"`
62 Text string `json:"text,omitempty"`
63 Source string `json:"source,omitempty"`
66 // TurnLoop runs the turns of one agent. A user message goes to the log when it
67 // comes, and it wakes the loop. A turn waits until every message before it is
68 // summarized. Then the turn runs a Chain whose first request holds the prompt,
69 // the tools, and the input of turnInput.
71 // The view goes out as the messages of a ViewLayout, so the first request of a
72 // turn reads the view of the turn before from the prompt cache. User messages
73 // that come during a turn join the next request of its chain after the tool
74 // results, and so do the reports of the subagents. The subagents run until the
76 type TurnLoop struct {
83 clock func() time.Time
89 cancel context.CancelFunc
93 // Submit logs a user message from the client source and wakes the loop. The
94 // message joins the next request: the first one of a new turn, or the next one
96 func (l *TurnLoop) Submit(source, text string) (Message, error) {
97 message, err := l.record("user", source, text)
103 l.pending = append(l.pending, message)
107 case l.wake <- struct{}{}:
114 // Report logs the report text of a subagent as a work message and tells the
115 // clients. Unless the subagent was stopped, the report joins the waiting
116 // messages and wakes the loop, as a user message of Submit does. A failed write
117 // stops the loop, because the log refuses all writes after it.
118 func (l *TurnLoop) Report(text string, stopped bool) {
119 message, err := l.record("work", "", text)
124 l.failure = fmt.Errorf("%w: %w", errChainLogWrite, err)
126 l.pending = append(l.pending, message)
131 case l.wake <- struct{}{}:
136 // Interrupt ends the running turn. A running tool is killed, and the turn sends
137 // no further request.
138 func (l *TurnLoop) Interrupt() bool {
140 defer l.mutex.Unlock()
151 // Busy tells if a turn runs.
152 func (l *TurnLoop) Busy() bool {
154 defer l.mutex.Unlock()
156 return l.cancel != nil
159 // Append logs a message and tells the clients. The toolbox logs its calls and
160 // results through it.
161 func (l *TurnLoop) Append(kind, text string) (Message, error) {
162 return l.record(kind, "", text)
165 // Flush makes the log durable.
166 func (l *TurnLoop) Flush(ctx context.Context) error {
167 return l.memory.Flush(ctx)
170 // Run runs a turn each time user messages or reports wait, until ctx ends. It
171 // returns the error of a failed log write, which stops the agent. At its end
172 // it ends the runs of the subagents and waits for them.
173 func (l *TurnLoop) Run(ctx context.Context) error {
197 // record logs a message and tells the clients, with the client source of a user
199 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
200 message, err := l.memory.Append(kind, text)
202 return Message{}, err
215 // waiting tells if user messages or reports wait for a request.
216 func (l *TurnLoop) waiting() bool {
218 defer l.mutex.Unlock()
220 return len(l.pending) > 0
223 // failed returns the error of a failed write of a report.
224 func (l *TurnLoop) failed() error {
226 defer l.mutex.Unlock()
231 // turn runs one turn. A failed or interrupted model call ends the turn and
232 // tells the clients. The messages of the turn stay in the log and the view, and
233 // the next turn starts only with a new message, so a lasting failure such as a
234 // needed login does not repeat. Only a failed log write is an error of turn.
235 func (l *TurnLoop) turn(ctx context.Context) error {
236 ctx, cancel := context.WithCancel(ctx)
254 if err != nil && !errors.Is(err, errChainLogWrite) {
257 Text: turnError(ctx, err),
270 // chain runs the request chain of a turn until the final answer.
271 func (l *TurnLoop) chain(ctx context.Context) error {
273 if len(messages) == 0 {
277 err := l.memory.Wait(ctx)
282 instructions, err := l.agent.Prompt()
287 skip := make(map[int]bool, len(messages))
288 for _, message := range messages {
289 skip[message.ID] = true
292 view, err := l.layout.Split(l.memory.ViewLines(skip))
300 request: ModelRequest{
301 Model: l.agent.config.Model,
302 Effort: l.agent.config.Effort,
303 Instructions: instructions,
304 Tools: promptTools(),
309 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
314 // take returns the user messages that wait for a request, and removes them.
315 func (l *TurnLoop) take() []Message {
317 defer l.mutex.Unlock()
319 messages := l.pending
325 // state returns the per-turn state: the end of the view, and the date and time
327 func (l *TurnLoop) state() string {
328 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
331 // turnError returns the text of the error that ended a turn.
332 func turnError(ctx context.Context, err error) string {
333 if ctx.Err() != nil {
340 // turnInput returns the input of the first request of a turn, stable parts
341 // first: a user message for each view message, one with the per-turn state,
342 // and one for each new message, whole. The view leaves out the leaf lines of
344 func turnInput(view []string, state string, messages []Message) []any {
345 input := make([]any, 0, len(view)+1+len(messages))
346 for _, text := range view {
347 input = append(input, modelUserMessage(text))
350 input = append(input, modelUserMessage(state))
351 for _, message := range messages {
352 input = append(input, modelUserMessage(message.Text))