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, note, work), or one of ready,
57 // busy, idle, error, and subagent, which tells that the subagent Text starts a
58 // run. ID is the ID of a logged message. Source names the client that sent a
59 // user message, such as terminal or telegram, so that each client can show the
60 // messages of the others, or the subagent of a report. Status tells how the run
61 // of a report ended: finished, stopped, or failed.
63 Kind string `json:"kind"`
64 ID int `json:"id,omitempty"`
65 Text string `json:"text,omitempty"`
66 Source string `json:"source,omitempty"`
67 Status string `json:"status,omitempty"`
70 // TurnLoop runs the turns of one agent. A user message goes to the log when it
71 // comes, and it wakes the loop. A turn waits until every message before it is
72 // summarized. Then the turn runs a Chain whose first request holds the prompt,
73 // the tools, and the input of turnInput.
75 // The view goes out as the messages of a ViewLayout, so the first request of a
76 // turn reads the view of the turn before from the prompt cache. User messages
77 // that come during a turn join the next request of its chain after the tool
78 // results, and so do the reports of the subagents. The subagents run until the
80 type TurnLoop struct {
87 clock func() time.Time
93 cancel context.CancelFunc
97 // Submit logs a user message from the client source and wakes the loop. The
98 // message joins the next request: the first one of a new turn, or the next one
100 func (l *TurnLoop) Submit(source, text string) (Message, error) {
101 message, err := l.record("user", source, text)
103 return Message{}, err
107 l.pending = append(l.pending, message)
111 case l.wake <- struct{}{}:
118 // Report logs the report text of the subagent name as a work message and tells
119 // the clients, with the status of the run. Unless the subagent was stopped, the
120 // report joins the waiting messages and wakes the loop, as a user message of
121 // Submit does. A failed write stops the loop, because the log refuses all
123 func (l *TurnLoop) Report(name, text, status string) {
124 message, err := l.memory.Append("work", text)
138 l.failure = fmt.Errorf("%w: %w", errChainLogWrite, err)
139 case status != subagentStopped:
140 l.pending = append(l.pending, message)
145 case l.wake <- struct{}{}:
150 // StopSubagent ends the run of the subagent name and tells if it ran. Its
151 // report is logged, but it starts no turn.
152 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
153 return l.runs.Stop(name)
156 // Interrupt ends the running turn. A running tool is killed, and the turn sends
157 // no further request.
158 func (l *TurnLoop) Interrupt() bool {
160 defer l.mutex.Unlock()
171 // Busy tells if a turn runs.
172 func (l *TurnLoop) Busy() bool {
174 defer l.mutex.Unlock()
176 return l.cancel != nil
179 // Append logs a message and tells the clients. The toolbox logs its calls and
180 // results through it.
181 func (l *TurnLoop) Append(kind, text string) (Message, error) {
182 return l.record(kind, "", text)
185 // Flush makes the log durable.
186 func (l *TurnLoop) Flush(ctx context.Context) error {
187 return l.memory.Flush(ctx)
190 // Run runs a turn each time user messages or reports wait, until ctx ends. It
191 // returns the error of a failed log write, which stops the agent. At its end
192 // it ends the runs of the subagents and waits for them.
193 func (l *TurnLoop) Run(ctx context.Context) error {
217 // note logs a note and tells the clients. A note starts no turn.
218 func (l *TurnLoop) note(text string) error {
219 _, err := l.record("note", "", text)
224 // record logs a message and tells the clients, with the client source of a user
226 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
227 message, err := l.memory.Append(kind, text)
229 return Message{}, err
242 // waiting tells if user messages or reports wait for a request.
243 func (l *TurnLoop) waiting() bool {
245 defer l.mutex.Unlock()
247 return len(l.pending) > 0
250 // failed returns the error of a failed write of a report.
251 func (l *TurnLoop) failed() error {
253 defer l.mutex.Unlock()
258 // turn runs one turn. A failed or interrupted model call ends the turn and
259 // tells the clients. The messages of the turn stay in the log and the view, and
260 // the next turn starts only with a new message, so a lasting failure such as a
261 // needed login does not repeat. Only a failed log write is an error of turn.
262 func (l *TurnLoop) turn(ctx context.Context) error {
263 ctx, cancel := context.WithCancel(ctx)
281 if err != nil && !errors.Is(err, errChainLogWrite) {
284 Text: turnError(ctx, err),
297 // chain runs the request chain of a turn until the final answer.
298 func (l *TurnLoop) chain(ctx context.Context) error {
300 if len(messages) == 0 {
304 err := l.memory.Wait(ctx)
309 instructions, err := l.agent.Prompt()
314 skip := make(map[int]bool, len(messages))
315 for _, message := range messages {
316 skip[message.ID] = true
319 view, err := l.layout.Split(l.memory.ViewLines(skip))
327 request: ModelRequest{
328 Model: l.agent.config.Model,
329 Effort: l.agent.config.Effort,
330 Instructions: instructions,
331 Tools: promptTools(),
336 _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
341 // take returns the user messages that wait for a request, and removes them.
342 func (l *TurnLoop) take() []Message {
344 defer l.mutex.Unlock()
346 messages := l.pending
352 // state returns the per-turn state: the end of the view, and the date and time
354 func (l *TurnLoop) state() string {
355 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
358 // turnError returns the text of the error that ended a turn.
359 func turnError(ctx context.Context, err error) string {
360 if ctx.Err() != nil {
367 // turnInput returns the input of the first request of a turn, stable parts
368 // first: a user message for each view message, one with the per-turn state,
369 // and one for each new message, whole. The view leaves out the leaf lines of
371 func turnInput(view []string, state string, messages []Message) []any {
372 input := make([]any, 0, len(view)+1+len(messages))
373 for _, text := range view {
374 input = append(input, modelUserMessage(text))
377 input = append(input, modelUserMessage(state))
378 for _, message := range messages {
379 input = append(input, modelUserMessage(message.Text))