]> git.giacomolli.uk - onechat/blob - turn.go
Give the WhatsApp batches to the agent
[onechat] / turn.go
1 package main
2
3 import (
4         "context"
5         "errors"
6         "fmt"
7         "path/filepath"
8         "sync"
9         "time"
10 )
11
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
14 // of a turn.
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))
17         if err != nil {
18                 return nil, err
19         }
20
21         l := &TurnLoop{
22                 agent:  agent,
23                 memory: memory,
24                 client: client,
25                 layout: layout,
26                 clock:  clock,
27                 notify: notify,
28                 wake:   make(chan struct{}, 1),
29         }
30
31         l.runs = &SubagentRuns{
32                 agent:     agent,
33                 memory:    memory,
34                 subagents: subagents,
35                 layout:    layout,
36                 client:    client,
37                 state:     l.state,
38                 report:    l.Report,
39                 note:      l.note,
40                 fail:      l.fail,
41                 notify:    notify,
42                 running:   make(map[string]*SubagentRun),
43         }
44
45         l.tools = &Toolbox{
46                 log:       l,
47                 chat:      memory,
48                 subagents: subagents,
49                 runs:      l.runs,
50                 workdir:   agent.config.Workdir,
51         }
52
53         return l, nil
54 }
55
56 // Event tells the clients what the agent does as it happens. Kind is the kind
57 // of a logged message (user, reply, tool, echo, note, work), or one of ready,
58 // busy, idle, error, and subagent, which tells that the subagent Text starts a
59 // run. ID is the ID of a logged message. Source names the client that sent a
60 // user message, such as terminal or telegram, so that each client can show the
61 // messages of the others, or the subagent of a report. Status tells how the run
62 // of a report ended: finished, stopped, or failed.
63 type Event struct {
64         Kind   string `json:"kind"`
65         ID     int    `json:"id,omitempty"`
66         Text   string `json:"text,omitempty"`
67         Source string `json:"source,omitempty"`
68         Status string `json:"status,omitempty"`
69 }
70
71 // TurnLoop runs the turns of one agent. A user message goes to the log when it
72 // comes, and it wakes the loop. A turn waits until every message before it is
73 // summarized. Then the turn runs a Chain whose first request holds the prompt,
74 // the tools, and the input of turnInput.
75 //
76 // The view goes out as the messages of a ViewLayout, so the first request of a
77 // turn reads the view of the turn before from the prompt cache. User messages
78 // that come during a turn join the next request of its chain after the tool
79 // results, and so do the reports of the subagents. The subagents run until the
80 // loop ends.
81 type TurnLoop struct {
82         agent  *Agent
83         memory *Memory
84         client ChainClient
85         tools  *Toolbox
86         runs   *SubagentRuns
87         layout *ViewLayout
88         clock  func() time.Time
89         notify func(Event)
90         wake   chan struct{}
91
92         mutex   sync.Mutex
93         pending []Message
94         cancel  context.CancelFunc
95         failure error
96 }
97
98 // Submit logs a user message from the client source and wakes the loop. The
99 // message joins the next request: the first one of a new turn, or the next one
100 // of a running turn.
101 func (l *TurnLoop) Submit(source, text string) (Message, error) {
102         message, err := l.record("user", source, text)
103         if err != nil {
104                 return Message{}, err
105         }
106
107         l.mutex.Lock()
108         l.pending = append(l.pending, message)
109         l.mutex.Unlock()
110
111         select {
112         case l.wake <- struct{}{}:
113         default:
114         }
115
116         return message, nil
117 }
118
119 // Report logs the report text of the subagent name as a work message and tells
120 // the clients, with the status of the run. Unless the subagent was stopped, the
121 // report joins the waiting messages and wakes the loop, as a user message of
122 // Submit does. A failed write stops the loop, because the log refuses all
123 // writes after it.
124 func (l *TurnLoop) Report(name, text, status string) {
125         _, err := l.Work(name, text, status, status != subagentStopped)
126         if err != nil {
127                 l.fail(fmt.Errorf("%w: %w", errChainLogWrite, err))
128         }
129 }
130
131 // Work logs text as a work message of source, such as the name of a subagent,
132 // and tells the clients, with status. With wake, the message joins the waiting
133 // messages and wakes the loop, as a user message of Submit does: it joins the
134 // first request of a new turn, or the next request of a running turn after the
135 // tool results.
136 func (l *TurnLoop) Work(source, text, status string, wake bool) (Message, error) {
137         message, err := l.memory.Append("work", text)
138         if err != nil {
139                 return Message{}, err
140         }
141
142         l.notify(Event{
143                 Kind:   "work",
144                 ID:     message.ID,
145                 Text:   text,
146                 Source: source,
147                 Status: status,
148         })
149
150         if !wake {
151                 return message, nil
152         }
153
154         l.mutex.Lock()
155         l.pending = append(l.pending, message)
156         l.mutex.Unlock()
157
158         select {
159         case l.wake <- struct{}{}:
160         default:
161         }
162
163         return message, nil
164 }
165
166 // StopSubagent ends the run of the subagent name and tells if it ran. Its
167 // report is logged, but it starts no turn.
168 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
169         return l.runs.Stop(name)
170 }
171
172 // Interrupt ends the running turn. A running tool is killed, and the turn sends
173 // no further request.
174 func (l *TurnLoop) Interrupt() bool {
175         l.mutex.Lock()
176         defer l.mutex.Unlock()
177
178         if l.cancel == nil {
179                 return false
180         }
181
182         l.cancel()
183
184         return true
185 }
186
187 // Busy tells if a turn runs.
188 func (l *TurnLoop) Busy() bool {
189         l.mutex.Lock()
190         defer l.mutex.Unlock()
191
192         return l.cancel != nil
193 }
194
195 // Append logs a message and tells the clients. The toolbox logs its calls and
196 // results through it.
197 func (l *TurnLoop) Append(kind, text string) (Message, error) {
198         return l.record(kind, "", text)
199 }
200
201 // Flush makes the log durable.
202 func (l *TurnLoop) Flush(ctx context.Context) error {
203         return l.memory.Flush(ctx)
204 }
205
206 // Run runs a turn each time user messages or reports wait, until ctx ends. It
207 // returns the error of a failed log write, which stops the agent. At its start
208 // it resumes the subagents that a stop of the daemon cut, and at its end it
209 // ends the runs of the subagents and waits for them.
210 func (l *TurnLoop) Run(ctx context.Context) error {
211         defer l.runs.Close()
212
213         err := l.runs.Resume(ctx)
214         if err != nil {
215                 return fmt.Errorf("resume subagents: %w", err)
216         }
217
218         for {
219                 for l.waiting() {
220                         err := l.turn(ctx)
221                         if err != nil {
222                                 return err
223                         }
224                 }
225
226                 select {
227                 case <-l.wake:
228                 case <-ctx.Done():
229                         return ctx.Err()
230                 }
231
232                 err := l.failed()
233                 if err != nil {
234                         return err
235                 }
236         }
237 }
238
239 // note logs a note and tells the clients. A note starts no turn.
240 func (l *TurnLoop) note(text string) error {
241         _, err := l.record("note", "", text)
242
243         return err
244 }
245
246 // record logs a message and tells the clients, with the client source of a user
247 // message.
248 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
249         message, err := l.memory.Append(kind, text)
250         if err != nil {
251                 return Message{}, err
252         }
253
254         l.notify(Event{
255                 Kind:   kind,
256                 ID:     message.ID,
257                 Text:   text,
258                 Source: source,
259         })
260
261         return message, nil
262 }
263
264 // waiting tells if user messages or reports wait for a request.
265 func (l *TurnLoop) waiting() bool {
266         l.mutex.Lock()
267         defer l.mutex.Unlock()
268
269         return len(l.pending) > 0
270 }
271
272 // fail stops the loop with err.
273 func (l *TurnLoop) fail(err error) {
274         l.mutex.Lock()
275         l.failure = errors.Join(l.failure, err)
276         l.mutex.Unlock()
277
278         select {
279         case l.wake <- struct{}{}:
280         default:
281         }
282 }
283
284 // failed returns the error of a failed write of a report.
285 func (l *TurnLoop) failed() error {
286         l.mutex.Lock()
287         defer l.mutex.Unlock()
288
289         return l.failure
290 }
291
292 // turn runs one turn. A failed or interrupted model call ends the turn and
293 // tells the clients. The messages of the turn stay in the log and the view, and
294 // the next turn starts only with a new message, so a lasting failure such as a
295 // needed login does not repeat. Only a failed log write is an error of turn.
296 func (l *TurnLoop) turn(ctx context.Context) error {
297         ctx, cancel := context.WithCancel(ctx)
298         defer cancel()
299
300         l.mutex.Lock()
301         l.cancel = cancel
302         l.mutex.Unlock()
303
304         defer func() {
305                 l.mutex.Lock()
306                 l.cancel = nil
307                 l.mutex.Unlock()
308         }()
309
310         l.notify(Event{
311                 Kind: "busy",
312         })
313
314         err := l.chain(ctx)
315         if err != nil && !errors.Is(err, errChainLogWrite) {
316                 l.notify(Event{
317                         Kind: "error",
318                         Text: turnError(ctx, err),
319                 })
320
321                 err = nil
322         }
323
324         l.notify(Event{
325                 Kind: "idle",
326         })
327
328         return err
329 }
330
331 // chain runs the request chain of a turn until the final answer.
332 func (l *TurnLoop) chain(ctx context.Context) error {
333         messages := l.take()
334         if len(messages) == 0 {
335                 return nil
336         }
337
338         err := l.memory.Wait(ctx)
339         if err != nil {
340                 return err
341         }
342
343         instructions, err := l.agent.Prompt()
344         if err != nil {
345                 return err
346         }
347
348         skip := make(map[int]bool, len(messages))
349         for _, message := range messages {
350                 skip[message.ID] = true
351         }
352
353         view, err := l.layout.Split(l.memory.ViewLines(skip))
354         if err != nil {
355                 return err
356         }
357
358         chain := &Chain{
359                 client: l.client,
360                 tools:  l.tools,
361                 request: ModelRequest{
362                         Model:        l.agent.config.Model,
363                         Effort:       l.agent.config.Effort,
364                         Instructions: instructions,
365                         Tools:        promptTools(),
366                 },
367                 take: l.take,
368         }
369
370         _, err = chain.Run(ctx, turnInput(view, l.state(), messages))
371
372         return err
373 }
374
375 // take returns the user messages that wait for a request, and removes them.
376 func (l *TurnLoop) take() []Message {
377         l.mutex.Lock()
378         defer l.mutex.Unlock()
379
380         messages := l.pending
381         l.pending = nil
382
383         return messages
384 }
385
386 // state returns the per-turn state: the end of the view, and the date and time
387 // of the turn.
388 func (l *TurnLoop) state() string {
389         return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
390 }
391
392 // turnError returns the text of the error that ended a turn.
393 func turnError(ctx context.Context, err error) string {
394         if ctx.Err() != nil {
395                 return "interrupted"
396         }
397
398         return err.Error()
399 }
400
401 // turnInput returns the input of the first request of a turn, stable parts
402 // first: a user message for each view message, one with the per-turn state,
403 // and one for each new message, whole. The view leaves out the leaf lines of
404 // the new messages.
405 func turnInput(view []string, state string, messages []Message) []any {
406         input := make([]any, 0, len(view)+1+len(messages))
407         for _, text := range view {
408                 input = append(input, modelUserMessage(text))
409         }
410
411         input = append(input, modelUserMessage(state))
412         for _, message := range messages {
413                 input = append(input, modelUserMessage(message.Text))
414         }
415
416         return input
417 }