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